1 /*
2 * tls.c
3 *
4 * Version: $Id: 4149a473a9ace8cddc67d4280d630f0098ef8a96 $
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 *
20 * Copyright 2001 hereUare Communications, Inc. <raghud@hereuare.com>
21 * Copyright 2003 Alan DeKok <aland@freeradius.org>
22 * Copyright 2006 The FreeRADIUS server project
23 */
24
25 RCSID("$Id: 4149a473a9ace8cddc67d4280d630f0098ef8a96 $")
26 USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/modules.h>
31 #include <freeradius-devel/rad_assert.h>
32
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36
37 #ifdef HAVE_FCNTL_H
38 #include <fcntl.h>
39 #endif
40
41 #ifdef HAVE_DIRENT_H
42 #include <dirent.h>
43 #endif
44
45 #ifdef HAVE_UTIME_H
46 #include <utime.h>
47 #endif
48 #include <ctype.h>
49
50 #ifdef WITH_TLS
51 # ifdef HAVE_OPENSSL_RAND_H
52 # include <openssl/rand.h>
53 # endif
54
55 # ifdef HAVE_OPENSSL_OCSP_H
56 # include <openssl/ocsp.h>
57 # endif
58
59 # ifdef HAVE_OPENSSL_EVP_H
60 # include <openssl/evp.h>
61 # endif
62 # include <openssl/ssl.h>
63
64 #define LOG_PREFIX "tls"
65
66 #ifdef ENABLE_OPENSSL_VERSION_CHECK
67 typedef struct libssl_defect {
68 uint64_t high;
69 uint64_t low;
70
71 char const *id;
72 char const *name;
73 char const *comment;
74 } libssl_defect_t;
75
76 /* Record critical defects in libssl here, new versions of OpenSSL to older versions of OpenSSL. */
77 static libssl_defect_t libssl_defects[] =
78 {
79 {
80 .low = 0x01010001f, /* 1.1.0a */
81 .high = 0x01010001f, /* 1.1.0a */
82 .id = "CVE-2016-6309",
83 .name = "OCSP status request extension",
84 .comment = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
85 },
86 {
87 .low = 0x01010000f, /* 1.1.0 */
88 .high = 0x01010000f, /* 1.1.0 */
89 .id = "CVE-2016-6304",
90 .name = "OCSP status request extension",
91 .comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
92 },
93 {
94 .low = 0x01000209f, /* 1.0.2i */
95 .high = 0x01000209f, /* 1.0.2i */
96 .id = "CVE-2016-7052",
97 .name = "OCSP status request extension",
98 .comment = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
99 },
100 {
101 .low = 0x01000200f, /* 1.0.2 */
102 .high = 0x01000208f, /* 1.0.2h */
103 .id = "CVE-2016-6304",
104 .name = "OCSP status request extension",
105 .comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
106 },
107 {
108 .low = 0x01000100f, /* 1.0.1 */
109 .high = 0x01000114f, /* 1.0.1t */
110 .id = "CVE-2016-6304",
111 .name = "OCSP status request extension",
112 .comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
113 },
114 {
115 .low = 0x010001000, /* 1.0.1 */
116 .high = 0x01000106f, /* 1.0.1f */
117 .id = "CVE-2014-0160",
118 .name = "Heartbleed",
119 .comment = "For more information see http://heartbleed.com"
120 },
121 };
122 #endif /* ENABLE_OPENSSL_VERSION_CHECK */
123
124 FR_NAME_NUMBER const fr_tls_status_table[] = {
125 { "invalid", FR_TLS_INVALID },
126 { "request", FR_TLS_REQUEST },
127 { "response", FR_TLS_RESPONSE },
128 { "success", FR_TLS_SUCCESS },
129 { "fail", FR_TLS_FAIL },
130 { "noop", FR_TLS_NOOP },
131
132 { "start", FR_TLS_START },
133 { "ok", FR_TLS_OK },
134 { "ack", FR_TLS_ACK },
135 { "first fragment", FR_TLS_FIRST_FRAGMENT },
136 { "more fragments", FR_TLS_MORE_FRAGMENTS },
137 { "length included", FR_TLS_LENGTH_INCLUDED },
138 { "more fragments with length", FR_TLS_MORE_FRAGMENTS_WITH_LENGTH },
139 { "handled", FR_TLS_HANDLED },
140 { NULL , -1},
141 };
142
143 /* index we use to store cached session VPs
144 * needs to be dynamic so we can supply a "free" function
145 */
146 int fr_tls_ex_index_vps = -1;
147 int fr_tls_ex_index_certs = -1;
148
149 /* Session */
150 static void session_close(tls_session_t *ssn);
151 static void session_init(tls_session_t *ssn);
152
153 /* record */
154 static void record_init(record_t *buf);
155 static void record_close(record_t *buf);
156 static unsigned int record_plus(record_t *buf, void const *ptr,
157 unsigned int size);
158 static unsigned int record_minus(record_t *buf, void *ptr,
159 unsigned int size);
160
161 typedef struct {
162 char const *name;
163 SSL_CTX *ctx;
164 } fr_realm_ctx_t;
165
166 DIAG_OFF(format-nonliteral)
167 /** Print errors in the TLS thread local error stack
168 *
169 * Drains the thread local OpenSSL error queue, and prints out errors.
170 *
171 * @param[in] request The current request (may be NULL).
172 * @param[in] msg Error message describing the operation being attempted.
173 * @param[in] ap Arguments for msg.
174 * @return the number of errors drained from the stack.
175 */
tls_verror_log(REQUEST * request,char const * msg,va_list ap)176 static int tls_verror_log(REQUEST *request, char const *msg, va_list ap)
177 {
178 unsigned long error;
179 char *p;
180 int in_stack = 0;
181 char buffer[256];
182
183 int line;
184 char const *file;
185
186 /*
187 * Pop the first error, so ERR_peek_error()
188 * can be used to determine if there are
189 * multiple errors.
190 */
191 error = ERR_get_error_line(&file, &line);
192
193 if (msg) {
194 p = talloc_vasprintf(request, msg, ap);
195
196 /*
197 * Single line mode (there's only one error)
198 */
199 if (error && !ERR_peek_error()) {
200 ERR_error_string_n(error, buffer, sizeof(buffer));
201
202 /* Extra verbose */
203 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
204 ROPTIONAL(REDEBUG, ERROR, "(TLS) %s: %s[%i]:%s", p, file, line, buffer);
205 } else {
206 ROPTIONAL(REDEBUG, ERROR, "(TLS) %s: %s", p, buffer);
207 }
208
209 talloc_free(p);
210
211 return 1;
212 }
213
214 /*
215 * Print the error we were given, irrespective
216 * of whether there were any OpenSSL errors.
217 */
218 ROPTIONAL(RERROR, ERROR, "(TLS) %s", p);
219 talloc_free(p);
220 }
221
222 /*
223 * Stack mode (there are multiple errors)
224 */
225 if (!error) return 0;
226 do {
227 ERR_error_string_n(error, buffer, sizeof(buffer));
228 /* Extra verbose */
229 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
230 ROPTIONAL(REDEBUG, ERROR, "(TLS) %s[%i]:%s", file, line, buffer);
231 } else {
232 ROPTIONAL(REDEBUG, ERROR, "(TLS) %s", buffer);
233 }
234 in_stack++;
235 } while ((error = ERR_get_error_line(&file, &line)));
236
237 return in_stack;
238 }
239 DIAG_ON(format-nonliteral)
240
241 /** Print errors in the TLS thread local error stack
242 *
243 * Drains the thread local OpenSSL error queue, and prints out errors.
244 *
245 * @param[in] request The current request (may be NULL).
246 * @param[in] msg Error message describing the operation being attempted.
247 * @param[in] ... Arguments for msg.
248 * @return the number of errors drained from the stack.
249 */
tls_error_log(REQUEST * request,char const * msg,...)250 int tls_error_log(REQUEST *request, char const *msg, ...)
251 {
252 va_list ap;
253 int ret;
254
255 va_start(ap, msg);
256 ret = tls_verror_log(request, msg, ap);
257 va_end(ap);
258
259 return ret;
260 }
261
262 /** Print errors raised by OpenSSL I/O functions
263 *
264 * Drains the thread local OpenSSL error queue, and prints out errors
265 * based on the SSL handle and the return code of the I/O function.
266 *
267 * OpenSSL lists I/O functions to be:
268 * - SSL_connect
269 * - SSL_accept
270 * - SSL_do_handshake
271 * - SSL_read
272 * - SSL_peek
273 * - SSL_write
274 *
275 * @param request The current request (may be NULL).
276 * @param session The current tls_session.
277 * @param ret from the I/O operation.
278 * @param msg Error message describing the operation being attempted.
279 * @param ... Arguments for msg.
280 * @return
281 * - 0 TLS session cannot continue.
282 * - 1 TLS session may still be viable.
283 */
tls_error_io_log(REQUEST * request,tls_session_t * session,int ret,char const * msg,...)284 int tls_error_io_log(REQUEST *request, tls_session_t *session, int ret, char const *msg, ...)
285 {
286 int error;
287 va_list ap;
288
289 if (ERR_peek_error()) {
290 va_start(ap, msg);
291 tls_verror_log(request, msg, ap);
292 va_end(ap);
293 }
294
295 error = SSL_get_error(session->ssl, ret);
296 switch (error) {
297 /*
298 * These seem to be harmless and already "dealt
299 * with" by our non-blocking environment. NB:
300 * "ZERO_RETURN" is the clean "error"
301 * indicating a successfully closed SSL
302 * tunnel. We let this happen because our IO
303 * loop should not appear to have broken on
304 * this condition - and outside the IO loop, the
305 * "shutdown" state is checked.
306 *
307 * Don't print anything if we ignore the error.
308 */
309 case SSL_ERROR_NONE:
310 case SSL_ERROR_WANT_READ:
311 case SSL_ERROR_WANT_WRITE:
312 case SSL_ERROR_WANT_X509_LOOKUP:
313 case SSL_ERROR_ZERO_RETURN:
314 break;
315
316 /*
317 * These seem to be indications of a genuine
318 * error that should result in the SSL tunnel
319 * being regarded as "dead".
320 */
321 case SSL_ERROR_SYSCALL:
322 ROPTIONAL(REDEBUG, ERROR, "(TLS) System call (I/O) error (%i)", ret);
323 return 0;
324
325 case SSL_ERROR_SSL:
326 ROPTIONAL(REDEBUG, ERROR, "(TLS) Protocol error (%i)", ret);
327 return 0;
328
329 /*
330 * For any other errors that (a) exist, and (b)
331 * crop up - we need to interpret what to do with
332 * them - so "politely inform" the caller that
333 * the code needs updating here.
334 */
335 default:
336 ROPTIONAL(REDEBUG, ERROR, "(TLS) Session error %i (%i)", error, ret);
337 return 0;
338 }
339
340 return 1;
341 }
342
343 #ifdef PSK_MAX_IDENTITY_LEN
identity_is_safe(const char * identity)344 static bool identity_is_safe(const char *identity)
345 {
346 char c;
347
348 if (!identity) return true;
349
350 while ((c = *(identity++)) != '\0') {
351 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
352 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
353 continue;
354 }
355
356 return false;
357 }
358
359 return true;
360 }
361
362 /*
363 * When a client uses TLS-PSK to talk to a server, this callback
364 * is used by the server to determine the PSK to use.
365 */
psk_server_callback(SSL * ssl,const char * identity,unsigned char * psk,unsigned int max_psk_len)366 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
367 unsigned char *psk,
368 unsigned int max_psk_len)
369 {
370 unsigned int psk_len = 0;
371 fr_tls_server_conf_t *conf;
372 REQUEST *request;
373
374 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
375 FR_TLS_EX_INDEX_CONF);
376 if (!conf) return 0;
377
378 request = (REQUEST *)SSL_get_ex_data(ssl,
379 FR_TLS_EX_INDEX_REQUEST);
380 if (request && conf->psk_query) {
381 size_t hex_len;
382 VALUE_PAIR *vp;
383 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
384
385 /*
386 * The passed identity is weird. Deny it.
387 */
388 if (!identity_is_safe(identity)) {
389 RWDEBUG("(TLS) Invalid characters in PSK identity %s", identity);
390 return 0;
391 }
392
393 vp = pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
394 if (!vp) return 0;
395
396 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
397 NULL, NULL);
398 if (!hex_len) {
399 RWDEBUG("(TLS) PSK expansion returned an empty string.");
400 return 0;
401 }
402
403 /*
404 * The returned key is truncated at MORE than
405 * OpenSSL can handle. That way we can detect
406 * the truncation, and complain about it.
407 */
408 if (hex_len > (2 * max_psk_len)) {
409 RWDEBUG("(TLS) Returned PSK is too long (%u > %u)",
410 (unsigned int) hex_len, 2 * max_psk_len);
411 return 0;
412 }
413
414 /*
415 * Leave the TLS-PSK-Identity in the request, and
416 * convert the expansion from printable string
417 * back to hex.
418 */
419 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
420 }
421
422 if (!conf->psk_identity) {
423 DEBUG("No static PSK identity set. Rejecting the user");
424 return 0;
425 }
426
427 /*
428 * No REQUEST, or no dynamic query. Just look for a
429 * static identity.
430 */
431 if (strcmp(identity, conf->psk_identity) != 0) {
432 ERROR("(TKS) Supplied PSK identity %s does not match configuration. Rejecting.",
433 identity);
434 return 0;
435 }
436
437 psk_len = strlen(conf->psk_password);
438 if (psk_len > (2 * max_psk_len)) return 0;
439
440 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
441 }
442
psk_client_callback(SSL * ssl,UNUSED char const * hint,char * identity,unsigned int max_identity_len,unsigned char * psk,unsigned int max_psk_len)443 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
444 char *identity, unsigned int max_identity_len,
445 unsigned char *psk, unsigned int max_psk_len)
446 {
447 unsigned int psk_len;
448 fr_tls_server_conf_t *conf;
449
450 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
451 FR_TLS_EX_INDEX_CONF);
452 if (!conf) return 0;
453
454 psk_len = strlen(conf->psk_password);
455 if (psk_len > (2 * max_psk_len)) return 0;
456
457 strlcpy(identity, conf->psk_identity, max_identity_len);
458
459 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
460 }
461
462 #endif
463
464 #define MAX_SESSION_SIZE (256)
465
466
tls_session_id(SSL_SESSION * ssn,char * buffer,size_t bufsize)467 void tls_session_id(SSL_SESSION *ssn, char *buffer, size_t bufsize)
468 {
469 #if OPENSSL_VERSION_NUMBER < 0x10001000L
470 size_t size;
471
472 size = ssn->session_id_length;
473 if (size > bufsize) size = bufsize;
474
475 fr_bin2hex(buffer, ssn->session_id, size);
476 #else
477 unsigned int size;
478 uint8_t const *p;
479
480 p = SSL_SESSION_get_id(ssn, &size);
481 if (size > bufsize) size = bufsize;
482
483 fr_bin2hex(buffer, p, size);
484
485 #endif
486 }
487
488
489
_tls_session_free(tls_session_t * ssn)490 static int _tls_session_free(tls_session_t *ssn)
491 {
492 /*
493 * Free any opaque TTLS or PEAP data.
494 */
495 if ((ssn->opaque) && (ssn->free_opaque)) {
496 ssn->free_opaque(ssn->opaque);
497 ssn->opaque = NULL;
498 }
499
500 session_close(ssn);
501
502 return 0;
503 }
504
tls_new_client_session(TALLOC_CTX * ctx,fr_tls_server_conf_t * conf,int fd,VALUE_PAIR ** certs)505 tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd, VALUE_PAIR **certs)
506 {
507 int ret;
508 int verify_mode;
509 tls_session_t *ssn = NULL;
510 REQUEST *request;
511
512 ssn = talloc_zero(ctx, tls_session_t);
513 if (!ssn) return NULL;
514
515 talloc_set_destructor(ssn, _tls_session_free);
516
517 ssn->ctx = conf->ctx;
518 ssn->mtu = conf->fragment_size;
519 ssn->conf = conf;
520
521 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
522
523 ssn->ssl = SSL_new(ssn->ctx);
524 if (!ssn->ssl) {
525 talloc_free(ssn);
526 return NULL;
527 }
528
529 request = request_alloc(ssn);
530 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
531
532 /*
533 * Add the message callback to identify what type of
534 * message/handshake is passed
535 */
536 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
537 SSL_set_msg_callback_arg(ssn->ssl, ssn);
538 SSL_set_info_callback(ssn->ssl, cbtls_info);
539
540 /*
541 * Always verify the peer certificate.
542 */
543 DEBUG2("Requiring Server certificate");
544 verify_mode = SSL_VERIFY_PEER;
545 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
546 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
547
548 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
549 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
550 if (certs) SSL_set_ex_data(ssn->ssl, fr_tls_ex_index_certs, (void *)certs);
551
552 SSL_set_fd(ssn->ssl, fd);
553
554 ret = SSL_connect(ssn->ssl);
555 if (ret < 0) {
556 switch (SSL_get_error(ssn->ssl, ret)) {
557 default:
558 break;
559
560
561
562 case SSL_ERROR_WANT_READ:
563 case SSL_ERROR_WANT_WRITE:
564 ssn->connected = false;
565 return ssn;
566 }
567 }
568
569 if (ret <= 0) {
570 tls_error_io_log(NULL, ssn, ret, "Failed in connecting TLS session.");
571 talloc_free(ssn);
572
573 return NULL;
574 }
575
576 ssn->connected = true;
577 return ssn;
578 }
579
580
581 /** Create a new TLS session
582 *
583 * Configures a new TLS session, configuring options, setting callbacks etc...
584 *
585 * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
586 * session is tied to another talloc'd object.
587 * @param conf to use to configure the tls session.
588 * @param request The current #REQUEST.
589 * @param client_cert Whether to require a client_cert.
590 * @param allow_tls13 Whether to allow or forbid TLS 1.3.
591 * @return a new session on success, or NULL on error.
592 */
tls_new_session(TALLOC_CTX * ctx,fr_tls_server_conf_t * conf,REQUEST * request,bool client_cert,UNUSED bool allow_tls13)593 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert,
594 #ifndef TLS1_3_VERSION
595 UNUSED
596 #endif
597 bool allow_tls13)
598 {
599 tls_session_t *state = NULL;
600 SSL *new_tls = NULL;
601 int verify_mode = 0;
602 VALUE_PAIR *vp;
603 X509_STORE *new_cert_store;
604
605 rad_assert(request != NULL);
606
607 RDEBUG2("(TLS) Initiating new session");
608
609 /*
610 * Replace X509 store if it is time to update CRLs/certs in ca_path
611 */
612 if (conf->ca_path_reload_interval > 0 && conf->ca_path_last_reload + conf->ca_path_reload_interval <= request->timestamp) {
613 pthread_mutex_lock(&conf->mutex);
614 /* recheck conf->ca_path_last_reload because it may be inaccurate without mutex */
615 if (conf->ca_path_last_reload + conf->ca_path_reload_interval <= request->timestamp) {
616 RDEBUG2("Flushing X509 store to re-read data from ca_path dir");
617
618 if ((new_cert_store = fr_init_x509_store(conf)) == NULL) {
619 RERROR("(TLS) Error replacing X509 store, out of memory (?)");
620 } else {
621 if (conf->old_x509_store) X509_STORE_free(conf->old_x509_store);
622 /*
623 * Swap empty store with the old one.
624 */
625 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
626 conf->old_x509_store = SSL_CTX_get_cert_store(conf->ctx);
627 /* Bump refcnt so the store is kept allocated till next store replacement */
628 X509_STORE_up_ref(conf->old_x509_store);
629 SSL_CTX_set_cert_store(conf->ctx, new_cert_store);
630 #else
631 /*
632 * We do not use SSL_CTX_set_cert_store() call here because
633 * we are not sure that old X509 store is not in the use by some
634 * thread (i.e. cert check in progress).
635 * Keep it allocated till next store replacement.
636 */
637 conf->old_x509_store = conf->ctx->cert_store;
638 conf->ctx->cert_store = new_cert_store;
639 #endif
640 conf->ca_path_last_reload = request->timestamp;
641 }
642 }
643 pthread_mutex_unlock(&conf->mutex);
644 }
645
646 new_tls = SSL_new(conf->ctx);
647 if (new_tls == NULL) {
648 tls_error_log(request, "Error creating new TLS session");
649 return NULL;
650 }
651
652 #ifdef TLS1_3_VERSION
653 /*
654 * Disallow TLS 1.3 for TTLS, PEAP, and FAST.
655 *
656 * We need another magic configuration option to allow
657 * it.
658 */
659 if (!allow_tls13 && (conf->max_version == TLS1_3_VERSION)) {
660 WARN("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
661 WARN("!! FORCING MAXIMUM TLS VERSION TO TLS 1.2 !!");
662 WARN("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
663 WARN("!! There is no standard for using this EAP method with TLS 1.3");
664 WARN("!! Please set tls_max_version = \"1.2\"");
665 WARN("!! FreeRADIUS only supports TLS 1.3 for special builds of wpa_supplicant and Windows");
666 WARN("!! This limitation is likely to change in late 2021.");
667 WARN("!! If you are using this version of FreeRADIUS after 2021, you will probably need to upgrade");
668 WARN("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
669
670 if (SSL_set_max_proto_version(new_tls, TLS1_2_VERSION) == 0) {
671 tls_error_log(request, "Failed limiting maximum version to TLS 1.2");
672 return NULL;
673 }
674 }
675 #endif
676
677 /* We use the SSL's "app_data" to indicate a call-back */
678 SSL_set_app_data(new_tls, NULL);
679
680 if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
681 RERROR("(TLS) Error allocating memory for SSL state");
682 return NULL;
683 }
684 session_init(state);
685 talloc_set_destructor(state, _tls_session_free);
686
687 state->ctx = conf->ctx;
688 state->ssl = new_tls;
689 state->conf = conf;
690
691 /*
692 * Initialize callbacks
693 */
694 state->record_init = record_init;
695 state->record_close = record_close;
696 state->record_plus = record_plus;
697 state->record_minus = record_minus;
698
699 /*
700 * Create & hook the BIOs to handle the dirty side of the
701 * SSL. This is *very important* as we want to handle
702 * the transmission part. Now the only IO interface
703 * that SSL is aware of, is our defined BIO buffers.
704 *
705 * This means that all SSL IO is done to/from memory,
706 * and we can update those BIOs from the packets we've
707 * received.
708 */
709 state->into_ssl = BIO_new(BIO_s_mem());
710 state->from_ssl = BIO_new(BIO_s_mem());
711 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
712
713 /*
714 * Add the message callback to identify what type of
715 * message/handshake is passed
716 */
717 SSL_set_msg_callback(new_tls, cbtls_msg);
718 SSL_set_msg_callback_arg(new_tls, state);
719 SSL_set_info_callback(new_tls, cbtls_info);
720
721 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
722 /*
723 * Allow policies to load context-specific certificate chains.
724 */
725 vp = fr_pair_find_by_num(request->config, PW_TLS_SESSION_CERT_FILE, 0, TAG_ANY);
726 if (vp) {
727 VALUE_PAIR *key = fr_pair_find_by_num(request->config, PW_TLS_SESSION_CERT_PRIVATE_KEY_FILE, 0, TAG_ANY);
728 if (!key) key = vp;
729
730 RDEBUG2("(TLS) Loading session certificate file \"%s\"", vp->vp_strvalue);
731
732 if (conf->realms) {
733 fr_realm_ctx_t my_r, *r;
734
735 /*
736 * Use a pre-existing SSL CTX, if
737 * available. Note that due to OpenSSL
738 * issues, this really changes only the
739 * certificate files, and leaves all
740 * other fields alone. e.g. you can't
741 * select a different TLS version.
742 *
743 * This is fine for our purposes in v3.
744 * Due to how we build them, the various
745 * additional SSL_CTXs are identical to
746 * the main one, except for certs.
747 */
748 my_r.name = vp->vp_strvalue;
749 r = fr_hash_table_finddata(conf->realms, &my_r);
750 if (r) {
751 (void) SSL_set_SSL_CTX(state->ssl, r->ctx);
752 goto after_chain;
753 }
754
755 /*
756 * Else fall through to trying to dynamically load the certs.
757 */
758 }
759
760 if (conf->file_type) {
761 if (SSL_use_certificate_chain_file(state->ssl, vp->vp_strvalue) != 1) {
762 tls_error_log(request, "Failed loading TLS session certificate \"%s\"",
763 vp->vp_strvalue);
764 error:
765 talloc_free(state);
766 return NULL;
767 }
768 } else {
769 if (SSL_use_certificate_file(state->ssl, vp->vp_strvalue, SSL_FILETYPE_ASN1) != 1) {
770 tls_error_log(request, "Failed loading TLS session certificate \"%s\"",
771 vp->vp_strvalue);
772 goto error;
773 }
774 }
775
776 /*
777 * Note that there is either no password, or it
778 * has to be the same as what's in the
779 * configuration.
780 *
781 * There is just no additional security to
782 * putting a password into the same file system
783 * as the private key.
784 */
785 if (SSL_use_PrivateKey_file(state->ssl, key->vp_strvalue, SSL_FILETYPE_PEM) != 1) {
786 tls_error_log(request, "Failed loading TLS session certificate \"%s\"",
787 key->vp_strvalue);
788 goto error;
789 }
790
791 if (SSL_check_private_key(state->ssl) != 1) {
792 tls_error_log(request, "Failed validating TLS session certificate \"%s\"",
793 vp->vp_strvalue);
794 goto error;
795 }
796 }
797 after_chain:
798 #endif
799
800 /*
801 * In Server mode we only accept.
802 */
803 SSL_set_accept_state(state->ssl);
804
805 /*
806 * Verify the peer certificate, if asked.
807 */
808 if (client_cert) {
809 RDEBUG2("(TLS) Setting verify mode to require certificate from client");
810 verify_mode = SSL_VERIFY_PEER;
811 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
812 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
813 }
814 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
815
816 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
817 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
818 state->length_flag = conf->include_length;
819
820 /*
821 * We use default fragment size, unless the Framed-MTU
822 * tells us it's too big. Note that we do NOT account
823 * for the EAP-TLS headers if conf->fragment_size is
824 * large, because that config item looks to be confusing.
825 *
826 * i.e. it should REALLY be called MTU, and the code here
827 * should figure out what that means for TLS fragment size.
828 * asking the administrator to know the internal details
829 * of EAP-TLS in order to calculate fragment sizes is
830 * just too much.
831 */
832 state->mtu = conf->fragment_size;
833 #define EAP_TLS_MAGIC_OVERHEAD (63)
834
835 /*
836 * If the packet contains an MTU, then use that. We
837 * trust the admin!
838 */
839 vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
840 if (vp) {
841 if ((vp->vp_integer > 100) && (vp->vp_integer < state->mtu)) {
842 state->mtu = vp->vp_integer;
843 }
844
845 } else if (request->parent) {
846 /*
847 * If there's a parent request, we look for what
848 * MTU was set there. Then, we use an MTU which
849 * accounts for the extra overhead of nesting EAP
850 * + TLS inside of EAP + TLS.
851 */
852 vp = fr_pair_find_by_num(request->parent->state, PW_FRAMED_MTU, 0, TAG_ANY);
853 if (vp && (vp->vp_integer > (100 + EAP_TLS_MAGIC_OVERHEAD)) && (vp->vp_integer <= state->mtu)) {
854 state->mtu = vp->vp_integer - EAP_TLS_MAGIC_OVERHEAD;
855 }
856 }
857
858 /*
859 * Cache / update the Framed-MTU in the session-state
860 * list.
861 */
862 vp = fr_pair_find_by_num(request->state, PW_FRAMED_MTU, 0, TAG_ANY);
863 if (!vp) {
864 vp = fr_pair_afrom_num(request->state_ctx, PW_FRAMED_MTU, 0);
865 fr_pair_add(&request->state, vp);
866 }
867 if (vp) vp->vp_integer = state->mtu;
868
869 if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
870
871 return state;
872 }
873
874 /*
875 * We are the server, we always get the dirty data
876 * (Handshake data is also considered as dirty data)
877 * During handshake, since SSL API handles itself,
878 * After clean-up, dirty_out will be filled with
879 * the data required for handshaking. So we check
880 * if dirty_out is empty then we simply send it back.
881 * As of now, if handshake is successful, then we keep going,
882 * otherwise we fail.
883 *
884 * Fill the Bio with the dirty data to clean it
885 * Get the cleaned data from SSL, if it is not Handshake data
886 */
tls_handshake_recv(REQUEST * request,tls_session_t * ssn)887 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
888 {
889 int err;
890
891 if (ssn->invalid_hb_used) {
892 REDEBUG("(TLS) OpenSSL Heartbeat attack detected. Closing connection");
893 return 0;
894 }
895
896 if (ssn->dirty_in.used > 0) {
897 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
898 if (err != (int) ssn->dirty_in.used) {
899 REDEBUG("(TLS) Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
900 record_init(&ssn->dirty_in);
901 return 0;
902 }
903 record_init(&ssn->dirty_in);
904 }
905
906 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
907 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
908 if (err > 0) {
909 ssn->clean_out.used += err;
910 return 1;
911 }
912
913 if (!tls_error_io_log(request, ssn, err, "Failed reading from OpenSSL")) return 0;
914
915 /* Some Extra STATE information for easy debugging */
916 if (!ssn->is_init_finished && SSL_is_init_finished(ssn->ssl)) {
917 VALUE_PAIR *vp;
918 char const *str_version;
919
920 RDEBUG2("(TLS) Connection Established");
921 ssn->is_init_finished = true;
922
923 vp = fr_pair_afrom_num(request->state_ctx, PW_TLS_SESSION_CIPHER_SUITE, 0);
924 if (vp) {
925 fr_pair_value_strcpy(vp, SSL_CIPHER_get_name(SSL_get_current_cipher(ssn->ssl)));
926 fr_pair_add(&request->state, vp);
927 RINDENT();
928 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
929 REXDENT();
930 }
931
932 switch (ssn->info.version) {
933 case SSL2_VERSION:
934 str_version = "SSL 2.0";
935 break;
936 case SSL3_VERSION:
937 str_version = "SSL 3.0";
938 break;
939 case TLS1_VERSION:
940 str_version = "TLS 1.0";
941 break;
942 #ifdef TLS1_1_VERSION
943 case TLS1_1_VERSION:
944 str_version = "TLS 1.1";
945 break;
946 #endif
947 #ifdef TLS1_2_VERSION
948 case TLS1_2_VERSION:
949 str_version = "TLS 1.2";
950 break;
951 #endif
952 #ifdef TLS1_3_VERSION
953 case TLS1_3_VERSION:
954 str_version = "TLS 1.3";
955 break;
956 #endif
957 default:
958 str_version = "UNKNOWN";
959 break;
960 }
961
962 vp = fr_pair_afrom_num(request->state_ctx, PW_TLS_SESSION_VERSION, 0);
963 if (vp) {
964 fr_pair_value_strcpy(vp, str_version);
965 fr_pair_add(&request->state, vp);
966 RINDENT();
967 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
968 REXDENT();
969
970 }
971 }
972 else if (SSL_in_init(ssn->ssl)) { RDEBUG2("(TLS) In Handshake Phase"); }
973 else if (SSL_in_before(ssn->ssl)) { RDEBUG2("(TLS) Before Handshake Phase"); }
974 else if (SSL_in_accept_init(ssn->ssl)) { RDEBUG2("(TLS) In Accept mode"); }
975 else if (SSL_in_connect_init(ssn->ssl)) { RDEBUG2("(TLS) In Connect mode"); }
976
977 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
978 /*
979 * Cache the SSL_SESSION pointer.
980 */
981 if (!ssn->ssl_session) {
982 ssn->ssl_session = SSL_get_session(ssn->ssl);
983
984 /*
985 * Some versions of OpenSSL don't allow you to
986 * get the session before the init is finished.
987 * In that case, this error is a soft fail.
988 *
989 * If the session init is finished, then failure
990 * to get the session is a hard fail.
991 */
992 if (!ssn->ssl_session && ssn->is_init_finished) {
993 RDEBUG("(TLS) Failed getting session");
994 return 0;
995 }
996 }
997
998 #else
999 #error You must use a newer version of OpenSSL
1000 #endif
1001
1002 err = BIO_ctrl_pending(ssn->from_ssl);
1003 if (err > 0) {
1004 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
1005 sizeof(ssn->dirty_out.data));
1006 if (err > 0) {
1007 RDEBUG3("(TLS) got %d bytes of data", err);
1008 ssn->dirty_out.used = err;
1009
1010 } else if (BIO_should_retry(ssn->from_ssl)) {
1011 record_init(&ssn->dirty_in);
1012 RDEBUG2("(TLS) Asking for more data in tunnel.");
1013 return 1;
1014
1015 } else {
1016 tls_error_log(NULL, "Error reading from OpenSSL");
1017 record_init(&ssn->dirty_in);
1018 return 0;
1019 }
1020 } else {
1021
1022 RDEBUG2("(TLS) Application data.");
1023 /* Its clean application data, do whatever we want */
1024 record_init(&ssn->clean_out);
1025 }
1026
1027 /* We are done with dirty_in, reinitialize it */
1028 record_init(&ssn->dirty_in);
1029 return 1;
1030 }
1031
1032 /*
1033 * Take cleartext user data, and encrypt it into the output buffer,
1034 * to send to the client at the other end of the SSL connection.
1035 */
tls_handshake_send(REQUEST * request,tls_session_t * ssn)1036 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
1037 {
1038 int err;
1039
1040 /*
1041 * If there's un-encrypted data in 'clean_in', then write
1042 * that data to the SSL session, and then call the BIO function
1043 * to get that encrypted data from the SSL session, into
1044 * a buffer which we can then package into an EAP packet.
1045 *
1046 * Based on Server's logic this clean_in is expected to
1047 * contain the data to send to the client.
1048 */
1049 if (ssn->clean_in.used > 0) {
1050 int written;
1051
1052 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
1053 record_minus(&ssn->clean_in, NULL, written);
1054
1055 /* Get the dirty data from Bio to send it */
1056 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data + ssn->dirty_out.used,
1057 sizeof(ssn->dirty_out.data) - ssn->dirty_out.used);
1058 if (err > 0) {
1059 ssn->dirty_out.used += err;
1060 } else {
1061 if (!tls_error_io_log(request, ssn, err, "Failed writing to OpenSSL")) {
1062 return 0;
1063 }
1064 }
1065 }
1066
1067 return 1;
1068 }
1069
session_init(tls_session_t * ssn)1070 static void session_init(tls_session_t *ssn)
1071 {
1072 ssn->ssl = NULL;
1073 ssn->into_ssl = ssn->from_ssl = NULL;
1074 record_init(&ssn->clean_in);
1075 record_init(&ssn->clean_out);
1076 record_init(&ssn->dirty_in);
1077 record_init(&ssn->dirty_out);
1078
1079 memset(&ssn->info, 0, sizeof(ssn->info));
1080
1081 ssn->mtu = 0;
1082 ssn->fragment = false;
1083 ssn->tls_msg_len = 0;
1084 ssn->length_flag = false;
1085 ssn->opaque = NULL;
1086 ssn->free_opaque = NULL;
1087 }
1088
session_close(tls_session_t * ssn)1089 static void session_close(tls_session_t *ssn)
1090 {
1091 if (ssn->ssl) {
1092 SSL_set_quiet_shutdown(ssn->ssl, 1);
1093 SSL_shutdown(ssn->ssl);
1094
1095 SSL_free(ssn->ssl);
1096 ssn->ssl = NULL;
1097 }
1098
1099 record_close(&ssn->clean_in);
1100 record_close(&ssn->clean_out);
1101 record_close(&ssn->dirty_in);
1102 record_close(&ssn->dirty_out);
1103 session_init(ssn);
1104 }
1105
record_init(record_t * rec)1106 static void record_init(record_t *rec)
1107 {
1108 rec->used = 0;
1109 }
1110
record_close(record_t * rec)1111 static void record_close(record_t *rec)
1112 {
1113 rec->used = 0;
1114 }
1115
1116
1117 /*
1118 * Copy data to the intermediate buffer, before we send
1119 * it somewhere.
1120 */
record_plus(record_t * rec,void const * ptr,unsigned int size)1121 static unsigned int record_plus(record_t *rec, void const *ptr,
1122 unsigned int size)
1123 {
1124 unsigned int added = MAX_RECORD_SIZE - rec->used;
1125
1126 if(added > size)
1127 added = size;
1128 if(added == 0)
1129 return 0;
1130 memcpy(rec->data + rec->used, ptr, added);
1131 rec->used += added;
1132 return added;
1133 }
1134
1135 /*
1136 * Take data from the buffer, and give it to the caller.
1137 */
record_minus(record_t * rec,void * ptr,unsigned int size)1138 static unsigned int record_minus(record_t *rec, void *ptr,
1139 unsigned int size)
1140 {
1141 unsigned int taken = rec->used;
1142
1143 if(taken > size)
1144 taken = size;
1145 if(taken == 0)
1146 return 0;
1147 if(ptr)
1148 memcpy(ptr, rec->data, taken);
1149 rec->used -= taken;
1150
1151 /*
1152 * This is pretty bad...
1153 */
1154 if (rec->used > 0) memmove(rec->data, rec->data + taken, rec->used);
1155
1156 return taken;
1157 }
1158
tls_session_information(tls_session_t * tls_session)1159 void tls_session_information(tls_session_t *tls_session)
1160 {
1161 char const *str_write_p, *str_version, *str_content_type = "";
1162 char const *str_details1 = "", *str_details2= "";
1163 REQUEST *request;
1164 VALUE_PAIR *vp;
1165 char content_type[16], alert_buf[16];
1166 char buffer[32];
1167
1168 /*
1169 * Don't print this out in the normal course of
1170 * operations.
1171 */
1172 if (rad_debug_lvl == 0) return;
1173
1174 /*
1175 * OpenSSL calls this function with 'pseudo' content
1176 * types. The user doesn't care about them, so suppress them.
1177 */
1178 if (tls_session->info.content_type > UINT8_MAX) return;
1179
1180 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
1181 if (!request) return;
1182
1183 str_write_p = tls_session->info.origin ? "(TLS) send" : "(TLS) recv";
1184
1185 switch (tls_session->info.version) {
1186 case SSL2_VERSION:
1187 str_version = "SSL 2.0 ";
1188 break;
1189 case SSL3_VERSION:
1190 str_version = "SSL 3.0 ";
1191 break;
1192 case TLS1_VERSION:
1193 str_version = "TLS 1.0 ";
1194 break;
1195 #ifdef TLS1_1_VERSION
1196 case TLS1_1_VERSION:
1197 str_version = "TLS 1.1 ";
1198 break;
1199 #endif
1200 #ifdef TLS1_2_VERSION
1201 case TLS1_2_VERSION:
1202 str_version = "TLS 1.2 ";
1203 break;
1204 #endif
1205 #ifdef TLS1_3_VERSION
1206 case TLS1_3_VERSION:
1207 str_version = "TLS 1.3 ";
1208 break;
1209 #endif
1210
1211 default:
1212 sprintf(buffer, "UNKNOWN TLS VERSION '%04X'", tls_session->info.version);
1213 str_version = buffer;
1214 break;
1215 }
1216
1217 if (1) {
1218 switch (tls_session->info.content_type) {
1219 case SSL3_RT_CHANGE_CIPHER_SPEC:
1220 str_content_type = "ChangeCipherSpec";
1221 break;
1222
1223 case SSL3_RT_ALERT:
1224 str_content_type = "Alert";
1225 break;
1226
1227 case SSL3_RT_HANDSHAKE:
1228 str_content_type = "Handshake";
1229 break;
1230
1231 case SSL3_RT_APPLICATION_DATA:
1232 str_content_type = "ApplicationData";
1233 break;
1234
1235 default:
1236 snprintf(content_type, sizeof(content_type), "content=%d", tls_session->info.content_type);
1237 str_content_type = content_type;
1238 break;
1239 }
1240
1241 if (tls_session->info.content_type == SSL3_RT_ALERT) {
1242 str_details1 = ", ???";
1243
1244 if (tls_session->info.record_len == 2) {
1245
1246 switch (tls_session->info.alert_level) {
1247 case SSL3_AL_WARNING:
1248 str_details1 = ", warning";
1249 break;
1250 case SSL3_AL_FATAL:
1251 str_details1 = ", fatal";
1252 break;
1253 }
1254
1255 str_details2 = " ???";
1256 switch (tls_session->info.alert_description) {
1257 case SSL3_AD_CLOSE_NOTIFY:
1258 str_details2 = " close_notify";
1259 break;
1260
1261 case SSL3_AD_UNEXPECTED_MESSAGE:
1262 str_details2 = " unexpected_message";
1263 break;
1264
1265 case SSL3_AD_BAD_RECORD_MAC:
1266 str_details2 = " bad_record_mac";
1267 break;
1268
1269 case TLS1_AD_DECRYPTION_FAILED:
1270 str_details2 = " decryption_failed";
1271 break;
1272
1273 case TLS1_AD_RECORD_OVERFLOW:
1274 str_details2 = " record_overflow";
1275 break;
1276
1277 case SSL3_AD_DECOMPRESSION_FAILURE:
1278 str_details2 = " decompression_failure";
1279 break;
1280
1281 case SSL3_AD_HANDSHAKE_FAILURE:
1282 str_details2 = " handshake_failure";
1283 break;
1284
1285 case SSL3_AD_NO_CERTIFICATE:
1286 str_details2 = " no_certificate";
1287 break;
1288
1289 case SSL3_AD_BAD_CERTIFICATE:
1290 str_details2 = " bad_certificate";
1291 break;
1292
1293 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
1294 str_details2 = " unsupported_certificate";
1295 break;
1296
1297 case SSL3_AD_CERTIFICATE_REVOKED:
1298 str_details2 = " certificate_revoked";
1299 break;
1300
1301 case SSL3_AD_CERTIFICATE_EXPIRED:
1302 str_details2 = " certificate_expired";
1303 break;
1304
1305 case SSL3_AD_CERTIFICATE_UNKNOWN:
1306 str_details2 = " certificate_unknown";
1307 break;
1308
1309 case SSL3_AD_ILLEGAL_PARAMETER:
1310 str_details2 = " illegal_parameter";
1311 break;
1312
1313 case TLS1_AD_UNKNOWN_CA:
1314 str_details2 = " unknown_ca";
1315 break;
1316
1317 case TLS1_AD_ACCESS_DENIED:
1318 str_details2 = " access_denied";
1319 break;
1320
1321 case TLS1_AD_DECODE_ERROR:
1322 str_details2 = " decode_error";
1323 break;
1324
1325 case TLS1_AD_DECRYPT_ERROR:
1326 str_details2 = " decrypt_error";
1327 break;
1328
1329 case TLS1_AD_EXPORT_RESTRICTION:
1330 str_details2 = " export_restriction";
1331 break;
1332
1333 case TLS1_AD_PROTOCOL_VERSION:
1334 str_details2 = " protocol_version";
1335
1336 #ifdef TLS1_3_VERSION
1337 /*
1338 * Complain about OpenSSL bugs.
1339 */
1340 if ((tls_session->info.version > tls_session->conf->max_version) &&
1341 (rad_debug_lvl > 0)) {
1342 WARN("TLS 1.3 has been negotiated even though it was disabled. This is an OpenSSL Bug.");
1343 WARN("Please set: cipher_list = \"DEFAULT@SECLEVEL=1\" in the tls {...} section.");
1344 }
1345 #endif
1346 break;
1347
1348 case TLS1_AD_INSUFFICIENT_SECURITY:
1349 str_details2 = " insufficient_security";
1350 break;
1351
1352 case TLS1_AD_INTERNAL_ERROR:
1353 str_details2 = " internal_error";
1354 break;
1355
1356 case TLS1_AD_USER_CANCELLED:
1357 str_details2 = " user_canceled";
1358 break;
1359
1360 case TLS1_AD_NO_RENEGOTIATION:
1361 str_details2 = " no_renegotiation";
1362 break;
1363
1364 #ifdef TLS13_AD_MISSING_EXTENSIONS
1365 case TLS13_AD_MISSING_EXTENSIONS:
1366 str_details2 = " missing_extensions";
1367 break;
1368 #endif
1369
1370 #ifdef TLS13_AD_CERTIFICATE_REQUIRED
1371 case TLS13_AD_CERTIFICATE_REQUIRED:
1372 str_details2 = " certificate_required";
1373 break;
1374 #endif
1375
1376 #ifdef TLS1_AD_UNSUPPORTED_EXTENSION
1377 case TLS1_AD_UNSUPPORTED_EXTENSION:
1378 str_details2 = " unsupported_extension";
1379 break;
1380 #endif
1381
1382 #ifdef TLS1_AD_CERTIFICATE_UNOBTAINABLE
1383 case TLS1_AD_CERTIFICATE_UNOBTAINABLE:
1384 str_details2 = " certificate_unobtainable";
1385 break;
1386 #endif
1387
1388 #ifdef TLS1_AD_UNRECOGNIZED_NAME
1389 case TLS1_AD_UNRECOGNIZED_NAME:
1390 str_details2 = " unrecognized_name";
1391 break;
1392 #endif
1393
1394 #ifdef TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE
1395 case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
1396 str_details2 = " bad_certificate_status_response";
1397 break;
1398 #endif
1399
1400 #ifdef TLS1_AD_BAD_CERTIFICATE_HASH_VALUE
1401 case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE:
1402 str_details2 = " bad_certificate_hash_value";
1403 break;
1404 #endif
1405
1406 #ifdef TLS1_AD_UNKNOWN_PSK_IDENTITY
1407 case TLS1_AD_UNKNOWN_PSK_IDENTITY:
1408 str_details2 = " unknown_psk_identity";
1409 break;
1410 #endif
1411
1412 #ifdef TLS1_AD_NO_APPLICATION_PROTOCOL
1413 case TLS1_AD_NO_APPLICATION_PROTOCOL:
1414 str_details2 = " no_application_protocol";
1415 break;
1416 #endif
1417 }
1418 }
1419 }
1420
1421 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
1422 str_details1 = "";
1423
1424 if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
1425 case SSL3_MT_HELLO_REQUEST:
1426 str_details1 = ", HelloRequest";
1427 break;
1428
1429 case SSL3_MT_CLIENT_HELLO:
1430 str_details1 = ", ClientHello";
1431 break;
1432
1433 case SSL3_MT_SERVER_HELLO:
1434 str_details1 = ", ServerHello";
1435 break;
1436
1437 #ifdef SSL3_MT_NEWSESSION_TICKET
1438 case SSL3_MT_NEWSESSION_TICKET:
1439 str_details1 = ", NewSessionTicket";
1440 break;
1441 #endif
1442
1443 #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
1444 case SSL3_MT_ENCRYPTED_EXTENSIONS:
1445 str_details1 = ", EncryptedExtensions";
1446 break;
1447 #endif
1448
1449 case SSL3_MT_CERTIFICATE:
1450 str_details1 = ", Certificate";
1451 break;
1452
1453 case SSL3_MT_SERVER_KEY_EXCHANGE:
1454 str_details1 = ", ServerKeyExchange";
1455 break;
1456
1457 case SSL3_MT_CERTIFICATE_REQUEST:
1458 str_details1 = ", CertificateRequest";
1459 break;
1460
1461 case SSL3_MT_SERVER_DONE:
1462 str_details1 = ", ServerHelloDone";
1463 break;
1464
1465 case SSL3_MT_CERTIFICATE_VERIFY:
1466 str_details1 = ", CertificateVerify";
1467 break;
1468
1469 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1470 str_details1 = ", ClientKeyExchange";
1471 break;
1472
1473 case SSL3_MT_FINISHED:
1474 str_details1 = ", Finished";
1475 break;
1476
1477 #ifdef SSL3_MT_KEY_UPDATE
1478 case SSL3_MT_KEY_UPDATE:
1479 str_content_type = "KeyUpdate";
1480 break;
1481 #endif
1482
1483 default:
1484 snprintf(alert_buf, sizeof(alert_buf), ", type=%d", tls_session->info.handshake_type);
1485 str_details1 = alert_buf;
1486 break;
1487 }
1488 }
1489 }
1490
1491 snprintf(tls_session->info.info_description,
1492 sizeof(tls_session->info.info_description),
1493 "%s %s%s%s%s",
1494 str_write_p, str_version, str_content_type,
1495 str_details1, str_details2);
1496
1497 /*
1498 * Cache the TLS session information in the session-state
1499 * list, so it can be accessed by Post-Auth-Type
1500 * Client-Lost { ... }
1501 */
1502 vp = fr_pair_afrom_num(request->state_ctx, PW_TLS_SESSION_INFORMATION, 0);
1503 if (vp) {
1504 fr_pair_value_strcpy(vp, tls_session->info.info_description);
1505 fr_pair_add(&request->state, vp);
1506 }
1507
1508 RDEBUG2("%s", tls_session->info.info_description);
1509 }
1510
1511 static CONF_PARSER cache_config[] = {
1512 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
1513
1514 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_lifetime), "24" },
1515 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
1516
1517 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
1518 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
1519 { "virtual_server", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_server), NULL },
1520 CONF_PARSER_TERMINATOR
1521 };
1522
1523 static CONF_PARSER verify_config[] = {
1524 { "skip_if_ocsp_ok", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, verify_skip_if_ocsp_ok), "no" },
1525 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
1526 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
1527 CONF_PARSER_TERMINATOR
1528 };
1529
1530 #ifdef HAVE_OPENSSL_OCSP_H
1531 static CONF_PARSER ocsp_config[] = {
1532 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
1533 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
1534 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
1535 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
1536 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
1537 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
1538 CONF_PARSER_TERMINATOR
1539 };
1540 #endif
1541
1542 static CONF_PARSER tls_server_config[] = {
1543 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1544 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
1545 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1546 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1547 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1548 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1549 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
1550 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1551 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1552 #ifdef PSK_MAX_IDENTITY_LEN
1553 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
1554 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
1555 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
1556 #endif
1557 { "dh_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, dh_file), NULL },
1558 { "random_file", FR_CONF_OFFSET(PW_TYPE_FILE_EXISTS, fr_tls_server_conf_t, random_file), NULL },
1559 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1560 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1561 { "auto_chain", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, auto_chain), "yes" },
1562 { "disable_single_dh_use", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_single_dh_use), NULL },
1563 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1564 #ifdef X509_V_FLAG_CRL_CHECK_ALL
1565 { "check_all_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), "no" },
1566 #endif
1567 { "ca_path_reload_interval", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ca_path_reload_interval), "0" },
1568 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
1569 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1570 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1571 { "cipher_server_preference", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, cipher_server_preference), NULL },
1572 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1573 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
1574
1575 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1576 { "reject_unknown_intermediate_ca", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disallow_untrusted), .dflt = "no", },
1577 #endif
1578
1579 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1580 #ifndef OPENSSL_NO_ECDH
1581 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1582 #endif
1583 #endif
1584
1585 #ifdef SSL_OP_NO_TLSv1
1586 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1587 #endif
1588
1589 #ifdef SSL_OP_NO_TLSv1_1
1590 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1591 #endif
1592
1593 #ifdef SSL_OP_NO_TLSv1_2
1594 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1595 #endif
1596
1597 { "tls_max_version", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, tls_max_version), NULL },
1598
1599 { "tls_min_version", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, tls_min_version),
1600 #if defined(TLS1_2_VERSION)
1601 "1.2"
1602 #elif defined(TLS1_1_VERSION)
1603 "1.1"
1604 #else
1605 "1.0"
1606 #endif
1607 },
1608
1609 #ifdef TLS1_3_VERSION
1610 { "tls13_enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, tls13_enable_magic), NULL },
1611 #endif
1612
1613 { "realm_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, realm_dir), NULL },
1614
1615 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
1616
1617 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
1618
1619 #ifdef HAVE_OPENSSL_OCSP_H
1620 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
1621 #endif
1622 CONF_PARSER_TERMINATOR
1623 };
1624
1625
1626 static CONF_PARSER tls_client_config[] = {
1627 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1628 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1629 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1630 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1631 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1632 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1633 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1634 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1635 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1636 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1637 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1638 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1639 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1640 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1641 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1642 { "ca_path_reload_interval", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ca_path_reload_interval), "0" },
1643
1644 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1645 #ifndef OPENSSL_NO_ECDH
1646 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1647 #endif
1648 #endif
1649
1650 #ifdef SSL_OP_NO_TLSv1
1651 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1652 #endif
1653
1654 #ifdef SSL_OP_NO_TLSv1_1
1655 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1656 #endif
1657
1658 #ifdef SSL_OP_NO_TLSv1_2
1659 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1660 #endif
1661
1662 { "tls_max_version", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, tls_max_version), NULL },
1663
1664 { "tls_min_version", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, tls_min_version),
1665 #if defined(TLS1_2_VERSION)
1666 "1.2"
1667 #elif defined(TLS1_1_VERSION)
1668 "1.1"
1669 #else
1670 "1.0"
1671 #endif
1672 },
1673
1674 { "hostname", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, client_hostname), NULL },
1675
1676 CONF_PARSER_TERMINATOR
1677 };
1678
1679
1680 /*
1681 * TODO: Check for the type of key exchange * like conf->dh_key
1682 */
load_dh_params(SSL_CTX * ctx,char * file)1683 static int load_dh_params(SSL_CTX *ctx, char *file)
1684 {
1685 DH *dh = NULL;
1686 BIO *bio;
1687
1688 if (!file) return 0;
1689
1690 /*
1691 * Prior to trying to load the file, check what OpenSSL will do with it.
1692 *
1693 * Certain downstreams (such as RHEL) will ignore user-provided dhparams
1694 * in FIPS mode, unless the specified parameters are FIPS-approved.
1695 * However, since OpenSSL >= 1.1.1 will automatically select parameters
1696 * anyways, there's no point in attempting to load them.
1697 *
1698 * Change suggested by @t8m
1699 */
1700 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
1701 if (FIPS_mode() > 0) {
1702 WARN(LOG_PREFIX ": Ignoring user-selected DH parameters in FIPS mode. Using defaults.");
1703 return 0;
1704 }
1705 #endif
1706
1707 if ((bio = BIO_new_file(file, "r")) == NULL) {
1708 ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
1709 return -1;
1710 }
1711
1712 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1713 BIO_free(bio);
1714 if (!dh) {
1715 WARN(LOG_PREFIX ": Unable to set DH parameters. DH cipher suites may not work!");
1716 WARN(LOG_PREFIX ": Fix this by running the OpenSSL command listed in eap.conf");
1717 return 0;
1718 }
1719
1720 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1721 ERROR(LOG_PREFIX ": Unable to set DH parameters");
1722 DH_free(dh);
1723 return -1;
1724 }
1725
1726 DH_free(dh);
1727 return 0;
1728 }
1729
1730
1731 /*
1732 * Print debugging messages, and free data.
1733 */
cbtls_remove_session(SSL_CTX * ctx,SSL_SESSION * sess)1734 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1735 {
1736 char buffer[2 * MAX_SESSION_SIZE + 1];
1737 fr_tls_server_conf_t *conf;
1738
1739 tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1740
1741 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1742 if (!conf) {
1743 DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
1744 return;
1745 }
1746
1747 {
1748 int rv;
1749 char filename[3 * MAX_SESSION_SIZE + 1];
1750
1751 DEBUG2(LOG_PREFIX ": Removing session %s from the cache", buffer);
1752
1753 /* remove session and any cached VPs */
1754 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1755 conf->session_cache_path, FR_DIR_SEP, buffer);
1756 rv = unlink(filename);
1757 if (rv != 0) {
1758 DEBUG2(LOG_PREFIX ": Could not remove persisted session file %s: %s",
1759 filename, fr_syserror(errno));
1760 }
1761 /* VPs might be absent; might not have been written to disk yet */
1762 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1763 conf->session_cache_path, FR_DIR_SEP, buffer);
1764 unlink(filename);
1765 }
1766
1767 return;
1768 }
1769
cbtls_new_session(SSL * ssl,SSL_SESSION * sess)1770 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1771 {
1772 char buffer[2 * MAX_SESSION_SIZE + 1];
1773 fr_tls_server_conf_t *conf;
1774 unsigned char *sess_blob = NULL;
1775
1776 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1777
1778 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1779 if (!conf) {
1780 RWDEBUG("(TLS) Failed to find TLS configuration in session");
1781 return 0;
1782 }
1783
1784 tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1785
1786 {
1787 int fd, rv, todo, blob_len;
1788 char filename[3 * MAX_SESSION_SIZE + 1];
1789 unsigned char *p;
1790
1791 RDEBUG2("Serialising session %s, and storing in cache", buffer);
1792
1793 /* find out what length data we need */
1794 blob_len = i2d_SSL_SESSION(sess, NULL);
1795 if (blob_len < 1) {
1796 /* something went wrong */
1797 if (request) RWDEBUG("(TLS) Session serialisation failed, could not determine required buffer length");
1798 return 0;
1799 }
1800
1801 /* Do not convert to TALLOC - Thread safety */
1802 /* alloc and convert to ASN.1 */
1803 sess_blob = malloc(blob_len);
1804 if (!sess_blob) {
1805 RWDEBUG("(TLS) Session serialisation failed, couldn't allocate buffer (%d bytes)", blob_len);
1806 return 0;
1807 }
1808 /* openssl mutates &p */
1809 p = sess_blob;
1810 rv = i2d_SSL_SESSION(sess, &p);
1811 if (rv != blob_len) {
1812 if (request) RWDEBUG("(TLS) Session serialisation failed");
1813 goto error;
1814 }
1815
1816 /* open output file */
1817 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1818 conf->session_cache_path, FR_DIR_SEP, buffer);
1819 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, S_IWUSR);
1820 if (fd < 0) {
1821 if (request) RERROR("(TLS) Session serialisation failed, failed opening session file %s: %s",
1822 filename, fr_syserror(errno));
1823 goto error;
1824 }
1825
1826 /*
1827 * Set the filename to be temporarily write-only.
1828 */
1829 if (request) {
1830 VALUE_PAIR *vp;
1831
1832 vp = fr_pair_afrom_num(request->state_ctx, PW_TLS_CACHE_FILENAME, 0);
1833 if (vp) {
1834 fr_pair_value_strcpy(vp, filename);
1835 fr_pair_add(&request->state, vp);
1836 }
1837 }
1838
1839 todo = blob_len;
1840 p = sess_blob;
1841 while (todo > 0) {
1842 rv = write(fd, p, todo);
1843 if (rv < 1) {
1844 if (request) RWDEBUG("(TLS) Failed writing session: %s", fr_syserror(errno));
1845 close(fd);
1846 goto error;
1847 }
1848 p += rv;
1849 todo -= rv;
1850 }
1851 close(fd);
1852 if (request) RWDEBUG("(TLS) Wrote session %s to %s (%d bytes)", buffer, filename, blob_len);
1853 }
1854
1855 error:
1856 free(sess_blob);
1857
1858 return 0;
1859 }
1860
1861 /** Convert OpenSSL's ASN1_TIME to an epoch time
1862 *
1863 * @param[out] out Where to write the time_t.
1864 * @param[in] asn1 The ASN1_TIME to convert.
1865 * @return
1866 * - 0 success.
1867 * - -1 on failure.
1868 */
ocsp_asn1time_to_epoch(time_t * out,char const * asn1)1869 static int ocsp_asn1time_to_epoch(time_t *out, char const *asn1)
1870 {
1871 struct tm t;
1872 char const *p = asn1, *end = p + strlen(p);
1873
1874 memset(&t, 0, sizeof(t));
1875
1876 if ((end - p) <= 13) {
1877 if ((end - p) < 2) {
1878 fr_strerror_printf("ASN1 date string too short, expected 2 additional bytes, got %zu bytes",
1879 end - p);
1880 return -1;
1881 }
1882
1883 t.tm_year = (*(p++) - '0') * 10;
1884 t.tm_year += (*(p++) - '0');
1885 if (t.tm_year < 70) t.tm_year += 100;
1886 } else {
1887 t.tm_year = (*(p++) - '0') * 1000;
1888 t.tm_year += (*(p++) - '0') * 100;
1889 t.tm_year += (*(p++) - '0') * 10;
1890 t.tm_year += (*(p++) - '0');
1891 t.tm_year -= 1900;
1892 }
1893
1894 if ((end - p) < 4) {
1895 fr_strerror_printf("ASN1 string too short, expected 10 additional bytes, got %zu bytes",
1896 end - p);
1897 return -1;
1898 }
1899
1900 t.tm_mon = (*(p++) - '0') * 10;
1901 t.tm_mon += (*(p++) - '0') - 1; // -1 since January is 0 not 1.
1902 t.tm_mday = (*(p++) - '0') * 10;
1903 t.tm_mday += (*(p++) - '0');
1904
1905 if ((end - p) < 2) goto done;
1906 t.tm_hour = (*(p++) - '0') * 10;
1907 t.tm_hour += (*(p++) - '0');
1908
1909 if ((end - p) < 2) goto done;
1910 t.tm_min = (*(p++) - '0') * 10;
1911 t.tm_min += (*(p++) - '0');
1912
1913 if ((end - p) < 2) goto done;
1914 t.tm_sec = (*(p++) - '0') * 10;
1915 t.tm_sec += (*(p++) - '0');
1916
1917 /* Apparently OpenSSL converts all timestamps to UTC? Maybe? */
1918 done:
1919 *out = timegm(&t);
1920 return 0;
1921 }
1922
1923 #if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
cbtls_get_session(SSL * ssl,unsigned char * data,int len,int * copy)1924 static SSL_SESSION *cbtls_get_session(SSL *ssl, unsigned char *data, int len, int *copy)
1925 #else
1926 static SSL_SESSION *cbtls_get_session(SSL *ssl, const unsigned char *data, int len, int *copy)
1927 #endif
1928 {
1929 size_t size;
1930 char buffer[2 * MAX_SESSION_SIZE + 1];
1931 fr_tls_server_conf_t *conf;
1932 TALLOC_CTX *talloc_ctx;
1933
1934 SSL_SESSION *sess = NULL;
1935 unsigned char *sess_data = NULL;
1936 PAIR_LIST *pairlist = NULL;
1937
1938 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1939
1940 rad_assert(request != NULL);
1941
1942 size = len;
1943 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1944
1945 fr_bin2hex(buffer, data, size);
1946
1947 RDEBUG2("Peer requested cached session: %s", buffer);
1948
1949 *copy = 0;
1950
1951 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1952 if (!conf) {
1953 RWDEBUG("(TLS) Failed to find TLS configuration in session");
1954 return NULL;
1955 }
1956
1957 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1958
1959 {
1960 int rv, fd, todo;
1961 char filename[3 * MAX_SESSION_SIZE + 1];
1962
1963 unsigned char const **o;
1964 unsigned char **p;
1965 uint8_t *q;
1966
1967 struct stat st;
1968 VALUE_PAIR *vps = NULL;
1969 VALUE_PAIR *vp;
1970
1971 /* load the actual SSL session */
1972 snprintf(filename, sizeof(filename), "%s%c%s.asn1", conf->session_cache_path, FR_DIR_SEP, buffer);
1973 fd = open(filename, O_RDONLY);
1974 if (fd < 0) {
1975 RWDEBUG("(TLS) No persisted session file %s: %s", filename, fr_syserror(errno));
1976 goto error;
1977 }
1978
1979 rv = fstat(fd, &st);
1980 if (rv < 0) {
1981 RWDEBUG("(TLS) Failed stating persisted session file %s: %s", filename, fr_syserror(errno));
1982 close(fd);
1983 goto error;
1984 }
1985
1986 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1987 if (!sess_data) {
1988 RWDEBUG("(TLS) Failed allocating buffer for persisted session (%d bytes)", (int) st.st_size);
1989 close(fd);
1990 goto error;
1991 }
1992
1993 q = sess_data;
1994 todo = st.st_size;
1995 while (todo > 0) {
1996 rv = read(fd, q, todo);
1997 if (rv < 1) {
1998 RWDEBUG("(TLS) Failed reading persisted session: %s", fr_syserror(errno));
1999 close(fd);
2000 goto error;
2001 }
2002 todo -= rv;
2003 q += rv;
2004 }
2005 close(fd);
2006
2007 /*
2008 * OpenSSL mutates what's passed in, so we assign sess_data to q,
2009 * so the value of q gets mutated, and not the value of sess_data.
2010 *
2011 * We then need a pointer to hold &q, but it can't be const, because
2012 * clang complains about lack of consting in nested pointer types.
2013 *
2014 * So we memcpy the value of that pointer, to one that
2015 * does have a const, which we then pass into d2i_SSL_SESSION *sigh*.
2016 */
2017 q = sess_data;
2018 p = &q;
2019 memcpy(&o, &p, sizeof(o));
2020 sess = d2i_SSL_SESSION(NULL, o, st.st_size);
2021 if (!sess) {
2022 RWDEBUG("(TLS) Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
2023 goto error;
2024 }
2025
2026 /* read in the cached VPs from the .vps file */
2027 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2028 conf->session_cache_path, FR_DIR_SEP, buffer);
2029 rv = pairlist_read(talloc_ctx, filename, &pairlist, 1);
2030 if (rv < 0) {
2031 /* not safe to un-persist a session w/o VPs */
2032 RWDEBUG("(TLS) Failed loading persisted VPs for session %s", buffer);
2033 SSL_SESSION_free(sess);
2034 sess = NULL;
2035 goto error;
2036 }
2037
2038 /*
2039 * Enforce client certificate expiration.
2040 */
2041 vp = fr_pair_find_by_num(pairlist->reply, PW_TLS_CLIENT_CERT_EXPIRATION, 0, TAG_ANY);
2042 if (vp) {
2043 time_t expires;
2044
2045 if (ocsp_asn1time_to_epoch(&expires, vp->vp_strvalue) < 0) {
2046 RDEBUG2("Failed getting certificate expiration, removing cache entry for session %s - %s", buffer, fr_strerror());
2047 SSL_SESSION_free(sess);
2048 sess = NULL;
2049 goto error;
2050 }
2051
2052 if (expires <= request->timestamp) {
2053 RDEBUG2("Certificate has expired, removing cache entry for session %s", buffer);
2054 SSL_SESSION_free(sess);
2055 sess = NULL;
2056 goto error;
2057 }
2058
2059 /*
2060 * Account for Session-Timeout, if it's available.
2061 */
2062 vp = fr_pair_find_by_num(request->reply->vps, PW_SESSION_TIMEOUT, 0, TAG_ANY);
2063 if (vp) {
2064 if ((request->timestamp + vp->vp_integer) > expires) {
2065 vp->vp_integer = expires - request->timestamp;
2066 RWDEBUG2("(TLS) Updating Session-Timeout to %u, due to impending certificate expiration",
2067 vp->vp_integer);
2068 }
2069 }
2070 }
2071
2072 /*
2073 * Resumption MUST use the same EAP type as from
2074 * the original packet.
2075 */
2076 vp = fr_pair_find_by_num(pairlist->reply, PW_EAP_TYPE, 0, TAG_ANY);
2077 if (vp) {
2078 VALUE_PAIR *type = fr_pair_find_by_num(request->packet->vps, PW_EAP_TYPE, 0, TAG_ANY);
2079
2080 if (type && (type->vp_integer != vp->vp_integer)) {
2081 REDEBUG("Resumption has changed EAP types for session %s", buffer);
2082 REDEBUG("Rejecting session due to protocol violations");
2083 goto error;
2084 }
2085 }
2086
2087 /* move the cached VPs into the session */
2088 fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &pairlist->reply, 0, 0, TAG_ANY);
2089
2090 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
2091 RDEBUG("Successfully restored session %s", buffer);
2092 rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
2093
2094 /*
2095 * The "restore VPs from OpenSSL cache" code is
2096 * now in eaptls_process()
2097 */
2098 }
2099 error:
2100 if (sess_data) talloc_free(sess_data);
2101 if (pairlist) pairlist_free(&pairlist);
2102
2103 return sess;
2104 }
2105
tls_session_id_binary(SSL_SESSION * ssn,uint8_t * buffer,size_t bufsize)2106 static size_t tls_session_id_binary(SSL_SESSION *ssn, uint8_t *buffer, size_t bufsize)
2107 {
2108 #if OPENSSL_VERSION_NUMBER < 0x10001000L
2109 size_t size;
2110
2111 size = ssn->session_id_length;
2112 if (size > bufsize) size = bufsize;
2113
2114 memcpy(buffer, ssn->session_id, size);
2115 return size;
2116 #else
2117 unsigned int size;
2118 uint8_t const *p;
2119
2120 p = SSL_SESSION_get_id(ssn, &size);
2121 if (size > bufsize) size = bufsize;
2122
2123 memcpy(buffer, p, size);
2124 return size;
2125 #endif
2126 }
2127
2128 /*
2129 * From TLS-Cache-Method
2130 *
2131 * All of the save / clear / load callbacks are done with any
2132 * OpenSSL locks *unlocked*. So says the OpenSSL code.
2133 */
2134 #define CACHE_SAVE (1)
2135 #define CACHE_LOAD (2)
2136 #define CACHE_CLEAR (3)
2137 #define CACHE_REFRESH (4)
2138
cache_init_fake_request(fr_tls_server_conf_t const * conf,SSL_SESSION * sess,SSL * ssl,uint8_t const * data,size_t size)2139 static REQUEST *cache_init_fake_request(fr_tls_server_conf_t const *conf, SSL_SESSION *sess, SSL *ssl,
2140 uint8_t const *data, size_t size)
2141 {
2142 VALUE_PAIR *vp;
2143 REQUEST *fake, *request = NULL;
2144 uint8_t buffer[MAX_SESSION_SIZE];
2145
2146 if (sess) {
2147 size = tls_session_id_binary(sess, buffer, sizeof(buffer));
2148 data = buffer;
2149 }
2150
2151 /*
2152 * We get called essentially at random by OpenSSL, with
2153 * no information other than the session ID. As a
2154 * result, we have to manually set up our own request.
2155 */
2156 if (ssl) request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
2157
2158 if (request) {
2159 fake = request_alloc_fake(request);
2160 } else {
2161 fake = request_alloc(NULL);
2162 fake->packet = rad_alloc(fake, false);
2163 fake->reply = rad_alloc(fake, false);
2164 }
2165
2166 vp = fr_pair_afrom_num(fake->packet, PW_TLS_SESSION_ID, 0);
2167 if (!vp) {
2168 talloc_free(fake);
2169 return NULL;
2170 }
2171
2172 fr_pair_value_memcpy(vp, data, size);
2173 fr_pair_add(&fake->packet->vps, vp);
2174
2175 fake->server = conf->session_cache_server;
2176
2177 return fake;
2178 }
2179
2180 /*
2181 * Clear cached data
2182 */
cbtls_cache_clear(SSL_CTX * ctx,SSL_SESSION * sess)2183 static void cbtls_cache_clear(SSL_CTX *ctx, SSL_SESSION *sess)
2184 {
2185 fr_tls_server_conf_t *conf;
2186 REQUEST *fake;
2187
2188 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
2189 if (!conf) {
2190 DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
2191 return;
2192 }
2193
2194 /*
2195 * Find the SSL ID from the session, and delete it.
2196 *
2197 * Don't bother with any parent request. We're in a
2198 * timer callback, and there is no request available.
2199 */
2200 fake = cache_init_fake_request(conf, sess, NULL, NULL, 0);
2201 if (!fake) return;
2202
2203 /*
2204 * Use &request:TLS-Session-Id to clear the cache entry.
2205 */
2206 (void) process_post_auth(CACHE_CLEAR, fake);
2207 talloc_free(fake);
2208 return;
2209 }
2210
2211 /*
2212 * OpenSSL calls this function in order to save the session
2213 * BEFORE it has sent the final TLS success. So our process here
2214 * is to say "yes, we saved it", and then do the *actual* saving
2215 * after the TLS success has been sent.
2216 */
cbtls_cache_save(UNUSED SSL * ssl,UNUSED SSL_SESSION * sess)2217 static int cbtls_cache_save(UNUSED SSL *ssl, UNUSED SSL_SESSION *sess)
2218 {
2219 return 0;
2220 }
2221
cbtls_cache_save_vps(SSL * ssl,SSL_SESSION * sess,VALUE_PAIR * vps)2222 static int cbtls_cache_save_vps(SSL *ssl, SSL_SESSION *sess, VALUE_PAIR *vps)
2223 {
2224 fr_tls_server_conf_t *conf;
2225 VALUE_PAIR *vp;
2226 REQUEST *fake = NULL;
2227 size_t size, rv;
2228 uint8_t *p, *sess_blob = NULL;
2229
2230 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
2231 if (!conf) return 0;
2232
2233 /*
2234 * Find the SSL ID from the session, and save it.
2235 *
2236 * Save anything from the parent request.
2237 */
2238 fake = cache_init_fake_request(conf, sess, ssl, NULL, 0);
2239 if (!fake) return 0;
2240
2241 /* find out what length data we need */
2242 size = i2d_SSL_SESSION(sess, NULL);
2243 if (size < 1) return 0;
2244
2245 /* Do not convert to TALLOC - it's passed to OpenSSL */
2246 /* alloc and convert to ASN.1 */
2247 MEM(sess_blob = malloc(size));
2248
2249 /* openssl mutates &p */
2250 p = sess_blob;
2251 rv = i2d_SSL_SESSION(sess, &p);
2252 if (rv != size) goto error;
2253
2254 vp = fr_pair_afrom_num(fake->state_ctx, PW_TLS_SESSION_DATA, 0);
2255 if (!vp) goto error;
2256
2257 fr_pair_value_memcpy(vp, sess_blob, size);
2258 fr_pair_add(&fake->state, vp);
2259
2260 if (vps) fr_pair_add(&fake->reply->vps, fr_pair_list_copy(fake->reply, vps));
2261
2262 /*
2263 * Use &request:TLS-Session-Id to save the
2264 * &session-state:TLS-Session-Data values.
2265 *
2266 * The current &reply: list is the list of VPs which
2267 * should be cached.
2268 *
2269 * Any other attributes which need to be saved can be
2270 * read from the &outer.reply: list.
2271 */
2272 (void) process_post_auth(CACHE_SAVE, fake);
2273
2274 error:
2275 if (fake) talloc_free(fake);
2276 free(sess_blob);
2277
2278 return 0;
2279 }
2280
cbtls_cache_refresh(SSL * ssl,SSL_SESSION * sess)2281 static int cbtls_cache_refresh(SSL *ssl, SSL_SESSION *sess)
2282 {
2283 fr_tls_server_conf_t *conf;
2284 REQUEST *fake = NULL;
2285
2286 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
2287 if (!conf) return 0;
2288
2289 /*
2290 * Find the SSL ID from the session, and save it.
2291 *
2292 * Save anything from the parent request.
2293 */
2294 fake = cache_init_fake_request(conf, sess, ssl, NULL, 0);
2295 if (!fake) return 0;
2296 /*
2297 * Use &request:TLS-Session-Id to update the cache
2298 * entry so that it doesn't not expire.
2299 */
2300 (void) process_post_auth(CACHE_REFRESH, fake);
2301
2302 talloc_free(fake);
2303
2304 return 0;
2305 }
2306
2307 #if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
cbtls_cache_load(SSL * ssl,unsigned char * data,int len,int * copy)2308 static SSL_SESSION *cbtls_cache_load(SSL *ssl, unsigned char *data, int len, int *copy)
2309 #else
2310 static SSL_SESSION *cbtls_cache_load(SSL *ssl, const unsigned char *data, int len, int *copy)
2311 #endif
2312 {
2313 fr_tls_server_conf_t *conf;
2314 size_t size;
2315 uint8_t const *p;
2316 VALUE_PAIR *vp, *vps;
2317 TALLOC_CTX *talloc_ctx;
2318 SSL_SESSION *sess = NULL;
2319 REQUEST *fake = NULL;
2320 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
2321 char buffer[2 * MAX_SESSION_SIZE + 1];
2322
2323 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
2324 if (!conf) return NULL;
2325
2326 rad_assert(request);
2327
2328 size = len;
2329 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2330
2331 if (fr_debug_lvl > 1) {
2332 fr_bin2hex(buffer, data, size);
2333 RDEBUG2("Peer requested cached session: %s", buffer);
2334 }
2335
2336 *copy = 0;
2337
2338 /*
2339 * Take the given SSL ID, and create a fake request.
2340 *
2341 * Don't bother parenting it from another request. We do
2342 * this for a number of reasons.
2343 *
2344 * One is that rest of the code expects that the VPs will
2345 * be added to fr_tls_ex_index_vps. So we don't want to
2346 * be poking the request directly, as that will result in
2347 * a change of behavior.
2348 *
2349 * The larger reason is that we do _not_ want to actually
2350 * update the reply, until such time as we know that the
2351 * user has been authenticated.
2352 */
2353 fake = cache_init_fake_request(conf, NULL, NULL, data, size);
2354 if (!fake) return 0;
2355
2356 /*
2357 * Use &request:TLS-Session-Id to load the cached
2358 * session.
2359 *
2360 * The "cache load { ...}" section should put the reply
2361 * attributes into the &reply: list, and the
2362 * &session-state:TLS-Session-Data attribute.
2363 *
2364 * Why? Because v4 does it that way, and there aren't
2365 * really good reasons for doing it differently.
2366 */
2367 (void) process_post_auth(CACHE_LOAD, fake);
2368
2369 /*
2370 * Enforce client certificate expiration.
2371 */
2372 vp = fr_pair_find_by_num(fake->reply->vps, PW_TLS_CLIENT_CERT_EXPIRATION, 0, TAG_ANY);
2373 if (vp) {
2374 time_t expires;
2375
2376 if (ocsp_asn1time_to_epoch(&expires, vp->vp_strvalue) < 0) {
2377 RDEBUG2("Failed getting certificate expiration, removing cache entry for session %s - %s", buffer, fr_strerror());
2378 SSL_SESSION_free(sess);
2379 sess = NULL;
2380 goto error;
2381 }
2382
2383 if (expires <= request->timestamp) {
2384 RDEBUG2("Certificate has expired, removing cache entry for session %s", buffer);
2385 SSL_SESSION_free(sess);
2386 sess = NULL;
2387 goto error;
2388 }
2389
2390 /*
2391 * Account for Session-Timeout, if it's available.
2392 */
2393 vp = fr_pair_find_by_num(request->reply->vps, PW_SESSION_TIMEOUT, 0, TAG_ANY);
2394 if (vp) {
2395 if ((request->timestamp + vp->vp_integer) > expires) {
2396 vp->vp_integer = expires - request->timestamp;
2397 RWDEBUG2("(TLS) Updating Session-Timeout to %u, due to impending certificate expiration",
2398 vp->vp_integer);
2399 }
2400 }
2401 }
2402
2403 /*
2404 * Try to de-serialize the session data.
2405 */
2406 vp = fr_pair_find_by_num(fake->state, PW_TLS_SESSION_DATA, 0, TAG_ANY);
2407 if (!vp) {
2408 RWDEBUG("(TLS) Failed to find TLS-Session-Data in 'session-state' list for session %s", buffer);
2409 goto error;
2410 }
2411
2412 /*
2413 * OpenSSL mutates what's passed in, so we assign sess_data to q,
2414 * so the value of q gets mutated, and not the value of sess_data.
2415 *
2416 * We then need a pointer to hold &q, but it can't be const, because
2417 * clang complains about lack of consting in nested pointer types.
2418 *
2419 * So we memcpy the value of that pointer, to one that
2420 * does have a const, which we then pass into d2i_SSL_SESSION *sigh*.
2421 */
2422 p = vp->vp_octets;
2423 sess = d2i_SSL_SESSION(NULL, &p, vp->vp_length);
2424 if (!sess) {
2425 RWDEBUG("(TLS) Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
2426 goto error;
2427 }
2428
2429 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
2430 vps = NULL;
2431
2432 /* move the cached VPs into the session */
2433 fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &fake->reply->vps, 0, 0, TAG_ANY);
2434
2435 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
2436 RDEBUG("Successfully restored session %s", buffer);
2437 rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
2438
2439 /*
2440 * The "restore VPs from OpenSSL cache" code is
2441 * now in eaptls_process()
2442 */
2443
2444 error:
2445 if (fake) talloc_free(fake);
2446
2447 return sess;
2448 }
2449
2450 #ifdef HAVE_OPENSSL_OCSP_H
2451
2452 /** Extract components of OCSP responser URL from a certificate
2453 *
2454 * @param[in] cert to extract URL from.
2455 * @param[out] host_out Portion of the URL (must be freed with free()).
2456 * @param[out] port_out Port portion of the URL (must be freed with free()).
2457 * @param[out] path_out Path portion of the URL (must be freed with free()).
2458 * @param[out] is_https Whether the responder should be contacted using https.
2459 * @return
2460 * - 0 if no valid URL is contained in the certificate.
2461 * - 1 if a URL was found and parsed.
2462 * - -1 if at least one URL was found, but none could be parsed.
2463 */
ocsp_parse_cert_url(X509 * cert,char ** host_out,char ** port_out,char ** path_out,int * is_https)2464 static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out,
2465 char **path_out, int *is_https)
2466 {
2467 int i;
2468 bool found_uri = false;
2469
2470 AUTHORITY_INFO_ACCESS *aia;
2471 ACCESS_DESCRIPTION *ad;
2472
2473 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
2474
2475 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
2476 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
2477 if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
2478 if (ad->location->type != GEN_URI) continue;
2479 found_uri = true;
2480
2481 if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
2482 port_out, path_out, is_https)) return 1;
2483 }
2484 return found_uri ? -1 : 0;
2485 }
2486
2487 /*
2488 * This function sends a OCSP request to a defined OCSP responder
2489 * and checks the OCSP response for correctness.
2490 */
2491
2492 /* Maximum leeway in validity period: default 5 minutes */
2493 #define MAX_VALIDITY_PERIOD (5 * 60)
2494
2495 typedef enum {
2496 OCSP_STATUS_FAILED = 0,
2497 OCSP_STATUS_OK = 1,
2498 OCSP_STATUS_SKIPPED = 2,
2499 } ocsp_status_t;
2500
ocsp_check(REQUEST * request,X509_STORE * store,X509 * issuer_cert,X509 * client_cert,fr_tls_server_conf_t * conf)2501 static ocsp_status_t ocsp_check(REQUEST *request, X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
2502 fr_tls_server_conf_t *conf)
2503 {
2504 OCSP_CERTID *certid;
2505 OCSP_REQUEST *req;
2506 OCSP_RESPONSE *resp = NULL;
2507 OCSP_BASICRESP *bresp = NULL;
2508 char *host = NULL;
2509 char *port = NULL;
2510 char *path = NULL;
2511 char hostheader[1024];
2512 int use_ssl = -1;
2513 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
2514 BIO *cbio, *bio_out;
2515 ocsp_status_t ocsp_status = OCSP_STATUS_FAILED;
2516 int status;
2517 ASN1_GENERALIZEDTIME *rev = NULL, *thisupd, *nextupd;
2518 int reason;
2519 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
2520 OCSP_REQ_CTX *ctx;
2521 int rc;
2522 struct timeval now;
2523 struct timeval when;
2524 #endif
2525 VALUE_PAIR *vp;
2526
2527 if (issuer_cert == NULL) {
2528 RWDEBUG("(TLS) Could not get issuer certificate");
2529 goto skipped;
2530 }
2531
2532 /*
2533 * Create OCSP Request
2534 */
2535 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
2536 req = OCSP_REQUEST_new();
2537 OCSP_request_add0_id(req, certid);
2538 if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
2539
2540 /*
2541 * Send OCSP Request and get OCSP Response
2542 */
2543
2544 /* Get OCSP responder URL */
2545 if (conf->ocsp_override_url) {
2546 char *url;
2547
2548 use_ocsp_url:
2549 memcpy(&url, &conf->ocsp_url, sizeof(url));
2550 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
2551 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
2552 if (!host || !port || !path) {
2553 RWDEBUG("(TLS) ocsp: Host or port or path missing from configured URL \"%s\". Not doing OCSP", url);
2554 goto skipped;
2555 }
2556 } else {
2557 int ret;
2558
2559 ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
2560 switch (ret) {
2561 case -1:
2562 RWDEBUG("(TLS) ocsp: Invalid URL in certificate. Not doing OCSP");
2563 break;
2564
2565 case 0:
2566 if (conf->ocsp_url) {
2567 RWDEBUG("(TLS) ocsp: No OCSP URL in certificate, falling back to configured URL");
2568 goto use_ocsp_url;
2569 }
2570 RWDEBUG("(TLS) ocsp: No OCSP URL in certificate. Not doing OCSP");
2571 goto skipped;
2572
2573 case 1:
2574 break;
2575 }
2576 }
2577
2578 RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
2579
2580 /* Check host and port length are sane, then create Host: HTTP header */
2581 if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
2582 RWDEBUG("(TLS) ocsp: Host and port too long");
2583 goto skipped;
2584 }
2585 snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
2586
2587 /* Setup BIO socket to OCSP responder */
2588 cbio = BIO_new_connect(host);
2589
2590 bio_out = NULL;
2591 if (rad_debug_lvl) {
2592 if (default_log.dst == L_DST_STDOUT) {
2593 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
2594 } else if (default_log.dst == L_DST_STDERR) {
2595 bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
2596 }
2597 }
2598
2599 BIO_set_conn_port(cbio, port);
2600 #if OPENSSL_VERSION_NUMBER < 0x1000003f
2601 BIO_do_connect(cbio);
2602
2603 /* Send OCSP request and wait for response */
2604 resp = OCSP_sendreq_bio(cbio, path, req);
2605 if (!resp) {
2606 REDEBUG("ocsp: Couldn't get OCSP response");
2607 ocsp_status = OCSP_STATUS_SKIPPED;
2608 goto ocsp_end;
2609 }
2610 #else
2611 if (conf->ocsp_timeout)
2612 BIO_set_nbio(cbio, 1);
2613
2614 rc = BIO_do_connect(cbio);
2615 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
2616 REDEBUG("ocsp: Couldn't connect to OCSP responder");
2617 ocsp_status = OCSP_STATUS_SKIPPED;
2618 goto ocsp_end;
2619 }
2620
2621 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
2622 if (!ctx) {
2623 REDEBUG("ocsp: Couldn't create OCSP request");
2624 ocsp_status = OCSP_STATUS_SKIPPED;
2625 goto ocsp_end;
2626 }
2627
2628 if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
2629 REDEBUG("ocsp: Couldn't set Host header");
2630 ocsp_status = OCSP_STATUS_SKIPPED;
2631 goto ocsp_end;
2632 }
2633
2634 if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
2635 REDEBUG("ocsp: Couldn't add data to OCSP request");
2636 ocsp_status = OCSP_STATUS_SKIPPED;
2637 goto ocsp_end;
2638 }
2639
2640 gettimeofday(&when, NULL);
2641 when.tv_sec += conf->ocsp_timeout;
2642
2643 do {
2644 rc = OCSP_sendreq_nbio(&resp, ctx);
2645 if (conf->ocsp_timeout) {
2646 gettimeofday(&now, NULL);
2647 if (!timercmp(&now, &when, <))
2648 break;
2649 }
2650 } while ((rc == -1) && BIO_should_retry(cbio));
2651
2652 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
2653 REDEBUG("ocsp: Response timed out");
2654 ocsp_status = OCSP_STATUS_SKIPPED;
2655 goto ocsp_end;
2656 }
2657
2658 OCSP_REQ_CTX_free(ctx);
2659
2660 if (rc == 0) {
2661 REDEBUG("ocsp: Couldn't get OCSP response");
2662 ocsp_status = OCSP_STATUS_SKIPPED;
2663 goto ocsp_end;
2664 }
2665 #endif
2666
2667 /* Verify OCSP response status */
2668 status = OCSP_response_status(resp);
2669 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
2670 REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
2671 goto ocsp_end;
2672 }
2673 bresp = OCSP_response_get1_basic(resp);
2674 if (!bresp) {
2675 RDEBUG("ocsp: Failed parsing response");
2676 goto ocsp_end;
2677 }
2678
2679 if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
2680 REDEBUG("ocsp: Response has wrong nonce value");
2681 goto ocsp_end;
2682 }
2683 if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
2684 REDEBUG("ocsp: Couldn't verify OCSP basic response");
2685 goto ocsp_end;
2686 }
2687
2688 /* Verify OCSP cert status */
2689 if (!OCSP_resp_find_status(bresp, certid, &status, &reason, &rev, &thisupd, &nextupd)) {
2690 REDEBUG("ocsp: No Status found");
2691 goto ocsp_end;
2692 }
2693
2694 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
2695 if (bio_out) {
2696 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
2697 ERR_print_errors(bio_out);
2698 }
2699 goto ocsp_end;
2700 }
2701
2702 if (bio_out) {
2703 BIO_puts(bio_out, "\tThis Update: ");
2704 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
2705 BIO_puts(bio_out, "\n");
2706 if (nextupd) {
2707 BIO_puts(bio_out, "\tNext Update: ");
2708 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
2709 BIO_puts(bio_out, "\n");
2710 }
2711 }
2712
2713 switch (status) {
2714 case V_OCSP_CERTSTATUS_GOOD:
2715 RDEBUG2("ocsp: Cert status: good");
2716 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
2717 vp->vp_integer = 1; /* yes */
2718 ocsp_status = OCSP_STATUS_OK;
2719 break;
2720
2721 default:
2722 /* REVOKED / UNKNOWN */
2723 REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
2724 if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
2725
2726 if (bio_out && rev) {
2727 BIO_puts(bio_out, "\tRevocation Time: ");
2728 ASN1_GENERALIZEDTIME_print(bio_out, rev);
2729 BIO_puts(bio_out, "\n");
2730 }
2731 break;
2732 }
2733
2734 ocsp_end:
2735 /* Free OCSP Stuff */
2736 OCSP_REQUEST_free(req);
2737 OCSP_RESPONSE_free(resp);
2738 free(host);
2739 free(port);
2740 free(path);
2741 BIO_free_all(cbio);
2742 if (bio_out) BIO_free(bio_out);
2743 OCSP_BASICRESP_free(bresp);
2744
2745 switch (ocsp_status) {
2746 case OCSP_STATUS_OK:
2747 RDEBUG2("ocsp: Certificate is valid");
2748 break;
2749
2750 case OCSP_STATUS_SKIPPED:
2751 skipped:
2752 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
2753 vp->vp_integer = 2; /* skipped */
2754 if (conf->ocsp_softfail) {
2755 RWDEBUG("(TLS) ocsp: Unable to check certificate, assuming it's valid");
2756 RWDEBUG("(TLS) ocsp: This may be insecure");
2757
2758 /* Remove OpenSSL errors from queue or handshake will fail */
2759 while (ERR_get_error());
2760
2761 ocsp_status = OCSP_STATUS_SKIPPED;
2762 } else {
2763 REDEBUG("(TLS) ocsp: Unable to check certificate, failing");
2764 ocsp_status = OCSP_STATUS_FAILED;
2765 }
2766 break;
2767
2768 default:
2769 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
2770 vp->vp_integer = 0; /* no */
2771 REDEBUG("(TLS) ocsp: Certificate has been expired/revoked");
2772 break;
2773 }
2774
2775 return ocsp_status;
2776 }
2777 #endif /* HAVE_OPENSSL_OCSP_H */
2778
2779 /*
2780 * For creating certificate attributes.
2781 */
2782 static char const *cert_attr_names[9][2] = {
2783 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
2784 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
2785 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
2786 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
2787 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
2788 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
2789 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
2790 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" },
2791 { "TLS-Client-Cert-Valid-Since", "TLS-Cert-Valid-Since" }
2792 };
2793
2794 #define FR_TLS_SERIAL (0)
2795 #define FR_TLS_EXPIRATION (1)
2796 #define FR_TLS_SUBJECT (2)
2797 #define FR_TLS_ISSUER (3)
2798 #define FR_TLS_CN (4)
2799 #define FR_TLS_SAN_EMAIL (5)
2800 #define FR_TLS_SAN_DNS (6)
2801 #define FR_TLS_SAN_UPN (7)
2802 #define FR_TLS_VALID_SINCE (8)
2803
2804 static const char *cert_names[2] = {
2805 "client", "server",
2806 };
2807
2808 /*
2809 * Before trusting a certificate, you must make sure that the
2810 * certificate is 'valid'. There are several steps that your
2811 * application can take in determining if a certificate is
2812 * valid. Commonly used steps are:
2813 *
2814 * 1.Verifying the certificate's signature, and verifying that
2815 * the certificate has been issued by a trusted Certificate
2816 * Authority.
2817 *
2818 * 2.Verifying that the certificate is valid for the present date
2819 * (i.e. it is being presented within its validity dates).
2820 *
2821 * 3.Verifying that the certificate has not been revoked by its
2822 * issuing Certificate Authority, by checking with respect to a
2823 * Certificate Revocation List (CRL).
2824 *
2825 * 4.Verifying that the credentials presented by the certificate
2826 * fulfill additional requirements specific to the application,
2827 * such as with respect to access control lists or with respect
2828 * to OCSP (Online Certificate Status Processing).
2829 *
2830 * NOTE: This callback will be called multiple times based on the
2831 * depth of the root certificate chain
2832 */
cbtls_verify(int ok,X509_STORE_CTX * ctx)2833 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
2834 {
2835 char subject[1024]; /* Used for the subject name */
2836 char issuer[1024]; /* Used for the issuer name */
2837 char attribute[1024];
2838 char value[1024];
2839 char common_name[1024];
2840 char cn_str[1024];
2841 char buf[64];
2842 X509 *client_cert;
2843 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
2844 const STACK_OF(X509_EXTENSION) *ext_list;
2845 #else
2846 STACK_OF(X509_EXTENSION) *ext_list;
2847 #endif
2848 SSL *ssl;
2849 int err, depth, lookup, loc;
2850 fr_tls_server_conf_t *conf;
2851 int my_ok = ok;
2852
2853 ASN1_INTEGER *sn = NULL;
2854 ASN1_TIME *asn_time = NULL;
2855 VALUE_PAIR **certs;
2856 char **identity;
2857 #ifdef HAVE_OPENSSL_OCSP_H
2858 X509_STORE *ocsp_store = NULL;
2859 X509 *issuer_cert;
2860 bool do_verify = false;
2861 #endif
2862 VALUE_PAIR *vp;
2863 TALLOC_CTX *talloc_ctx;
2864
2865 REQUEST *request;
2866
2867 client_cert = X509_STORE_CTX_get_current_cert(ctx);
2868 err = X509_STORE_CTX_get_error(ctx);
2869 depth = X509_STORE_CTX_get_error_depth(ctx);
2870
2871 lookup = depth;
2872
2873 /*
2874 * Log client/issuing cert. If there's an error, log
2875 * issuing cert.
2876 */
2877 if ((lookup > 1) && !my_ok) lookup = 1;
2878
2879 /*
2880 * Retrieve the pointer to the SSL of the connection currently treated
2881 * and the application specific data stored into the SSL object.
2882 */
2883 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
2884 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
2885 if (!conf) return 1;
2886
2887 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
2888 rad_assert(request != NULL);
2889 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
2890
2891 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
2892 #ifdef HAVE_OPENSSL_OCSP_H
2893 ocsp_store = conf->ocsp_store;
2894 #endif
2895
2896 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
2897
2898 /*
2899 * Get the Serial Number
2900 */
2901 buf[0] = '\0';
2902 sn = X509_get_serialNumber(client_cert);
2903
2904 RDEBUG2("(TLS) Creating attributes from %s certificate", cert_names[lookup]);
2905 RINDENT();
2906
2907 /*
2908 * For this next bit, we create the attributes *only* if
2909 * we're at the client or issuing certificate.
2910 */
2911 if (certs &&
2912 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
2913 char *p = buf;
2914 int i;
2915
2916 for (i = 0; i < sn->length; i++) {
2917 sprintf(p, "%02x", (unsigned int)sn->data[i]);
2918 p += 2;
2919 }
2920 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
2921 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2922 }
2923
2924 /*
2925 * Get the Expiration Date
2926 */
2927 buf[0] = '\0';
2928 asn_time = X509_get_notAfter(client_cert);
2929 if (certs && (lookup <= 1) && asn_time &&
2930 (asn_time->length < (int) sizeof(buf))) {
2931 memcpy(buf, (char*) asn_time->data, asn_time->length);
2932 buf[asn_time->length] = '\0';
2933 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
2934 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2935 }
2936
2937 /*
2938 * Get the Valid Since Date
2939 */
2940 buf[0] = '\0';
2941 asn_time = X509_get_notBefore(client_cert);
2942 if (certs && (lookup <= 1) && asn_time &&
2943 (asn_time->length < (int) sizeof(buf))) {
2944 memcpy(buf, (char*) asn_time->data, asn_time->length);
2945 buf[asn_time->length] = '\0';
2946 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_VALID_SINCE][lookup], buf, T_OP_SET);
2947 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2948 }
2949
2950 /*
2951 * Get the Subject & Issuer
2952 */
2953 subject[0] = issuer[0] = '\0';
2954 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
2955 sizeof(subject));
2956 subject[sizeof(subject) - 1] = '\0';
2957 if (certs && (lookup <= 1) && subject[0]) {
2958 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
2959 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2960 }
2961
2962 X509_NAME_oneline(X509_get_issuer_name(client_cert), issuer,
2963 sizeof(issuer));
2964 issuer[sizeof(issuer) - 1] = '\0';
2965 if (certs && (lookup <= 1) && issuer[0]) {
2966 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
2967 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2968 }
2969
2970 /*
2971 * Get the Common Name, if there is a subject.
2972 */
2973 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
2974 NID_commonName, common_name, sizeof(common_name));
2975 common_name[sizeof(common_name) - 1] = '\0';
2976 if (certs && (lookup <= 1) && common_name[0] && subject[0]) {
2977 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
2978 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2979 }
2980
2981 /*
2982 * Get the RFC822 Subject Alternative Name
2983 */
2984 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, -1);
2985 if (certs && (lookup <= 1) && (loc >= 0)) {
2986 X509_EXTENSION *ext = NULL;
2987 GENERAL_NAMES *names = NULL;
2988 int i;
2989
2990 if ((ext = X509_get_ext(client_cert, loc)) &&
2991 (names = X509V3_EXT_d2i(ext))) {
2992 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
2993 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2994
2995 switch (name->type) {
2996 #ifdef GEN_EMAIL
2997 case GEN_EMAIL:
2998 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
2999 (char const *) ASN1_STRING_get0_data(name->d.rfc822Name), T_OP_SET);
3000 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
3001 break;
3002 #endif /* GEN_EMAIL */
3003 #ifdef GEN_DNS
3004 case GEN_DNS:
3005 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
3006 (char const *) ASN1_STRING_get0_data(name->d.dNSName), T_OP_SET);
3007 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
3008 break;
3009 #endif /* GEN_DNS */
3010 #ifdef GEN_OTHERNAME
3011 case GEN_OTHERNAME:
3012 /* look for a MS UPN */
3013 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
3014 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
3015 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
3016 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
3017 (char const *) ASN1_STRING_get0_data(name->d.otherName->value->value.utf8string), T_OP_SET);
3018 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
3019 break;
3020 } else {
3021 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
3022 break;
3023 }
3024 }
3025 break;
3026 #endif /* GEN_OTHERNAME */
3027 default:
3028 /* XXX TODO handle other SAN types */
3029 break;
3030 }
3031 }
3032 }
3033 if (names != NULL)
3034 GENERAL_NAMES_free(names);
3035 }
3036
3037 /*
3038 * If the CRL has expired, that might still be OK.
3039 */
3040 if (!my_ok &&
3041 (conf->allow_expired_crl) &&
3042 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
3043 my_ok = 1;
3044 X509_STORE_CTX_set_error( ctx, 0 );
3045 }
3046
3047 if (!my_ok) {
3048 char const *p = X509_verify_cert_error_string(err);
3049 RERROR("(TLS) OpenSSL says error %d : %s", err, p);
3050 REXDENT();
3051
3052 /*
3053 * Copy certs even on failure so that they can be logged.
3054 */
3055 if (certs && request) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3056
3057 return my_ok;
3058 }
3059
3060 if (lookup == 0) {
3061 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
3062 ext_list = X509_get0_extensions(client_cert);
3063 #else
3064 X509_CINF *client_inf;
3065 client_inf = client_cert->cert_info;
3066 ext_list = client_inf->extensions;
3067 #endif
3068 } else {
3069 ext_list = NULL;
3070 }
3071
3072 /*
3073 * Grab the X509 extensions, and create attributes out of them.
3074 * For laziness, we re-use the OpenSSL names
3075 */
3076 if (certs && (sk_X509_EXTENSION_num(ext_list) > 0)) {
3077 int i, len;
3078 EXTENDED_KEY_USAGE *eku;
3079 char *p;
3080 BIO *out;
3081
3082 out = BIO_new(BIO_s_mem());
3083 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
3084
3085 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
3086 ASN1_OBJECT *obj;
3087 X509_EXTENSION *ext;
3088
3089 ext = sk_X509_EXTENSION_value(ext_list, i);
3090
3091 obj = X509_EXTENSION_get_object(ext);
3092 i2a_ASN1_OBJECT(out, obj);
3093 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
3094 if (len <= 0) continue;
3095
3096 attribute[16 + len] = '\0';
3097
3098 for (p = attribute + 16; *p != '\0'; p++) {
3099 if (*p == ' ') *p = '-';
3100 }
3101
3102 if (X509V3_EXT_get(ext)) { /* Known extension, converting value into plain string */
3103 X509V3_EXT_print(out, ext, 0, 0);
3104 len = BIO_read(out, value, sizeof(value) - 1);
3105 if (len <= 0) continue;
3106 value[len] = '\0';
3107 } else {
3108 /*
3109 * An extension not known to OpenSSL, dump it's value as a value of an unknown attribute.
3110 */
3111 value[0] = '0';
3112 value[1] = 'x';
3113 const unsigned char *srcp;
3114 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
3115 const ASN1_STRING *srcasn1p;
3116 srcasn1p = X509_EXTENSION_get_data(ext);
3117 srcp = ASN1_STRING_get0_data(srcasn1p);
3118 #else
3119 ASN1_STRING *srcasn1p;
3120 srcasn1p = X509_EXTENSION_get_data(ext);
3121 srcp = ASN1_STRING_data(srcasn1p);
3122 #endif
3123 int asn1len = ASN1_STRING_length(srcasn1p);
3124 /* 3 comes from '0x' + \0 */
3125 if ((size_t)(asn1len << 1) >= sizeof(value) - 3) {
3126 RDEBUG("Value of '%s' attribute is too long to be stored, it will be truncated", attribute);
3127 asn1len = (sizeof(value) - 3) >> 1;
3128 }
3129 fr_bin2hex(value + 2, srcp, asn1len);
3130 }
3131
3132 vp = fr_pair_make(talloc_ctx, certs, attribute, value, T_OP_ADD);
3133 if (!vp) {
3134 RDEBUG3("Skipping %s += '%s'. Please check that both the "
3135 "attribute and value are defined in the dictionaries",
3136 attribute, value);
3137 } else {
3138 /*
3139 * rdebug_pair_list indents (so pre REXDENT())
3140 */
3141 REXDENT();
3142 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
3143 RINDENT();
3144 }
3145 }
3146
3147 BIO_free_all(out);
3148
3149 /* Export raw EKU OIDs to allow matching a single OID regardless of its name */
3150 eku = X509_get_ext_d2i(client_cert, NID_ext_key_usage, NULL, NULL);
3151 if (eku != NULL) {
3152 for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
3153 len = OBJ_obj2txt(value, sizeof(value), sk_ASN1_OBJECT_value(eku, i), 1);
3154 if ((len > 0) && ((unsigned) len < sizeof(value))) {
3155 vp = fr_pair_make(talloc_ctx, certs,
3156 "TLS-Client-Cert-X509v3-Extended-Key-Usage-OID",
3157 value, T_OP_ADD);
3158 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
3159 }
3160 else {
3161 RDEBUG("Failed to get EKU OID at index %d", i);
3162 }
3163 }
3164 EXTENDED_KEY_USAGE_free(eku);
3165 }
3166 }
3167
3168 REXDENT();
3169
3170 switch (X509_STORE_CTX_get_error(ctx)) {
3171 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
3172 RERROR("(TLS) unable to get issuer certificate for issuer=%s", issuer);
3173 break;
3174
3175 case X509_V_ERR_CERT_NOT_YET_VALID:
3176 RERROR("(TLS) Failed with certificate not yet valid.");
3177 break;
3178
3179 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
3180 RERROR("(TLS) Failed with error in certificate 'not before' field.");
3181 #if 0
3182 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
3183 #endif
3184 break;
3185
3186 case X509_V_ERR_CERT_HAS_EXPIRED:
3187 RERROR("(TLS) Failed with certificate has expired.");
3188 break;
3189
3190 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
3191 RERROR("(TLS) Failed with err in certificate 'no after' field..");
3192 break;
3193
3194 #if 0
3195 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
3196 #endif
3197 break;
3198 }
3199
3200 /*
3201 * If we're at the actual client cert, apply additional
3202 * checks.
3203 */
3204 if (depth == 0) {
3205 tls_session_t *ssn = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_SSN);
3206 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3207 STACK_OF(X509)* untrusted = NULL;
3208 #endif
3209
3210 rad_assert(ssn != NULL);
3211
3212 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3213 /*
3214 * See if there are any untrusted certificates.
3215 * If so, complain about them.
3216 */
3217 untrusted = X509_STORE_CTX_get0_untrusted(ctx);
3218 if (untrusted) {
3219 if (conf->disallow_untrusted || RDEBUG_ENABLED2) {
3220 int i;
3221
3222 WARN("Certificate chain - %i cert(s) untrusted",
3223 X509_STORE_CTX_get_num_untrusted(ctx));
3224 for (i = sk_X509_num(untrusted); i > 0 ; i--) {
3225 X509 *this_cert = sk_X509_value(untrusted, i - 1);
3226
3227 X509_NAME_oneline(X509_get_subject_name(this_cert), subject, sizeof(subject));
3228 subject[sizeof(subject) - 1] = '\0';
3229
3230 WARN("(TLS) untrusted certificate with depth [%i] subject name %s",
3231 i - 1, subject);
3232 }
3233 }
3234
3235 if (conf->disallow_untrusted) {
3236 AUTH(LOG_PREFIX ": There are untrusted certificates in the certificate chain. Rejecting.");
3237 my_ok = 0;
3238 }
3239 }
3240 #endif
3241
3242 /*
3243 * If the conf tells us to, check cert issuer
3244 * against the specified value and fail
3245 * verification if they don't match.
3246 */
3247 if (my_ok && conf->check_cert_issuer &&
3248 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
3249 AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
3250 issuer, conf->check_cert_issuer);
3251 my_ok = 0;
3252 }
3253
3254 /*
3255 * If the conf tells us to, check the CN in the
3256 * cert against xlat'ed value, but only if the
3257 * previous checks passed.
3258 */
3259 if (my_ok && conf->check_cert_cn) {
3260 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
3261 /* if this fails, fail the verification */
3262 my_ok = 0;
3263 } else {
3264 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
3265 if (strcmp(cn_str, common_name) != 0) {
3266 AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
3267 common_name, cn_str);
3268 my_ok = 0;
3269 }
3270 }
3271 } /* check_cert_cn */
3272
3273 #ifdef HAVE_OPENSSL_OCSP_H
3274 if (my_ok) {
3275 /*
3276 * No OCSP, allow external verification.
3277 */
3278 if (!conf->ocsp_enable) {
3279 do_verify = true;
3280
3281 } else {
3282 RDEBUG2("Starting OCSP Request");
3283
3284 /*
3285 * If we don't have an issuer, then we can't send
3286 * and OCSP request, but pass the NULL issuer in
3287 * so ocsp_check can decide on the correct
3288 * return code.
3289 */
3290 issuer_cert = X509_STORE_CTX_get0_current_issuer(ctx);
3291
3292 /*
3293 * Do the full OCSP checks.
3294 *
3295 * If they fail, don't run the external verify. We don't want
3296 * to allow admins to force authentication success for bad
3297 * certificates.
3298 *
3299 * If the OCSP checks succeed, check whether we still want to
3300 * run the external verification routine. If it's marked as
3301 * "skip verify on OK", then we don't do verify.
3302 */
3303 my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
3304 if (my_ok != OCSP_STATUS_FAILED) {
3305 do_verify = !conf->verify_skip_if_ocsp_ok;
3306 }
3307 }
3308 }
3309 #endif
3310
3311 if ((my_ok != OCSP_STATUS_FAILED)
3312 #ifdef HAVE_OPENSSL_OCSP_H
3313 && do_verify
3314 #endif
3315 ) while (conf->verify_client_cert_cmd) {
3316 char filename[3 * MAX_SESSION_SIZE + 1];
3317 int fd;
3318 FILE *fp;
3319
3320 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
3321 conf->verify_tmp_dir, main_config.name);
3322 fd = mkstemp(filename);
3323 if (fd < 0) {
3324 RDEBUG("Failed creating file in %s: %s",
3325 conf->verify_tmp_dir, fr_syserror(errno));
3326 break;
3327 }
3328
3329 fp = fdopen(fd, "w");
3330 if (!fp) {
3331 close(fd);
3332 RDEBUG("Failed opening file %s: %s",
3333 filename, fr_syserror(errno));
3334 break;
3335 }
3336
3337 if (!PEM_write_X509(fp, client_cert)) {
3338 fclose(fp);
3339 RDEBUG("Failed writing certificate to file");
3340 goto do_unlink;
3341 }
3342 fclose(fp);
3343
3344 if (!pair_make_request("TLS-Client-Cert-Filename",
3345 filename, T_OP_SET)) {
3346 RDEBUG("Failed creating TLS-Client-Cert-Filename");
3347
3348 goto do_unlink;
3349 }
3350
3351 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
3352 if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
3353 request->packet->vps,
3354 true, true, EXEC_TIMEOUT) != 0) {
3355 AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
3356 my_ok = 0;
3357
3358 } else if (request) {
3359 RDEBUG("Client certificate CN %s passed external validation", common_name);
3360 }
3361
3362 do_unlink:
3363 unlink(filename);
3364 break;
3365 }
3366
3367 /*
3368 * Track that we've verified the client certificate.
3369 */
3370 ssn->client_cert_ok = (my_ok == 1);
3371 } /* depth == 0 */
3372
3373 /*
3374 * Copy certs to request even on failure, so that the
3375 * user can log them.
3376 */
3377 if (certs && request && !my_ok) {
3378 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3379 }
3380
3381 if (RDEBUG_ENABLED3) {
3382 RDEBUG3("(TLS) chain-depth : %d", depth);
3383 RDEBUG3("(TLS) error : %d", err);
3384
3385 if (identity) RDEBUG3("identity : %s", *identity);
3386 RDEBUG3("(TLS) common name : %s", common_name);
3387 RDEBUG3("(TLS) subject : %s", subject);
3388 RDEBUG3("(TLS) issuer : %s", issuer);
3389 RDEBUG3("(TLS) verify return : %d", my_ok);
3390 }
3391
3392 return (my_ok != 0);
3393 }
3394
3395
3396 /*
3397 * Configure a X509 CA store to verify OCSP or client repsonses
3398 *
3399 * - Load the trusted CAs
3400 * - Load the trusted issuer certificates
3401 * - Configure CRLs check if needed
3402 */
fr_init_x509_store(fr_tls_server_conf_t * conf)3403 X509_STORE *fr_init_x509_store(fr_tls_server_conf_t *conf)
3404 {
3405 X509_STORE *store = X509_STORE_new();
3406
3407 if (store == NULL) return NULL;
3408
3409 /* Load the CAs we trust */
3410 if (conf->ca_file || conf->ca_path)
3411 if (!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
3412 tls_error_log(NULL, "Error reading Trusted root CA list \"%s\"", conf->ca_file);
3413 X509_STORE_free(store);
3414 return NULL;
3415 }
3416
3417 #ifdef X509_V_FLAG_CRL_CHECK
3418 if (conf->check_crl)
3419 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
3420 #endif
3421 #ifdef X509_V_FLAG_CRL_CHECK_ALL
3422 if (conf->check_all_crl)
3423 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
3424 #endif
3425 return store;
3426 }
3427
3428 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
3429 #ifndef OPENSSL_NO_ECDH
set_ecdh_curve(SSL_CTX * ctx,char const * ecdh_curve,bool disable_single_dh_use)3430 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
3431 {
3432 int nid;
3433 EC_KEY *ecdh;
3434
3435 if (!disable_single_dh_use) {
3436 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
3437 }
3438
3439 if (!ecdh_curve || !*ecdh_curve) return 0;
3440
3441 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
3442 if (strchr(ecdh_curve, ':') != 0) {
3443 char *list = strdup(ecdh_curve);
3444
3445 if (SSL_CTX_set1_curves_list(ctx, list) == 0) {
3446 free(list);
3447 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
3448 return -1;
3449 }
3450 free(list);
3451
3452 (void) SSL_CTX_set_ecdh_auto(ctx, 1);
3453 return 0;
3454 }
3455
3456 /*
3457 * Just pick the right curve.
3458 */
3459 if (ecdh_curve && !*ecdh_curve) {
3460 (void) SSL_CTX_set_ecdh_auto(ctx, 1);
3461 }
3462 #endif
3463
3464 nid = OBJ_sn2nid(ecdh_curve);
3465 if (!nid) {
3466 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
3467 return -1;
3468 }
3469
3470 ecdh = EC_KEY_new_by_curve_name(nid);
3471 if (!ecdh) {
3472 ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
3473 return -1;
3474 }
3475
3476 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
3477
3478 EC_KEY_free(ecdh);
3479
3480 return 0;
3481 }
3482 #endif
3483 #endif
3484
3485 /** Add all the default ciphers and message digests reate our context.
3486 *
3487 * This should be called exactly once from main, before reading the main config
3488 * or initialising any modules.
3489 */
tls_global_init(bool spawn_flag,bool check)3490 int tls_global_init(bool spawn_flag, bool check)
3491 {
3492 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
3493 SSL_library_init(); /* initialize library */
3494 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
3495 CONF_modules_load_file(NULL, NULL, 0);
3496
3497 /*
3498 * Initialize the index for the certificates.
3499 */
3500 fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, NULL);
3501
3502 /*
3503 * If we're linking with OpenSSL too, then we need
3504 * to set up the mutexes and enable the thread callbacks.
3505 *
3506 * 'check' and not 'check_config' because it's a global,
3507 * and we don't want to have tls.c depend on globals.
3508 */
3509 if (spawn_flag && !check && (tls_mutexes_init() < 0)) {
3510 ERROR("(TLS) FATAL: Failed to set up SSL mutexes");
3511 return -1;
3512 }
3513
3514 return 0;
3515 }
3516
3517 #ifdef ENABLE_OPENSSL_VERSION_CHECK
3518 /** Check for vulnerable versions of libssl
3519 *
3520 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
3521 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
3522 */
tls_global_version_check(char const * acknowledged)3523 int tls_global_version_check(char const *acknowledged)
3524 {
3525 uint64_t v;
3526 bool bad = false;
3527 size_t i;
3528
3529 if (strcmp(acknowledged, "yes") == 0) return 0;
3530
3531 /* Check for bad versions */
3532 v = (uint64_t) SSLeay();
3533
3534 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
3535 libssl_defect_t *defect = &libssl_defects[i];
3536
3537 if ((v >= defect->low) && (v <= defect->high)) {
3538 /*
3539 * If the CVE is acknowledged, allow it.
3540 */
3541 if (!bad && (strcmp(acknowledged, defect->id) == 0)) return 0;
3542
3543 ERROR("Refusing to start with libssl version %s (in range %s)",
3544 ssl_version(), ssl_version_range(defect->low, defect->high));
3545 ERROR("Security advisory %s (%s)", defect->id, defect->name);
3546 ERROR("%s", defect->comment);
3547
3548 /*
3549 * Only warn about the first one...
3550 */
3551 if (!bad) {
3552 INFO("Once you have verified libssl has been correctly patched, "
3553 "set security.allow_vulnerable_openssl = '%s'", defect->id);
3554
3555 bad = true;
3556 }
3557 }
3558 }
3559
3560 if (bad) return -1;
3561
3562 return 0;
3563 }
3564 #endif
3565
3566 /** Free any memory alloced by libssl
3567 *
3568 */
tls_global_cleanup(void)3569 void tls_global_cleanup(void)
3570 {
3571 #if OPENSSL_VERSION_NUMBER < 0x10000000L
3572 ERR_remove_state(0);
3573 #elif OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
3574 ERR_remove_thread_state(NULL);
3575 #endif
3576 #ifndef OPENSSL_NO_ENGINE
3577 ENGINE_cleanup();
3578 #endif
3579 CONF_modules_unload(1);
3580 ERR_free_strings();
3581 EVP_cleanup();
3582 CRYPTO_cleanup_all_ex_data();
3583 }
3584
3585
3586 /*
3587 * Map version strings to OpenSSL macros.
3588 */
3589 static const FR_NAME_NUMBER version2int[] = {
3590 { "1.0", TLS1_VERSION },
3591 #ifdef TLS1_1_VERSION
3592 { "1.1", TLS1_1_VERSION },
3593 #endif
3594 #ifdef TLS1_2_VERSION
3595 { "1.2", TLS1_2_VERSION },
3596 #endif
3597 #ifdef TLS1_3_VERSION
3598 { "1.3", TLS1_3_VERSION },
3599 #endif
3600 { NULL, 0 }
3601 };
3602
3603 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3604 #ifdef TLS1_3_VERSION
3605 #define CHECK_FOR_PSK_CERTS (1)
3606 #endif
3607 #endif
3608
3609 /** Create SSL context
3610 *
3611 * - Load the trusted CAs
3612 * - Load the Private key & the certificate
3613 * - Set the Context options & Verify options
3614 */
tls_init_ctx(fr_tls_server_conf_t * conf,int client,char const * chain_file,char const * private_key_file)3615 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client, char const *chain_file, char const *private_key_file)
3616 {
3617 SSL_CTX *ctx;
3618 X509_STORE *certstore;
3619 int verify_mode = SSL_VERIFY_NONE;
3620 int ctx_options = 0, ctx_available = 0;
3621 int type;
3622 #ifdef CHECK_FOR_PSK_CERTS
3623 bool psk_and_certs = false;
3624 #endif
3625 int min_version;
3626 int max_version;
3627
3628 /*
3629 * SHA256 is in all versions of OpenSSL, but isn't
3630 * initialized by default. It's needed for WiMAX
3631 * certificates.
3632 */
3633 #ifdef HAVE_OPENSSL_EVP_SHA256
3634 EVP_add_digest(EVP_sha256());
3635 #endif
3636
3637 ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
3638 if (!ctx) {
3639 tls_error_log(NULL, "Failed creating OpenSSL context");
3640 return NULL;
3641 }
3642
3643 /*
3644 * Save the config on the context so that callbacks which
3645 * only get SSL_CTX* e.g. session persistence, can get it
3646 */
3647 SSL_CTX_set_app_data(ctx, conf);
3648
3649 /*
3650 * Identify the type of certificates that needs to be loaded
3651 */
3652 if (conf->file_type) {
3653 type = SSL_FILETYPE_PEM;
3654 } else {
3655 type = SSL_FILETYPE_ASN1;
3656 }
3657
3658 /*
3659 * Set the password to load private key
3660 */
3661 if (conf->private_key_password) {
3662 #ifdef __APPLE__
3663 /*
3664 * We don't want to put the private key password in eap.conf, so check
3665 * for our special string which indicates we should get the password
3666 * programmatically.
3667 */
3668 char const* special_string = "Apple:UseCertAdmin";
3669 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
3670 char cmd[256];
3671 char *password;
3672 long const max_password_len = 128;
3673 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
3674 conf->private_key_file);
3675
3676 DEBUG2(LOG_PREFIX ": Getting private key passphrase using command \"%s\"", cmd);
3677
3678 FILE* cmd_pipe = popen(cmd, "r");
3679 if (!cmd_pipe) {
3680 ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
3681 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
3682 return NULL;
3683 }
3684
3685 rad_const_free(conf->private_key_password);
3686 password = talloc_array(conf, char, max_password_len);
3687 if (!password) {
3688 ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
3689 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
3690 pclose(cmd_pipe);
3691 return NULL;
3692 }
3693
3694 fgets(password, max_password_len, cmd_pipe);
3695 pclose(cmd_pipe);
3696
3697 /* Get rid of newline at end of password. */
3698 password[strlen(password) - 1] = '\0';
3699
3700 DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
3701 conf->private_key_password = password;
3702 }
3703 #endif
3704
3705 {
3706 char *password;
3707
3708 memcpy(&password, &conf->private_key_password, sizeof(password));
3709 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
3710 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
3711 }
3712 }
3713
3714 #ifdef PSK_MAX_IDENTITY_LEN
3715 /*
3716 * A dynamic query exists. There MUST NOT be a
3717 * statically configured identity and password.
3718 */
3719 if (conf->psk_query) {
3720 if (!*conf->psk_query) {
3721 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
3722 return NULL;
3723 }
3724
3725 if (conf->psk_identity && *conf->psk_identity) {
3726 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity and psk_query cannot be used at the same time.");
3727 return NULL;
3728 }
3729
3730 if (conf->psk_password && *conf->psk_password) {
3731 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_password and psk_query cannot be used at the same time.");
3732 return NULL;
3733 }
3734
3735 if (client) {
3736 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
3737 return NULL;
3738 }
3739
3740 /*
3741 * Now check that if PSK is being used, that the config is valid.
3742 */
3743 } else if (conf->psk_identity) {
3744 if (!*conf->psk_identity) {
3745 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity is empty");
3746 return NULL;
3747 }
3748
3749
3750 if (!conf->psk_password || !*conf->psk_password) {
3751 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity is set, but there is no psk_password");
3752 return NULL;
3753 }
3754
3755 } else if (conf->psk_password) {
3756 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_password is set, but there is no psk_identity");
3757 return NULL;
3758 }
3759
3760 /*
3761 * Set the server PSK callback if necessary.
3762 */
3763 if (!client && (conf->psk_identity || conf->psk_query)) {
3764 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
3765 }
3766
3767 /*
3768 * Do more sanity checking if we have a PSK identity. We
3769 * check the password, and convert it to it's final form.
3770 */
3771 if (conf->psk_identity) {
3772 size_t psk_len, hex_len;
3773 uint8_t buffer[PSK_MAX_PSK_LEN];
3774
3775 if (client) {
3776 SSL_CTX_set_psk_client_callback(ctx,
3777 psk_client_callback);
3778 }
3779
3780 if (!conf->psk_password || !*conf->psk_password) {
3781 ERROR(LOG_PREFIX ": psk_hexphrase cannot be empty");
3782 return NULL;
3783 }
3784
3785 psk_len = strlen(conf->psk_password);
3786 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
3787 ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
3788 return NULL;
3789 }
3790
3791 /*
3792 * Check the password now, so that we don't have
3793 * errors at run-time.
3794 */
3795 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
3796 if (psk_len != (2 * hex_len)) {
3797 ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
3798 return NULL;
3799 }
3800
3801 #ifdef CHECK_FOR_PSK_CERTS
3802 /*
3803 * RFC 8446 says:
3804 *
3805 * When authenticating via a certificate, the server will send the
3806 * Certificate (Section 4.4.2) and CertificateVerify (Section 4.4.3)
3807 * messages. In TLS 1.3 as defined by this document, either a PSK or
3808 * a certificate is always used, but not both. Future documents may
3809 * define how to use them together.
3810 */
3811 if (((conf->psk_identity || conf->psk_password || conf->psk_query)) &&
3812 (conf->certificate_file || conf->private_key_password || conf->private_key_file)) {
3813 psk_and_certs = true;
3814 }
3815 #endif
3816
3817 goto post_ca;
3818 }
3819 #else
3820 (void) client; /* -Wunused */
3821 #endif
3822
3823 /*
3824 * Load our keys and certificates
3825 *
3826 * If certificates are of type PEM then we can make use
3827 * of cert chain authentication using openssl api call
3828 * SSL_CTX_use_certificate_chain_file. Please see how
3829 * the cert chain needs to be given in PEM from
3830 * openSSL.org
3831 */
3832 if (!chain_file) chain_file = conf->certificate_file;
3833 if (!chain_file) goto load_ca;
3834
3835 if (type == SSL_FILETYPE_PEM) {
3836 if (!(SSL_CTX_use_certificate_chain_file(ctx, chain_file))) {
3837 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
3838 chain_file);
3839 return NULL;
3840 }
3841
3842 } else if (!(SSL_CTX_use_certificate_file(ctx, chain_file, type))) {
3843 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
3844 chain_file);
3845 return NULL;
3846 }
3847
3848 load_ca:
3849 /*
3850 * Load the CAs we trust and configure CRL checks if needed
3851 */
3852 #if defined(X509_V_FLAG_PARTIAL_CHAIN)
3853 X509_STORE_set_flags(SSL_CTX_get_cert_store(ctx), X509_V_FLAG_PARTIAL_CHAIN);
3854 #endif
3855 if (conf->ca_file || conf->ca_path) {
3856 if ((certstore = fr_init_x509_store(conf)) == NULL ) return NULL;
3857 SSL_CTX_set_cert_store(ctx, certstore);
3858 }
3859
3860 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
3861
3862 conf->ca_path_last_reload = time(NULL);
3863 conf->old_x509_store = NULL;
3864
3865 /*
3866 * Disable reloading of cert store if we're not using CA path
3867 */
3868 if (!conf->ca_path) conf->ca_path_reload_interval = 0;
3869
3870 if (conf->ca_path_reload_interval > 0 && conf->ca_path_reload_interval < 300) {
3871 DEBUG2("ca_path_reload_interval is set too low, reset it to 300");
3872 conf->ca_path_reload_interval = 300;
3873 }
3874
3875 /* Load private key */
3876 if (!private_key_file) private_key_file = conf->private_key_file;
3877 if (private_key_file) {
3878 if (!(SSL_CTX_use_PrivateKey_file(ctx, private_key_file, type))) {
3879 tls_error_log(NULL, "Failed reading private key file \"%s\"",
3880 private_key_file);
3881 return NULL;
3882 }
3883
3884 /*
3885 * Check if the loaded private key is the right one
3886 */
3887 if (!SSL_CTX_check_private_key(ctx)) {
3888 ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
3889 return NULL;
3890 }
3891 }
3892
3893 #ifdef PSK_MAX_IDENTITY_LEN
3894 post_ca:
3895 #endif
3896
3897 /*
3898 * We never want SSLv2 or SSLv3.
3899 */
3900 ctx_options |= SSL_OP_NO_SSLv2;
3901 ctx_options |= SSL_OP_NO_SSLv3;
3902
3903 /*
3904 * If set then dummy Change Cipher Spec (CCS) messages are sent in
3905 * TLSv1.3. This has the effect of making TLSv1.3 look more like TLSv1.2
3906 * so that middleboxes that do not understand TLSv1.3 will not drop
3907 * the connection. This isn't needed for EAP-TLS, so we disable it.
3908 *
3909 * EAP (hopefully) does not have middlebox deployments
3910 */
3911 #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
3912 ctx_options &= ~SSL_OP_ENABLE_MIDDLEBOX_COMPAT;
3913 #endif
3914
3915 /*
3916 * SSL_CTX_set_(min|max)_proto_version was included in OpenSSL 1.1.0
3917 *
3918 * This version already defines macros for TLS1_2_VERSION and
3919 * below, so we don't need to check for them explicitly.
3920 *
3921 * TLS1_3_VERSION is available in OpenSSL 1.1.1.
3922 */
3923
3924 /*
3925 * Get the max version from the configuration files.
3926 */
3927 if (conf->tls_max_version && *conf->tls_max_version) {
3928 max_version = fr_str2int(version2int, conf->tls_max_version, 0);
3929 if (!max_version) {
3930 ERROR("Invalid value for tls_max_version '%s'", conf->tls_max_version);
3931 return NULL;
3932 }
3933 } else {
3934 /*
3935 * Pick the maximum version available at compile
3936 * time.
3937 */
3938 #if defined(TLS1_3_VERSION)
3939 max_version = TLS1_2_VERSION; /* yes, we only use TLS 1.3 if it's EXPLICITELY ENABLED */
3940 #elif defined(TLS1_2_VERSION)
3941 max_version = TLS1_2_VERSION;
3942 #elif defined(TLS1_1_VERSION)
3943 max_version = TLS1_1_VERSION;
3944 #else
3945 max_version = TLS1_VERSION;
3946 #endif
3947 }
3948
3949 /*
3950 * Get the min version from the configuration files.
3951 */
3952 if (conf->tls_min_version && *conf->tls_min_version) {
3953 min_version = fr_str2int(version2int, conf->tls_min_version, 0);
3954 if (!min_version) {
3955 ERROR("Unknown or unsupported value for tls_min_version '%s'", conf->tls_min_version);
3956 return NULL;
3957 }
3958 } else {
3959 /*
3960 * Allow TLS 1.0. It is horribly insecure, but
3961 * some systems still use it.
3962 */
3963 min_version = TLS1_VERSION;
3964 }
3965
3966 /*
3967 * Compare the two.
3968 */
3969 if ((min_version > max_version) || (max_version < min_version)) {
3970 ERROR("tls_min_version '%s' must be <= tls_max_version '%s'",
3971 conf->tls_min_version, conf->tls_max_version);
3972 return NULL;
3973 }
3974
3975 #ifdef CHECK_FOR_PSK_CERTS
3976 /*
3977 * Disable TLS 1.3 when using PSKs and certs.
3978 * This doesn't work.
3979 *
3980 * It's best to disable the offending
3981 * configuration and warn about it. The
3982 * alternative is to have the admin wonder why it
3983 * doesn't work.
3984 *
3985 * Note that the admin can over-ride this by
3986 * setting "min_version = max_version = 1.3"
3987 */
3988 if (psk_and_certs &&
3989 (min_version < TLS1_3_VERSION) && (max_version >= TLS1_3_VERSION)) {
3990 max_version = TLS1_2_VERSION;
3991 radlog(L_DBG | L_WARN, "Disabling TLS 1.3 due to PSK and certificates being configured simultaneously. This is not supported by the standards.");
3992 }
3993 #endif
3994
3995 /*
3996 * No one should be using TLS 1.0 or TLS 1.1 any more
3997 *
3998 * If TLS1.2 isn't defined by OpenSSL, then we _know_
3999 * it's an insecure version of OpenSSL.
4000 */
4001 #ifdef TLS1_2_VERSION
4002 if (max_version < TLS1_2_VERSION)
4003 #endif
4004 {
4005 if (rad_debug_lvl) {
4006 WARN(LOG_PREFIX ": The configuration allows TLS 1.0 and/or TLS 1.1. We STRONGLY recommned using only TLS 1.2 for security");
4007 WARN(LOG_PREFIX ": Please set: tls_min_version = '1.2'");
4008 }
4009 }
4010
4011 #ifdef SSL_OP_NO_TLSv1
4012 /*
4013 * Check min / max against the old-style "disable" flag.
4014 */
4015 if (conf->disable_tlsv1) {
4016 if (min_version == TLS1_VERSION) {
4017 ERROR(LOG_PREFIX ": 'disable_tlsv1' is set, but 'min_version = 1.0'. These cannot both be true.");
4018 return NULL;
4019 }
4020 if (max_version == TLS1_VERSION) {
4021 ERROR(LOG_PREFIX ": 'disable_tlsv1' is set, but 'max_version = 1.0'. These cannot both be true.");
4022 return NULL;
4023 }
4024 ctx_options |= SSL_OP_NO_TLSv1;
4025 }
4026
4027 if (min_version > TLS1_VERSION) ctx_options |= SSL_OP_NO_TLSv1;
4028
4029 ctx_available |= SSL_OP_NO_TLSv1;
4030 #endif
4031
4032 #ifdef SSL_OP_NO_TLSv1_1
4033 /*
4034 * Check min / max against the old-style "disable" flag.
4035 */
4036 if (conf->disable_tlsv1_1) {
4037 if (min_version <= TLS1_1_VERSION) {
4038 ERROR(LOG_PREFIX ": 'disable_tlsv1_1' is set, but 'min_version <= 1.1'. These cannot both be true.");
4039 return NULL;
4040 }
4041 if (max_version == TLS1_1_VERSION) {
4042 ERROR(LOG_PREFIX ": 'disable_tlsv1_1' is set, but 'max_version = 1.1'. These cannot both be true.");
4043 return NULL;
4044 }
4045 ctx_options |= SSL_OP_NO_TLSv1_1;
4046 }
4047
4048 if (min_version > TLS1_1_VERSION) ctx_options |= SSL_OP_NO_TLSv1_1;
4049 if (max_version < TLS1_1_VERSION) ctx_options |= SSL_OP_NO_TLSv1_1;
4050
4051 ctx_available |= SSL_OP_NO_TLSv1_1;
4052 #endif
4053
4054 #ifdef SSL_OP_NO_TLSv1_2
4055 /*
4056 * Check min / max against the old-style "disable" flag.
4057 */
4058 if (conf->disable_tlsv1_2) {
4059 if (min_version <= TLS1_2_VERSION) {
4060 ERROR(LOG_PREFIX ": 'disable_tlsv1_2' is set, but 'min_version <= 1.2'. These cannot both be true.");
4061 return NULL;
4062 }
4063 if (max_version == TLS1_2_VERSION) {
4064 ERROR(LOG_PREFIX ": 'disable_tlsv1_1' is set, but 'max_version = 1.2'. These cannot both be true.");
4065 return NULL;
4066 }
4067 ctx_options |= SSL_OP_NO_TLSv1_2;
4068 }
4069 ctx_available |= SSL_OP_NO_TLSv1_2;
4070
4071 if (min_version > TLS1_2_VERSION) ctx_options |= SSL_OP_NO_TLSv1_2;
4072 if (max_version < TLS1_2_VERSION) ctx_options |= SSL_OP_NO_TLSv1_2;
4073 #endif
4074
4075 #ifdef SSL_OP_NO_TLSv1_3
4076 ctx_available |= SSL_OP_NO_TLSv1_3;
4077 if (min_version > TLS1_3_VERSION) ctx_options |= SSL_OP_NO_TLSv1_3;
4078 if (max_version < TLS1_3_VERSION) ctx_options |= SSL_OP_NO_TLSv1_3;
4079 #endif
4080
4081 /*
4082 * Tell OpenSSL PRETTY PLEASE MAY WE USE TLS 1.1.
4083 *
4084 * Because saying "use TLS 1.1" isn't enough. We have to
4085 * send it flowers and cake.
4086 */
4087 if ((min_version <= TLS1_1_VERSION) &&
4088 !strstr(conf->cipher_list, "DEFAULT@SECLEVEL=1")) {
4089 WARN(LOG_PREFIX ": In order to use TLS 1.0 and/or TLS 1.1, you likely need to set: cipher_list = \"DEFAULT@SECLEVEL=1\"");
4090 }
4091
4092 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
4093 if (conf->disable_tlsv1) {
4094 WARN(LOG_PREFIX ": Please use 'tls_min_version' and 'tls_max_version' instead of 'disable_tlsv1'");
4095 }
4096 if (conf->disable_tlsv1_1) {
4097 WARN(LOG_PREFIX ": Please use 'tls_min_version' and 'tls_max_version' instead of 'disable_tlsv1_1'");
4098 }
4099 if (conf->disable_tlsv1_2) {
4100 WARN(LOG_PREFIX ": Please use 'tls_min_version' and 'tls_max_version' instead of 'disable_tlsv1_2'");
4101 }
4102
4103 ctx_options &= ~(ctx_available); /* clear these flags, as they're not needed. */
4104
4105 if (!SSL_CTX_set_max_proto_version(ctx, max_version)) {
4106 ERROR("Failed setting TLS maximum version");
4107 return NULL;
4108 }
4109
4110 if (!SSL_CTX_set_min_proto_version(ctx, min_version)) {
4111 ERROR("Failed setting TLS minimum version");
4112 return NULL;
4113 }
4114 #endif /* OpenSSL version < 1.1.0 */
4115
4116 if ((ctx_options & ctx_available) == ctx_available) {
4117 ERROR(LOG_PREFIX ": You have disabled all available TLS versions. EAP will not work");
4118 return NULL;
4119 }
4120
4121 /*
4122 * Cache min / max TLS version so that we can
4123 * programatically disable TLS 1.3 for TTLS, PEAP, and
4124 * FAST.
4125 */
4126 conf->min_version = min_version;
4127 conf->max_version = max_version;
4128
4129 #ifdef SSL_OP_NO_TICKET
4130 ctx_options |= SSL_OP_NO_TICKET;
4131 #endif
4132
4133 if (!conf->disable_single_dh_use) {
4134 /*
4135 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
4136 * small subgroup attacks and forward secrecy. Always
4137 * using SSL_OP_SINGLE_DH_USE has an impact on the
4138 * computer time needed during negotiation, but it is not
4139 * very large.
4140 */
4141 ctx_options |= SSL_OP_SINGLE_DH_USE;
4142 }
4143
4144 /*
4145 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
4146 * in Windows Vista client.
4147 * http://www.openssl.org/~bodo/tls-cbc.txt
4148 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
4149 */
4150 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
4151
4152 if (conf->cipher_server_preference) {
4153 /*
4154 * SSL_OP_CIPHER_SERVER_PREFERENCE to follow best practice
4155 * of nowday's TLS: do not allow poorly-selected ciphers from
4156 * client to take preference
4157 */
4158 ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
4159 }
4160
4161 SSL_CTX_set_options(ctx, ctx_options);
4162
4163 /*
4164 * TLS 1.3 introduces the concept of early data (also known as zero
4165 * round trip data or 0-RTT data). Early data allows a client to send
4166 * data to a server in the first round trip of a connection, without
4167 * waiting for the TLS handshake to complete if the client has spoken
4168 * to the same server recently. This doesn't work for EAP, so we
4169 * disable early data.
4170 *
4171 */
4172 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
4173 SSL_CTX_set_max_early_data(ctx, 0);
4174 #endif
4175
4176 /*
4177 * TODO: Set the RSA & DH
4178 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
4179 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
4180 */
4181
4182 /*
4183 * set the message callback to identify the type of
4184 * message. For every new session, there can be a
4185 * different callback argument.
4186 *
4187 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
4188 */
4189
4190 /*
4191 * Set eliptical curve crypto configuration.
4192 */
4193 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
4194 #ifndef OPENSSL_NO_ECDH
4195 if (set_ecdh_curve(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) {
4196 return NULL;
4197 }
4198 #endif
4199 #endif
4200
4201 /*
4202 * OpenSSL will automatically create certificate chains,
4203 * unless we tell it to not do that. The problem is that
4204 * it sometimes gets the chains right from a certificate
4205 * signature view, but wrong from the clients view.
4206 */
4207 if (!conf->auto_chain) {
4208 SSL_CTX_set_mode(ctx, SSL_MODE_NO_AUTO_CHAIN);
4209 }
4210
4211 /* Set Info callback */
4212 SSL_CTX_set_info_callback(ctx, cbtls_info);
4213
4214 /*
4215 * Callbacks, etc. for session resumption.
4216 */
4217 if (conf->session_cache_enable) {
4218 /*
4219 * Cache sessions on disk if requested.
4220 */
4221 if (conf->session_cache_path && *conf->session_cache_path) {
4222 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
4223 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
4224 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
4225 }
4226
4227 /*
4228 * Or run the cache through a virtual server.
4229 */
4230 if (conf->session_cache_server && *conf->session_cache_server) {
4231 SSL_CTX_sess_set_new_cb(ctx, cbtls_cache_save);
4232 SSL_CTX_sess_set_get_cb(ctx, cbtls_cache_load);
4233 SSL_CTX_sess_set_remove_cb(ctx, cbtls_cache_clear);
4234 }
4235
4236 SSL_CTX_set_quiet_shutdown(ctx, 1);
4237 if (fr_tls_ex_index_vps < 0)
4238 fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, NULL);
4239 }
4240
4241 /*
4242 * Check the certificates for revocation.
4243 */
4244 #ifdef X509_V_FLAG_CRL_CHECK
4245 if (conf->check_crl) {
4246 certstore = SSL_CTX_get_cert_store(ctx);
4247 if (certstore == NULL) {
4248 tls_error_log(NULL, "Error reading Certificate Store");
4249 return NULL;
4250 }
4251 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
4252
4253 #ifdef X509_V_FLAG_USE_DELTAS
4254 /*
4255 * If set, delta CRLs (if present) are used to
4256 * determine certificate status. If not set
4257 * deltas are ignored.
4258 *
4259 * So it's safe to always set this flag.
4260 */
4261 X509_STORE_set_flags(certstore, X509_V_FLAG_USE_DELTAS);
4262 #endif
4263
4264 #ifdef X509_V_FLAG_CRL_CHECK_ALL
4265 if (conf->check_all_crl)
4266 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
4267 #endif
4268 }
4269 #endif
4270
4271 /*
4272 * Set verify modes
4273 * Always verify the peer certificate
4274 */
4275 verify_mode |= SSL_VERIFY_PEER;
4276 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4277 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
4278 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
4279
4280 if (conf->verify_depth) {
4281 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
4282 }
4283
4284 #ifndef LIBRESSL_VERSION_NUMBER
4285 /* Load randomness */
4286 if (conf->random_file) {
4287 if (!(RAND_load_file(conf->random_file, 1024*10))) {
4288 tls_error_log(NULL, "Failed loading randomness");
4289 return NULL;
4290 }
4291 }
4292 #endif
4293
4294 /*
4295 * Set the cipher list if we were told to
4296 */
4297 if (conf->cipher_list) {
4298 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
4299 tls_error_log(NULL, "Failed setting cipher list");
4300 return NULL;
4301 }
4302 }
4303
4304 /*
4305 * Setup session caching
4306 */
4307 if (conf->session_cache_enable) {
4308 /*
4309 * Create a unique context Id per EAP-TLS configuration.
4310 */
4311 if (conf->session_id_name) {
4312 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
4313 "FR eap %s", conf->session_id_name);
4314 } else {
4315 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
4316 "FR eap %p", conf);
4317 }
4318
4319 /*
4320 * Cache it, DON'T auto-clear it, and disable the internal OpenSSL session cache.
4321 */
4322 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR | SSL_SESS_CACHE_NO_INTERNAL);
4323
4324 SSL_CTX_set_session_id_context(ctx,
4325 (unsigned char *) conf->session_context_id,
4326 (unsigned int) strlen(conf->session_context_id));
4327
4328 /*
4329 * Our lifetime is in hours, this is in seconds.
4330 */
4331 SSL_CTX_set_timeout(ctx, conf->session_lifetime * 3600);
4332
4333 /*
4334 * Set the maximum number of entries in the
4335 * session cache.
4336 */
4337 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
4338
4339 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
4340 SSL_CTX_set_num_tickets(ctx, 1);
4341 #endif
4342
4343 } else {
4344 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4345
4346 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
4347 /*
4348 * This controls the number of stateful or stateless tickets
4349 * generated with TLS 1.3. In OpenSSL 1.1.1 it's also
4350 * required to disable sending session tickets,
4351 * SSL_SESS_CACHE_OFF is not good enough.
4352 */
4353 SSL_CTX_set_num_tickets(ctx, 0);
4354 #endif
4355 }
4356
4357 return ctx;
4358 }
4359
4360
4361 /*
4362 * Free TLS client/server config
4363 * Should not be called outside this code, as a callback is
4364 * added to automatically free the data when the CONF_SECTION
4365 * is freed.
4366 */
_tls_server_conf_free(fr_tls_server_conf_t * conf)4367 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
4368 {
4369 if (conf->ctx) SSL_CTX_free(conf->ctx);
4370
4371 if (conf->cache_ht) fr_hash_table_free(conf->cache_ht);
4372
4373 pthread_mutex_destroy(&conf->mutex);
4374
4375 #ifdef HAVE_OPENSSL_OCSP_H
4376 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
4377 conf->ocsp_store = NULL;
4378 #endif
4379
4380 if (conf->realms) fr_hash_table_free(conf->realms);
4381
4382 #ifndef NDEBUG
4383 memset(conf, 0, sizeof(*conf));
4384 #endif
4385 return 0;
4386 }
4387
tls_server_conf_alloc(TALLOC_CTX * ctx)4388 fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
4389 {
4390 fr_tls_server_conf_t *conf;
4391
4392 conf = talloc_zero(ctx, fr_tls_server_conf_t);
4393 if (!conf) {
4394 ERROR(LOG_PREFIX ": Out of memory");
4395 return NULL;
4396 }
4397
4398 talloc_set_destructor(conf, _tls_server_conf_free);
4399
4400 return conf;
4401 }
4402
store_hash(void const * data)4403 static uint32_t store_hash(void const *data)
4404 {
4405 DICT_ATTR const *da = data;
4406 return fr_hash(&da, sizeof(da));
4407 }
4408
store_cmp(void const * a,void const * b)4409 static int store_cmp(void const *a, void const *b)
4410 {
4411 DICT_ATTR const *one = a;
4412 DICT_ATTR const *two = b;
4413
4414 return (one < two) - (one > two);
4415 }
4416
realm_hash(void const * data)4417 static uint32_t realm_hash(void const *data)
4418 {
4419 fr_realm_ctx_t const *r = data;
4420
4421 return fr_hash_string(r->name);
4422 }
4423
realm_cmp(void const * a,void const * b)4424 static int realm_cmp(void const *a, void const *b)
4425 {
4426 fr_realm_ctx_t const *one = a;
4427 fr_realm_ctx_t const *two = b;
4428
4429 return strcmp(one->name, two->name);
4430 }
4431
realm_free(void * data)4432 static void realm_free(void *data)
4433 {
4434 fr_realm_ctx_t *r = data;
4435
4436 SSL_CTX_free(r->ctx);
4437 }
4438
tls_realms_load(fr_tls_server_conf_t * conf)4439 static int tls_realms_load(fr_tls_server_conf_t *conf)
4440 {
4441 fr_hash_table_t *ht;
4442 DIR *dir;
4443 struct dirent *dp;
4444 char buffer[PATH_MAX];
4445 char buffer2[PATH_MAX];
4446
4447 ht = fr_hash_table_create(realm_hash, realm_cmp, realm_free);
4448 if (!ht) return -1;
4449
4450 dir = opendir(conf->realm_dir);
4451 if (!dir) {
4452 ERROR("Error reading directory %s: %s", conf->realm_dir, fr_syserror(errno));
4453 error:
4454 fr_hash_table_free(ht);
4455 return -1;
4456 }
4457
4458 /*
4459 * Read only the PEM files
4460 */
4461 while ((dp = readdir(dir)) != NULL) {
4462 char *p;
4463 struct stat stat_buf;
4464 SSL_CTX *ctx;
4465 fr_realm_ctx_t *r;
4466 char const *private_key_file = buffer;
4467
4468 if (dp->d_name[0] == '.') continue;
4469
4470 p = strrchr(dp->d_name, '.');
4471 if (!p) continue;
4472
4473 if (memcmp(p, ".pem", 5) != 0) continue; /* must END in .pem */
4474
4475 snprintf(buffer, sizeof(buffer), "%s/%s", conf->realm_dir, dp->d_name); /* ignore directories */
4476 if ((stat(buffer, &stat_buf) != 0) ||
4477 S_ISDIR(stat_buf.st_mode)) continue;
4478
4479 strcpy(buffer2, buffer);
4480 p = strchr(buffer2, '.'); /* which must be there... */
4481 if (!p) continue;
4482
4483 /*
4484 * If there's a key file, then use that.
4485 * Otherwise assume that the private key is in
4486 * the chain file.
4487 */
4488 strcpy(p, ".key");
4489 if (stat(buffer2, &stat_buf) != 0) private_key_file = buffer2;
4490
4491 ctx = tls_init_ctx(conf, 1, buffer, private_key_file);
4492 if (!ctx) goto error;
4493
4494 r = talloc_zero(conf, fr_realm_ctx_t);
4495 if (!r) {
4496 SSL_CTX_free(ctx);
4497 goto error;
4498 }
4499
4500 r->name = talloc_strdup(r, buffer);
4501 r->ctx = ctx;
4502
4503 if (fr_hash_table_insert(ht, r) < 0) {
4504 ERROR("Failed inserting certificate file %s into hash table", buffer);
4505 goto error;
4506 }
4507 }
4508
4509 return 0;
4510 }
4511
4512
tls_server_conf_parse(CONF_SECTION * cs)4513 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
4514 {
4515 fr_tls_server_conf_t *conf;
4516
4517 /*
4518 * If cs has already been parsed there should be a cached copy
4519 * of conf already stored, so just return that.
4520 */
4521 conf = cf_data_find(cs, "tls-conf");
4522 if (conf) {
4523 DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
4524 return conf;
4525 }
4526
4527 conf = tls_server_conf_alloc(cs);
4528
4529 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
4530 error:
4531 talloc_free(conf);
4532 return NULL;
4533 }
4534
4535 /*
4536 * Save people from their own stupidity.
4537 */
4538 if (conf->fragment_size < 100) conf->fragment_size = 100;
4539
4540 /*
4541 * Disallow sessions of more than 7 days, as per RFC
4542 * 8446.
4543 *
4544 * Note that we also enforce this on TLS 1.2, etc.
4545 * Because there's just no reason to have month-long TLS
4546 * sessions.
4547 */
4548 if (conf->session_lifetime > (7 * 24)) conf->session_lifetime = 7 * 24;
4549
4550 /*
4551 * Only check for certificate things if we don't have a
4552 * PSK query.
4553 */
4554 #ifdef PSK_MAX_IDENTITY_LEN
4555 if (conf->psk_identity) {
4556 if (conf->private_key_file) {
4557 WARN(LOG_PREFIX ": Ignoring private key file due to psk_identity being used");
4558 }
4559
4560 if (conf->certificate_file) {
4561 WARN(LOG_PREFIX ": Ignoring certificate file due to psk_identity being used");
4562 }
4563
4564 } else
4565 #endif
4566 {
4567 if (!conf->private_key_file) {
4568 ERROR(LOG_PREFIX ": TLS Server requires a private key file");
4569 goto error;
4570 }
4571
4572 if (!conf->certificate_file) {
4573 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
4574 goto error;
4575 }
4576 }
4577
4578 /*
4579 * Initialize configuration mutex
4580 */
4581 pthread_mutex_init(&conf->mutex, NULL);
4582
4583 /*
4584 * Initialize TLS
4585 */
4586 conf->ctx = tls_init_ctx(conf, 0, NULL, NULL);
4587 if (conf->ctx == NULL) {
4588 goto error;
4589 }
4590
4591 if (conf->session_cache_enable) {
4592 CONF_SECTION *subcs;
4593 CONF_ITEM *ci;
4594
4595 subcs = cf_section_sub_find(cs, "cache");
4596 if (!subcs) goto skip_list;
4597 subcs = cf_section_sub_find(subcs, "store");
4598 if (!subcs) goto skip_list;
4599
4600 /*
4601 * Largely taken from rlm_detail for laziness.
4602 */
4603 conf->cache_ht = fr_hash_table_create(store_hash, store_cmp, NULL);
4604
4605 for (ci = cf_item_find_next(subcs, NULL);
4606 ci != NULL;
4607 ci = cf_item_find_next(subcs, ci)) {
4608 char const *attr;
4609 DICT_ATTR const *da;
4610
4611 if (!cf_item_is_pair(ci)) continue;
4612
4613 attr = cf_pair_attr(cf_item_to_pair(ci));
4614 if (!attr) continue; /* pair-anoia */
4615
4616 da = dict_attrbyname(attr);
4617 if (!da) {
4618 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
4619 goto error;
4620 }
4621
4622 /*
4623 * Be kind to minor mistakes.
4624 */
4625 if (fr_hash_table_finddata(conf->cache_ht, da)) {
4626 WARN(LOG_PREFIX ": Ignoring duplicate entry '%s'", attr);
4627 continue;
4628 }
4629
4630
4631 if (!fr_hash_table_insert(conf->cache_ht, da)) {
4632 ERROR(LOG_PREFIX ": Failed inserting '%s' into cache list", attr);
4633 goto error;
4634 }
4635 }
4636
4637 /*
4638 * If we didn't suppress anything, delete the hash table.
4639 */
4640 if (fr_hash_table_num_elements(conf->cache_ht) == 0) {
4641 fr_hash_table_free(conf->cache_ht);
4642 conf->cache_ht = NULL;
4643 }
4644 }
4645
4646 skip_list:
4647
4648 #ifdef HAVE_OPENSSL_OCSP_H
4649 /*
4650 * Initialize OCSP Revocation Store
4651 */
4652 if (conf->ocsp_enable) {
4653 conf->ocsp_store = fr_init_x509_store(conf);
4654 if (conf->ocsp_store == NULL) goto error;
4655 }
4656 #endif /*HAVE_OPENSSL_OCSP_H*/
4657 {
4658 char *dh_file;
4659
4660 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
4661 if (load_dh_params(conf->ctx, dh_file) < 0) {
4662 goto error;
4663 }
4664 }
4665
4666 if (conf->verify_tmp_dir) {
4667 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
4668 ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
4669 conf->verify_tmp_dir, fr_syserror(errno));
4670 goto error;
4671 }
4672 }
4673
4674 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
4675 ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
4676 goto error;
4677 }
4678
4679 #ifdef SSL_OP_NO_TLSv1_2
4680 /*
4681 * OpenSSL 1.0.1f and 1.0.1g get the MS-MPPE keys wrong.
4682 */
4683 #if (OPENSSL_VERSION_NUMBER >= 0x1010106L) && (OPENSSL_VERSION_NUMBER <= 0x1010107L)
4684 conf->disable_tlsv1_2 = true;
4685 WARN(LOG_PREFIX ": Disabling TLSv1.2 due to OpenSSL bugs");
4686 #endif
4687 #endif
4688
4689 /*
4690 * Load certificates and private keys from the realm directory.
4691 */
4692 if (conf->realm_dir && (tls_realms_load(conf) < 0)) goto error;
4693
4694 /*
4695 * Cache conf in cs in case we're asked to parse this again.
4696 */
4697 cf_data_add(cs, "tls-conf", conf, NULL);
4698
4699 return conf;
4700 }
4701
tls_client_conf_parse(CONF_SECTION * cs)4702 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
4703 {
4704 fr_tls_server_conf_t *conf;
4705
4706 conf = cf_data_find(cs, "tls-conf");
4707 if (conf) {
4708 DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
4709 return conf;
4710 }
4711
4712 conf = tls_server_conf_alloc(cs);
4713
4714 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
4715 error:
4716 talloc_free(conf);
4717 return NULL;
4718 }
4719
4720 /*
4721 * Save people from their own stupidity.
4722 */
4723 if (conf->fragment_size < 100) conf->fragment_size = 100;
4724
4725 /*
4726 * Initialize TLS
4727 */
4728 conf->ctx = tls_init_ctx(conf, 1, NULL, NULL);
4729 if (conf->ctx == NULL) {
4730 goto error;
4731 }
4732
4733 {
4734 char *dh_file;
4735
4736 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
4737 if (load_dh_params(conf->ctx, dh_file) < 0) {
4738 goto error;
4739 }
4740 }
4741
4742 cf_data_add(cs, "tls-conf", conf, NULL);
4743
4744 return conf;
4745 }
4746
4747
tls_success(tls_session_t * ssn,REQUEST * request)4748 int tls_success(tls_session_t *ssn, REQUEST *request)
4749 {
4750 VALUE_PAIR *vp, *vps = NULL;
4751 fr_tls_server_conf_t *conf;
4752 TALLOC_CTX *talloc_ctx;
4753
4754 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
4755 rad_assert(conf != NULL);
4756
4757 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
4758
4759 /*
4760 * If there's no session resumption, delete the entry
4761 * from the cache. This means either it's disabled
4762 * globally for this SSL context, OR we were told to
4763 * disable it for this user.
4764 *
4765 * This also means you can't turn it on just for one
4766 * user.
4767 */
4768 if ((!ssn->allow_session_resumption) ||
4769 (((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
4770 (vp->vp_integer == 0))) {
4771 SSL_CTX_remove_session(ssn->ctx,
4772 ssn->ssl_session);
4773 ssn->allow_session_resumption = false;
4774
4775 /*
4776 * If we're in a resumed session and it's
4777 * not allowed,
4778 */
4779 if (SSL_session_reused(ssn->ssl)) {
4780 RDEBUG("(TLS) cache - Forcibly stopping session resumption as it is administratively disabled.");
4781 return -1;
4782 }
4783
4784 /*
4785 * Else resumption IS allowed, so we store the
4786 * user data in the cache.
4787 */
4788 } else if ((!SSL_session_reused(ssn->ssl)) || ssn->session_not_resumed) {
4789 VALUE_PAIR **certs;
4790 char buffer[2 * MAX_SESSION_SIZE + 1];
4791
4792 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
4793
4794 RDEBUG("(TLS) cache - Setting up attributes for session resumption");
4795
4796 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
4797 if (vp) fr_pair_add(&vps, vp);
4798
4799 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
4800 if (vp) fr_pair_add(&vps, vp);
4801
4802 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
4803 if (vp) fr_pair_add(&vps, vp);
4804
4805 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_EAP_TYPE, 0, TAG_ANY);
4806 if (vp) fr_pair_add(&vps, vp);
4807
4808 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
4809 if (vp) fr_pair_add(&vps, vp);
4810
4811 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
4812 if (vp) fr_pair_add(&vps, vp);
4813
4814 if (conf->cache_ht) {
4815 vp_cursor_t cursor;
4816
4817 /* Write each attribute/value to the log file */
4818 for (vp = fr_cursor_init(&cursor, &request->reply->vps);
4819 vp;
4820 vp = fr_cursor_next(&cursor)) {
4821 VALUE_PAIR *copy;
4822
4823 if (!fr_hash_table_finddata(conf->cache_ht, vp->da)) {
4824 continue;
4825 }
4826
4827 copy = fr_pair_copy(talloc_ctx, vp);
4828 if (copy) fr_pair_add(&vps, copy);
4829 }
4830 }
4831
4832 /*
4833 * Hmm... the certs should probably be session data.
4834 */
4835 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
4836 if (certs) {
4837 /*
4838 * @todo: some go into reply, others into
4839 * request
4840 */
4841 fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
4842
4843 vp = fr_pair_find_by_num(vps, PW_TLS_CLIENT_CERT_EXPIRATION, 0, TAG_ANY);
4844 if (vp) {
4845 time_t expires;
4846
4847 if (ocsp_asn1time_to_epoch(&expires, vp->vp_strvalue) < 0) {
4848 RDEBUG2("Failed getting certificate expiration, removing cache entry for session %s", buffer);
4849 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
4850 return -1;
4851 }
4852
4853 if (expires <= request->timestamp) {
4854 RDEBUG2("Certificate has expired, removing cache entry for session %s", buffer);
4855 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
4856 return -1;
4857 }
4858
4859 /*
4860 * Account for Session-Timeout, if it's available.
4861 */
4862 vp = fr_pair_find_by_num(request->reply->vps, PW_SESSION_TIMEOUT, 0, TAG_ANY);
4863 if (vp) {
4864 if ((request->timestamp + vp->vp_integer) > expires) {
4865 vp->vp_integer = expires - request->timestamp;
4866 RWDEBUG2("(TLS) Updating Session-Timeout to %u, due to impending certificate expiration",
4867 vp->vp_integer);
4868 }
4869 }
4870 }
4871 }
4872
4873 if (vps) {
4874 SSL_SESSION_set_ex_data(ssn->ssl_session, fr_tls_ex_index_vps, vps);
4875 rdebug_pair_list(L_DBG_LVL_2, request, vps, " caching ");
4876
4877 if (conf->session_cache_path) {
4878 /* write the VPs to the cache file */
4879 char filename[3 * MAX_SESSION_SIZE + 1], buf[1024];
4880 FILE *vp_file;
4881
4882 RDEBUG2("Saving session %s in the disk cache", buffer);
4883
4884 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
4885 FR_DIR_SEP, buffer);
4886 vp_file = fopen(filename, "w");
4887 if (vp_file == NULL) {
4888 RWDEBUG("(TLS) Could not write session VPs to persistent cache: %s",
4889 fr_syserror(errno));
4890 } else {
4891 VALUE_PAIR *prev = NULL;
4892 vp_cursor_t cursor;
4893 /* generate a dummy user-style entry which is easy to read back */
4894 fprintf(vp_file, "# SSL cached session\n");
4895 fprintf(vp_file, "%s\n\t", buffer);
4896
4897 for (vp = fr_cursor_init(&cursor, &vps);
4898 vp;
4899 vp = fr_cursor_next(&cursor)) {
4900 /*
4901 * Terminate the previous line.
4902 */
4903 if (prev) fprintf(vp_file, ",\n\t");
4904
4905 /*
4906 * Write this one.
4907 */
4908 vp_prints(buf, sizeof(buf), vp);
4909 fputs(buf, vp_file);
4910 prev = vp;
4911 }
4912
4913 /*
4914 * Terminate the final line.
4915 */
4916 fprintf(vp_file, "\n");
4917 fclose(vp_file);
4918 }
4919
4920 } else if (conf->session_cache_server) {
4921 cbtls_cache_save_vps(ssn->ssl, ssn->ssl_session, vps);
4922
4923 } else {
4924 RDEBUG("Failed to find 'persist_dir' in TLS configuration. Session will not be cached on disk.");
4925 }
4926 } else {
4927 RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
4928 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
4929 }
4930
4931 /*
4932 * Else the session WAS allowed. Copy the cached reply.
4933 */
4934 } else {
4935 RDEBUG("(TLS) cache - Refreshing entry for session resumption");
4936
4937 /*
4938 * The "restore VPs from OpenSSL cache" code is
4939 * now in eaptls_process()
4940 */
4941 if (conf->session_cache_path) {
4942 char buffer[2 * MAX_SESSION_SIZE + 1];
4943
4944 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
4945 #ifdef TLS1_3_VERSION
4946 /*
4947 * OpenSSL frees the underlying session out from
4948 * under us in TLS 1.3.
4949 */
4950 if (ssn->info.version == TLS1_3_VERSION) ssn->ssl_session = SSL_get_session(ssn->ssl);
4951 #endif
4952 #endif
4953
4954 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
4955
4956 /* "touch" the cached session/vp file */
4957 char filename[3 * MAX_SESSION_SIZE + 1];
4958
4959 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
4960 conf->session_cache_path, FR_DIR_SEP, buffer);
4961 utime(filename, NULL);
4962 snprintf(filename, sizeof(filename), "%s%c%s.vps",
4963 conf->session_cache_path, FR_DIR_SEP, buffer);
4964 utime(filename, NULL);
4965 }
4966
4967 if (conf->session_cache_server) {
4968 cbtls_cache_refresh(ssn->ssl, ssn->ssl_session);
4969 }
4970
4971 /*
4972 * Mark the request as resumed.
4973 */
4974 pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
4975 RDEBUG(" &request:EAP-Session-Resumed := 1");
4976 }
4977
4978 return 0;
4979 }
4980
4981
tls_fail(tls_session_t * ssn)4982 void tls_fail(tls_session_t *ssn)
4983 {
4984 /*
4985 * Force the session to NOT be cached.
4986 */
4987 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
4988 }
4989
tls_application_data(tls_session_t * ssn,REQUEST * request)4990 fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
4991
4992 {
4993 int err;
4994 VALUE_PAIR **certs;
4995
4996 /*
4997 * Decrypt the complete record.
4998 */
4999 if (ssn->dirty_in.used > 0) {
5000 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
5001 ssn->dirty_in.used);
5002 if (err != (int) ssn->dirty_in.used) {
5003 record_init(&ssn->dirty_in);
5004 RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
5005 return FR_TLS_FAIL;
5006 }
5007 }
5008
5009 /*
5010 * Clear the dirty buffer now that we are done with it
5011 * and init the clean_out buffer to store decrypted data
5012 */
5013 record_init(&ssn->dirty_in);
5014 record_init(&ssn->clean_out);
5015
5016 /*
5017 * Read (and decrypt) the tunneled data from the
5018 * SSL session, and put it into the decrypted
5019 * data buffer.
5020 */
5021 err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
5022 if (err <= 0) {
5023 int code;
5024
5025 RDEBUG3("SSL_read Error");
5026
5027 code = SSL_get_error(ssn->ssl, err);
5028 switch (code) {
5029 case SSL_ERROR_WANT_READ:
5030 RDEBUG("(TLS) OpenSSL says that it needs to read more data.");
5031 return FR_TLS_MORE_FRAGMENTS;
5032
5033 case SSL_ERROR_WANT_WRITE:
5034 RDEBUG("(TLS) Error in fragmentation logic: SSL_WANT_WRITE");
5035 return FR_TLS_FAIL;
5036
5037 case SSL_ERROR_NONE:
5038 RDEBUG2("(TLS) No application data received. Assuming handshake is continuing...");
5039 err = 0;
5040 break;
5041
5042 case SSL_ERROR_ZERO_RETURN:
5043 RDEBUG2("(TLS) Other end closed the TLS tunnel.");
5044 return FR_TLS_FAIL;
5045
5046 default:
5047 REDEBUG("(TLS) Error in fragmentation logic - code %d", code);
5048 tls_error_io_log(request, ssn, err, "Failed reading application data from OpenSSL");
5049 return FR_TLS_FAIL;
5050 }
5051 }
5052
5053 /*
5054 * Passed all checks, successfully decrypted data
5055 */
5056 ssn->clean_out.used = err;
5057
5058 /*
5059 * Add the certificates to intermediate packets, so that
5060 * the inner tunnel policies can use them.
5061 */
5062 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
5063
5064 if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
5065
5066 return FR_TLS_OK;
5067 }
5068
5069
5070 /*
5071 * Acknowledge received is for one of the following messages sent earlier
5072 * 1. Handshake completed Message, so now send, EAP-Success
5073 * 2. Alert Message, now send, EAP-Failure
5074 * 3. Fragment Message, now send, next Fragment
5075 */
tls_ack_handler(tls_session_t * ssn,REQUEST * request)5076 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
5077 {
5078 if (ssn == NULL){
5079 REDEBUG("(TLS) Unexpected ACK received: No ongoing SSL session");
5080 return FR_TLS_INVALID;
5081 }
5082 if (!ssn->info.initialized) {
5083 RDEBUG("(TLS) No SSL info available. Waiting for more SSL data");
5084 return FR_TLS_REQUEST;
5085 }
5086
5087 if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
5088 REDEBUG("(TLS) Unexpected ACK received: We sent no previous messages");
5089 return FR_TLS_INVALID;
5090 }
5091
5092 switch (ssn->info.content_type) {
5093 case alert:
5094 RDEBUG2("(TLS) Peer ACKed our alert");
5095 return FR_TLS_FAIL;
5096
5097 case handshake:
5098 if ((ssn->is_init_finished) && (ssn->dirty_out.used == 0)) {
5099 RDEBUG2("(TLS) Peer ACKed our handshake fragment. handshake is finished");
5100
5101 /*
5102 * From now on all the content is
5103 * application data set it here as nobody else
5104 * sets it.
5105 */
5106 ssn->info.content_type = application_data;
5107 return FR_TLS_SUCCESS;
5108 } /* else more data to send */
5109
5110 RDEBUG2("(TLS) Peer ACKed our handshake fragment");
5111 /* Fragmentation handler, send next fragment */
5112 return FR_TLS_REQUEST;
5113
5114 case application_data:
5115 RDEBUG2("(TLS) Peer ACKed our application data fragment");
5116 return FR_TLS_REQUEST;
5117
5118 /*
5119 * For the rest of the conditions, switch over
5120 * to the default section below.
5121 */
5122 default:
5123 REDEBUG("(TLS) Invalid ACK received: %d", ssn->info.content_type);
5124 return FR_TLS_INVALID;
5125 }
5126 }
5127 #endif /* WITH_TLS */
5128
5129