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.
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.
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
20 * Copyright 2001 hereUare Communications, Inc. <raghud@hereuare.com>
21 * Copyright 2003 Alan DeKok <aland@freeradius.org>
22 * Copyright 2006 The FreeRADIUS server project
26 USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/rad_assert.h>
32 #ifdef HAVE_SYS_STAT_H
46 # ifdef HAVE_OPENSSL_RAND_H
47 # include <openssl/rand.h>
50 # ifdef HAVE_OPENSSL_OCSP_H
51 # include <openssl/ocsp.h>
54 # ifdef HAVE_OPENSSL_EVP_H
55 # include <openssl/evp.h>
57 # include <openssl/ssl.h>
59 #define LOG_PREFIX "tls"
61 #ifdef ENABLE_OPENSSL_VERSION_CHECK
62 typedef struct libssl_defect {
71 /* Record critical defects in libssl here, new versions of OpenSSL to older versions of OpenSSL. */
72 static libssl_defect_t libssl_defects[] =
75 .low = 0x01010101f, /* 1.1.0a */
76 .high = 0x01010101f, /* 1.1.0a */
77 .id = "CVE-2016-6309",
78 .name = "OCSP status request extension",
79 .comment = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
82 .low = 0x01010100f, /* 1.1.0 */
83 .high = 0x01010100f, /* 1.1.0 */
84 .id = "CVE-2016-6304",
85 .name = "OCSP status request extension",
86 .comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
89 .low = 0x01000209f, /* 1.0.2i */
90 .high = 0x01000209f, /* 1.0.2i */
91 .id = "CVE-2016-7052",
92 .name = "OCSP status request extension",
93 .comment = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
96 .low = 0x01000200f, /* 1.0.2 */
97 .high = 0x01000208f, /* 1.0.2h */
98 .id = "CVE-2016-6304",
99 .name = "OCSP status request extension",
100 .comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
103 .low = 0x01000100f, /* 1.0.1 */
104 .high = 0x01000114f, /* 1.0.1t */
105 .id = "CVE-2016-6304",
106 .name = "OCSP status request extension",
107 .comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
110 .low = 0x010001000, /* 1.0.1 */
111 .high = 0x01000106f, /* 1.0.1f */
112 .id = "CVE-2014-0160",
113 .name = "Heartbleed",
114 .comment = "For more information see http://heartbleed.com"
117 #endif /* ENABLE_OPENSSL_VERSION_CHECK */
119 FR_NAME_NUMBER const fr_tls_status_table[] = {
120 { "invalid", FR_TLS_INVALID },
121 { "request", FR_TLS_REQUEST },
122 { "response", FR_TLS_RESPONSE },
123 { "success", FR_TLS_SUCCESS },
124 { "fail", FR_TLS_FAIL },
125 { "noop", FR_TLS_NOOP },
127 { "start", FR_TLS_START },
129 { "ack", FR_TLS_ACK },
130 { "first fragment", FR_TLS_FIRST_FRAGMENT },
131 { "more fragments", FR_TLS_MORE_FRAGMENTS },
132 { "length included", FR_TLS_LENGTH_INCLUDED },
133 { "more fragments with length", FR_TLS_MORE_FRAGMENTS_WITH_LENGTH },
134 { "handled", FR_TLS_HANDLED },
138 /* index we use to store cached session VPs
139 * needs to be dynamic so we can supply a "free" function
141 int fr_tls_ex_index_vps = -1;
142 int fr_tls_ex_index_certs = -1;
145 static void session_close(tls_session_t *ssn);
146 static void session_init(tls_session_t *ssn);
149 static void record_init(record_t *buf);
150 static void record_close(record_t *buf);
151 static unsigned int record_plus(record_t *buf, void const *ptr,
153 static unsigned int record_minus(record_t *buf, void *ptr,
156 DIAG_OFF(format-nonliteral)
157 /** Print errors in the TLS thread local error stack
159 * Drains the thread local OpenSSL error queue, and prints out errors.
161 * @param[in] request The current request (may be NULL).
162 * @param[in] msg Error message describing the operation being attempted.
163 * @param[in] ap Arguments for msg.
164 * @return the number of errors drained from the stack.
166 static int tls_verror_log(REQUEST *request, char const *msg, va_list ap)
177 * Pop the first error, so ERR_peek_error()
178 * can be used to determine if there are
181 error = ERR_get_error_line(&file, &line);
184 p = talloc_vasprintf(request, msg, ap);
187 * Single line mode (there's only one error)
189 if (error && !ERR_peek_error()) {
190 ERR_error_string_n(error, buffer, sizeof(buffer));
193 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
194 ROPTIONAL(REDEBUG, ERROR, "%s: %s[%i]:%s", p, file, line, buffer);
196 ROPTIONAL(REDEBUG, ERROR, "%s: %s", p, buffer);
205 * Print the error we were given, irrespective
206 * of whether there were any OpenSSL errors.
208 ROPTIONAL(RERROR, ERROR, "%s", p);
213 * Stack mode (there are multiple errors)
215 if (!error) return 0;
217 ERR_error_string_n(error, buffer, sizeof(buffer));
219 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
220 ROPTIONAL(REDEBUG, ERROR, "%s[%i]:%s", file, line, buffer);
222 ROPTIONAL(REDEBUG, ERROR, "%s", buffer);
225 } while ((error = ERR_get_error_line(&file, &line)));
229 DIAG_ON(format-nonliteral)
231 /** Print errors in the TLS thread local error stack
233 * Drains the thread local OpenSSL error queue, and prints out errors.
235 * @param[in] request The current request (may be NULL).
236 * @param[in] msg Error message describing the operation being attempted.
237 * @param[in] ... Arguments for msg.
238 * @return the number of errors drained from the stack.
240 int tls_error_log(REQUEST *request, char const *msg, ...)
246 ret = tls_verror_log(request, msg, ap);
252 /** Print errors raised by OpenSSL I/O functions
254 * Drains the thread local OpenSSL error queue, and prints out errors
255 * based on the SSL handle and the return code of the I/O function.
257 * OpenSSL lists I/O functions to be:
265 * @param request The current request (may be NULL).
266 * @param session The current tls_session.
267 * @param ret from the I/O operation.
268 * @param msg Error message describing the operation being attempted.
269 * @param ... Arguments for msg.
271 * - 0 TLS session cannot continue.
272 * - 1 TLS session may still be viable.
274 int tls_error_io_log(REQUEST *request, tls_session_t *session, int ret, char const *msg, ...)
279 if (ERR_peek_error()) {
281 tls_verror_log(request, msg, ap);
285 error = SSL_get_error(session->ssl, ret);
288 * These seem to be harmless and already "dealt
289 * with" by our non-blocking environment. NB:
290 * "ZERO_RETURN" is the clean "error"
291 * indicating a successfully closed SSL
292 * tunnel. We let this happen because our IO
293 * loop should not appear to have broken on
294 * this condition - and outside the IO loop, the
295 * "shutdown" state is checked.
297 * Don't print anything if we ignore the error.
300 case SSL_ERROR_WANT_READ:
301 case SSL_ERROR_WANT_WRITE:
302 case SSL_ERROR_WANT_X509_LOOKUP:
303 case SSL_ERROR_ZERO_RETURN:
307 * These seem to be indications of a genuine
308 * error that should result in the SSL tunnel
309 * being regarded as "dead".
311 case SSL_ERROR_SYSCALL:
312 ROPTIONAL(REDEBUG, ERROR, "System call (I/O) error (%i)", ret);
316 ROPTIONAL(REDEBUG, ERROR, "TLS protocol error (%i)", ret);
320 * For any other errors that (a) exist, and (b)
321 * crop up - we need to interpret what to do with
322 * them - so "politely inform" the caller that
323 * the code needs updating here.
326 ROPTIONAL(REDEBUG, ERROR, "TLS session error %i (%i)", error, ret);
333 #ifdef PSK_MAX_IDENTITY_LEN
334 static bool identity_is_safe(const char *identity)
338 if (!identity) return true;
340 while ((c = *(identity++)) != '\0') {
341 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
342 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
353 * When a client uses TLS-PSK to talk to a server, this callback
354 * is used by the server to determine the PSK to use.
356 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
358 unsigned int max_psk_len)
360 unsigned int psk_len = 0;
361 fr_tls_server_conf_t *conf;
364 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
365 FR_TLS_EX_INDEX_CONF);
368 request = (REQUEST *)SSL_get_ex_data(ssl,
369 FR_TLS_EX_INDEX_REQUEST);
370 if (request && conf->psk_query) {
373 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
376 * The passed identity is weird. Deny it.
378 if (!identity_is_safe(identity)) {
379 RWDEBUG("Invalid characters in PSK identity %s", identity);
383 vp = pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
386 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
389 RWDEBUG("PSK expansion returned an empty string.");
394 * The returned key is truncated at MORE than
395 * OpenSSL can handle. That way we can detect
396 * the truncation, and complain about it.
398 if (hex_len > (2 * max_psk_len)) {
399 RWDEBUG("Returned PSK is too long (%u > %u)",
400 (unsigned int) hex_len, 2 * max_psk_len);
405 * Leave the TLS-PSK-Identity in the request, and
406 * convert the expansion from printable string
409 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
412 if (!conf->psk_identity) {
413 DEBUG("No static PSK identity set. Rejecting the user");
418 * No REQUEST, or no dynamic query. Just look for a
421 if (strcmp(identity, conf->psk_identity) != 0) {
422 ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
427 psk_len = strlen(conf->psk_password);
428 if (psk_len > (2 * max_psk_len)) return 0;
430 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
433 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
434 char *identity, unsigned int max_identity_len,
435 unsigned char *psk, unsigned int max_psk_len)
437 unsigned int psk_len;
438 fr_tls_server_conf_t *conf;
440 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
441 FR_TLS_EX_INDEX_CONF);
444 psk_len = strlen(conf->psk_password);
445 if (psk_len > (2 * max_psk_len)) return 0;
447 strlcpy(identity, conf->psk_identity, max_identity_len);
449 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
454 #define MAX_SESSION_SIZE (256)
457 void tls_session_id(SSL_SESSION *ssn, char *buffer, size_t bufsize)
459 #if OPENSSL_VERSION_NUMBER < 0x10001000L
462 size = ssn->session_id_length;
463 if (size > bufsize) size = bufsize;
465 fr_bin2hex(buffer, ssn->session_id, size);
470 p = SSL_SESSION_get_id(ssn, &size);
471 if (size > bufsize) size = bufsize;
473 fr_bin2hex(buffer, p, size);
480 static int _tls_session_free(tls_session_t *ssn)
483 * Free any opaque TTLS or PEAP data.
485 if ((ssn->opaque) && (ssn->free_opaque)) {
486 ssn->free_opaque(ssn->opaque);
495 tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
499 tls_session_t *ssn = NULL;
502 ssn = talloc_zero(ctx, tls_session_t);
503 if (!ssn) return NULL;
505 talloc_set_destructor(ssn, _tls_session_free);
507 ssn->ctx = conf->ctx;
509 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
511 ssn->ssl = SSL_new(ssn->ctx);
517 request = request_alloc(ssn);
518 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
521 * Add the message callback to identify what type of
522 * message/handshake is passed
524 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
525 SSL_set_msg_callback_arg(ssn->ssl, ssn);
526 SSL_set_info_callback(ssn->ssl, cbtls_info);
529 * Always verify the peer certificate.
531 DEBUG2("Requiring Server certificate");
532 verify_mode = SSL_VERIFY_PEER;
533 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
534 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
536 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
537 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
538 SSL_set_fd(ssn->ssl, fd);
539 ret = SSL_connect(ssn->ssl);
541 tls_error_io_log(NULL, ssn, ret, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_connect)");
547 ssn->mtu = conf->fragment_size;
552 /** Create a new TLS session
554 * Configures a new TLS session, configuring options, setting callbacks etc...
556 * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
557 * session is tied to another talloc'd object.
558 * @param conf to use to configure the tls session.
559 * @param request The current #REQUEST.
560 * @param client_cert Whether to require a client_cert.
561 * @return a new session on success, or NULL on error.
563 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
565 tls_session_t *state = NULL;
570 rad_assert(request != NULL);
572 RDEBUG2("Initiating new EAP-TLS session");
575 * Manually flush the sessions every so often. If HALF
576 * of the session lifetime has passed since we last
577 * flushed, then flush it again.
579 * FIXME: Also do it every N sessions?
581 if (conf->session_cache_enable &&
582 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
583 RDEBUG2("Flushing SSL sessions (of #%ld)", SSL_CTX_sess_number(conf->ctx));
585 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
586 conf->session_last_flushed = request->timestamp;
589 new_tls = SSL_new(conf->ctx);
590 if (new_tls == NULL) {
591 tls_error_log(request, "Error creating new TLS session");
595 /* We use the SSL's "app_data" to indicate a call-back */
596 SSL_set_app_data(new_tls, NULL);
598 if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
599 RERROR("Error allocating memory for SSL state");
603 talloc_set_destructor(state, _tls_session_free);
605 state->ctx = conf->ctx;
606 state->ssl = new_tls;
609 * Initialize callbacks
611 state->record_init = record_init;
612 state->record_close = record_close;
613 state->record_plus = record_plus;
614 state->record_minus = record_minus;
617 * Create & hook the BIOs to handle the dirty side of the
618 * SSL. This is *very important* as we want to handle
619 * the transmission part. Now the only IO interface
620 * that SSL is aware of, is our defined BIO buffers.
622 * This means that all SSL IO is done to/from memory,
623 * and we can update those BIOs from the packets we've
626 state->into_ssl = BIO_new(BIO_s_mem());
627 state->from_ssl = BIO_new(BIO_s_mem());
628 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
631 * Add the message callback to identify what type of
632 * message/handshake is passed
634 SSL_set_msg_callback(new_tls, cbtls_msg);
635 SSL_set_msg_callback_arg(new_tls, state);
636 SSL_set_info_callback(new_tls, cbtls_info);
639 * In Server mode we only accept.
641 SSL_set_accept_state(state->ssl);
644 * Verify the peer certificate, if asked.
647 RDEBUG2("Setting verify mode to require certificate from client");
648 verify_mode = SSL_VERIFY_PEER;
649 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
650 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
652 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
654 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
655 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
656 state->length_flag = conf->include_length;
659 * We use default fragment size, unless the Framed-MTU
660 * tells us it's too big. Note that we do NOT account
661 * for the EAP-TLS headers if conf->fragment_size is
662 * large, because that config item looks to be confusing.
664 * i.e. it should REALLY be called MTU, and the code here
665 * should figure out what that means for TLS fragment size.
666 * asking the administrator to know the internal details
667 * of EAP-TLS in order to calculate fragment sizes is
670 state->mtu = conf->fragment_size;
671 vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
672 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->mtu)) {
673 state->mtu = vp->vp_integer;
676 if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
682 * We are the server, we always get the dirty data
683 * (Handshake data is also considered as dirty data)
684 * During handshake, since SSL API handles itself,
685 * After clean-up, dirty_out will be filled with
686 * the data required for handshaking. So we check
687 * if dirty_out is empty then we simply send it back.
688 * As of now, if handshake is successful, then we keep going,
691 * Fill the Bio with the dirty data to clean it
692 * Get the cleaned data from SSL, if it is not Handshake data
694 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
698 if (ssn->invalid_hb_used) return 0;
700 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
701 if (err != (int) ssn->dirty_in.used) {
702 REDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
703 record_init(&ssn->dirty_in);
706 record_init(&ssn->dirty_in);
708 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
709 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
711 ssn->clean_out.used += err;
715 if (!tls_error_io_log(request, ssn, err, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)")) return 0;
717 /* Some Extra STATE information for easy debugging */
718 if (SSL_is_init_finished(ssn->ssl)) RDEBUG2("SSL Connection Established");
719 if (SSL_in_init(ssn->ssl)) RDEBUG2("In SSL Handshake Phase");
720 if (SSL_in_before(ssn->ssl)) RDEBUG2("Before SSL Handshake Phase");
721 if (SSL_in_accept_init(ssn->ssl)) RDEBUG2("In SSL Accept mode");
722 if (SSL_in_connect_init(ssn->ssl)) RDEBUG2("In SSL Connect mode");
724 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
726 * Cache the SSL_SESSION pointer.
728 if (!ssn->ssl_session && SSL_is_init_finished(ssn->ssl)) {
729 ssn->ssl_session = SSL_get_session(ssn->ssl);
730 if (!ssn->ssl_session) {
731 RDEBUG("Failed getting SSL session");
737 err = BIO_ctrl_pending(ssn->from_ssl);
739 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
740 sizeof(ssn->dirty_out.data));
742 ssn->dirty_out.used = err;
744 } else if (BIO_should_retry(ssn->from_ssl)) {
745 record_init(&ssn->dirty_in);
746 RDEBUG2("Asking for more data in tunnel");
750 tls_error_log(NULL, NULL);
751 record_init(&ssn->dirty_in);
755 RDEBUG2("SSL Application Data");
756 /* Its clean application data, do whatever we want */
757 record_init(&ssn->clean_out);
760 /* We are done with dirty_in, reinitialize it */
761 record_init(&ssn->dirty_in);
766 * Take cleartext user data, and encrypt it into the output buffer,
767 * to send to the client at the other end of the SSL connection.
769 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
774 * If there's un-encrypted data in 'clean_in', then write
775 * that data to the SSL session, and then call the BIO function
776 * to get that encrypted data from the SSL session, into
777 * a buffer which we can then package into an EAP packet.
779 * Based on Server's logic this clean_in is expected to
780 * contain the data to send to the client.
782 if (ssn->clean_in.used > 0) {
785 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
786 record_minus(&ssn->clean_in, NULL, written);
788 /* Get the dirty data from Bio to send it */
789 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
790 sizeof(ssn->dirty_out.data));
792 ssn->dirty_out.used = err;
794 if (!tls_error_io_log(request, ssn, err,
795 "Failed in " STRINGIFY(__FUNCTION__) " (SSL_write)")) {
804 static void session_init(tls_session_t *ssn)
807 ssn->into_ssl = ssn->from_ssl = NULL;
808 record_init(&ssn->clean_in);
809 record_init(&ssn->clean_out);
810 record_init(&ssn->dirty_in);
811 record_init(&ssn->dirty_out);
813 memset(&ssn->info, 0, sizeof(ssn->info));
816 ssn->fragment = false;
817 ssn->tls_msg_len = 0;
818 ssn->length_flag = false;
820 ssn->free_opaque = NULL;
823 static void session_close(tls_session_t *ssn)
825 SSL_set_quiet_shutdown(ssn->ssl, 1);
826 SSL_shutdown(ssn->ssl);
833 record_close(&ssn->clean_in);
834 record_close(&ssn->clean_out);
835 record_close(&ssn->dirty_in);
836 record_close(&ssn->dirty_out);
840 static void record_init(record_t *rec)
845 static void record_close(record_t *rec)
852 * Copy data to the intermediate buffer, before we send
855 static unsigned int record_plus(record_t *rec, void const *ptr,
858 unsigned int added = MAX_RECORD_SIZE - rec->used;
864 memcpy(rec->data + rec->used, ptr, added);
870 * Take data from the buffer, and give it to the caller.
872 static unsigned int record_minus(record_t *rec, void *ptr,
875 unsigned int taken = rec->used;
882 memcpy(ptr, rec->data, taken);
886 * This is pretty bad...
888 if (rec->used > 0) memmove(rec->data, rec->data + taken, rec->used);
893 void tls_session_information(tls_session_t *tls_session)
895 char const *str_write_p, *str_version, *str_content_type = "";
896 char const *str_details1 = "", *str_details2= "";
901 * Don't print this out in the normal course of
904 if (rad_debug_lvl == 0) return;
906 str_write_p = tls_session->info.origin ? ">>> send" : "<<< recv";
908 switch (tls_session->info.version) {
910 str_version = "SSL 2.0 ";
913 str_version = "SSL 3.0 ";
916 str_version = "TLS 1.0 ";
918 #ifdef TLS1_1_VERSION
920 str_version = "TLS 1.1 ";
923 #ifdef TLS1_2_VERSION
925 str_version = "TLS 1.2 ";
930 str_version = "TLS 1.3 ";
935 sprintf(buffer, "UNKNOWN TLS VERSION ?%04X?", tls_session->info.version);
936 str_version = buffer;
940 if (tls_session->info.version == SSL3_VERSION ||
941 tls_session->info.version == TLS1_VERSION) {
942 switch (tls_session->info.content_type) {
943 case SSL3_RT_CHANGE_CIPHER_SPEC:
944 str_content_type = "ChangeCipherSpec";
948 str_content_type = "Alert";
951 case SSL3_RT_HANDSHAKE:
952 str_content_type = "Handshake";
955 case SSL3_RT_APPLICATION_DATA:
956 str_content_type = "ApplicationData";
960 str_content_type = "UnknownContentType";
964 if (tls_session->info.content_type == SSL3_RT_ALERT) {
965 str_details1 = ", ???";
967 if (tls_session->info.record_len == 2) {
969 switch (tls_session->info.alert_level) {
970 case SSL3_AL_WARNING:
971 str_details1 = ", warning";
974 str_details1 = ", fatal";
978 str_details2 = " ???";
979 switch (tls_session->info.alert_description) {
980 case SSL3_AD_CLOSE_NOTIFY:
981 str_details2 = " close_notify";
984 case SSL3_AD_UNEXPECTED_MESSAGE:
985 str_details2 = " unexpected_message";
988 case SSL3_AD_BAD_RECORD_MAC:
989 str_details2 = " bad_record_mac";
992 case TLS1_AD_DECRYPTION_FAILED:
993 str_details2 = " decryption_failed";
996 case TLS1_AD_RECORD_OVERFLOW:
997 str_details2 = " record_overflow";
1000 case SSL3_AD_DECOMPRESSION_FAILURE:
1001 str_details2 = " decompression_failure";
1004 case SSL3_AD_HANDSHAKE_FAILURE:
1005 str_details2 = " handshake_failure";
1008 case SSL3_AD_BAD_CERTIFICATE:
1009 str_details2 = " bad_certificate";
1012 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
1013 str_details2 = " unsupported_certificate";
1016 case SSL3_AD_CERTIFICATE_REVOKED:
1017 str_details2 = " certificate_revoked";
1020 case SSL3_AD_CERTIFICATE_EXPIRED:
1021 str_details2 = " certificate_expired";
1024 case SSL3_AD_CERTIFICATE_UNKNOWN:
1025 str_details2 = " certificate_unknown";
1028 case SSL3_AD_ILLEGAL_PARAMETER:
1029 str_details2 = " illegal_parameter";
1032 case TLS1_AD_UNKNOWN_CA:
1033 str_details2 = " unknown_ca";
1036 case TLS1_AD_ACCESS_DENIED:
1037 str_details2 = " access_denied";
1040 case TLS1_AD_DECODE_ERROR:
1041 str_details2 = " decode_error";
1044 case TLS1_AD_DECRYPT_ERROR:
1045 str_details2 = " decrypt_error";
1048 case TLS1_AD_EXPORT_RESTRICTION:
1049 str_details2 = " export_restriction";
1052 case TLS1_AD_PROTOCOL_VERSION:
1053 str_details2 = " protocol_version";
1056 case TLS1_AD_INSUFFICIENT_SECURITY:
1057 str_details2 = " insufficient_security";
1060 case TLS1_AD_INTERNAL_ERROR:
1061 str_details2 = " internal_error";
1064 case TLS1_AD_USER_CANCELLED:
1065 str_details2 = " user_canceled";
1068 case TLS1_AD_NO_RENEGOTIATION:
1069 str_details2 = " no_renegotiation";
1075 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
1076 str_details1 = "???";
1078 if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
1079 case SSL3_MT_HELLO_REQUEST:
1080 str_details1 = ", HelloRequest";
1083 case SSL3_MT_CLIENT_HELLO:
1084 str_details1 = ", ClientHello";
1087 case SSL3_MT_SERVER_HELLO:
1088 str_details1 = ", ServerHello";
1091 case SSL3_MT_CERTIFICATE:
1092 str_details1 = ", Certificate";
1095 case SSL3_MT_SERVER_KEY_EXCHANGE:
1096 str_details1 = ", ServerKeyExchange";
1099 case SSL3_MT_CERTIFICATE_REQUEST:
1100 str_details1 = ", CertificateRequest";
1103 case SSL3_MT_SERVER_DONE:
1104 str_details1 = ", ServerHelloDone";
1107 case SSL3_MT_CERTIFICATE_VERIFY:
1108 str_details1 = ", CertificateVerify";
1111 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1112 str_details1 = ", ClientKeyExchange";
1115 case SSL3_MT_FINISHED:
1116 str_details1 = ", Finished";
1122 snprintf(tls_session->info.info_description,
1123 sizeof(tls_session->info.info_description),
1124 "%s %s%s [length %04lx]%s%s\n",
1125 str_write_p, str_version, str_content_type,
1126 (unsigned long)tls_session->info.record_len,
1127 str_details1, str_details2);
1129 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
1130 ROPTIONAL(RDEBUG2, DEBUG2, "%s", tls_session->info.info_description);
1133 static CONF_PARSER cache_config[] = {
1134 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
1136 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
1137 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
1139 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
1140 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
1141 CONF_PARSER_TERMINATOR
1144 static CONF_PARSER verify_config[] = {
1145 { "skip_if_ocsp_ok", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, verify_skip_if_ocsp_ok), "no" },
1146 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
1147 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
1148 CONF_PARSER_TERMINATOR
1151 #ifdef HAVE_OPENSSL_OCSP_H
1152 static CONF_PARSER ocsp_config[] = {
1153 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
1154 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
1155 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
1156 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
1157 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
1158 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
1159 CONF_PARSER_TERMINATOR
1163 static CONF_PARSER tls_server_config[] = {
1164 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1165 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
1166 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1167 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1168 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1169 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1170 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
1171 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1172 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1173 #ifdef PSK_MAX_IDENTITY_LEN
1174 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
1175 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
1176 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
1178 { "dh_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, dh_file), NULL },
1179 { "random_file", FR_CONF_OFFSET(PW_TYPE_FILE_EXISTS, fr_tls_server_conf_t, random_file), NULL },
1180 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1181 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1182 { "auto_chain", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, auto_chain), "yes" },
1183 { "disable_single_dh_use", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_single_dh_use), NULL },
1184 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1185 #ifdef X509_V_FLAG_CRL_CHECK_ALL
1186 { "check_all_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), "no" },
1188 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
1189 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1190 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1191 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1192 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
1194 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1195 #ifndef OPENSSL_NO_ECDH
1196 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1200 #ifdef SSL_OP_NO_TLSv1
1201 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1204 #ifdef SSL_OP_NO_TLSv1_1
1205 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1208 #ifdef SSL_OP_NO_TLSv1_2
1209 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1212 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
1214 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
1216 #ifdef HAVE_OPENSSL_OCSP_H
1217 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
1219 CONF_PARSER_TERMINATOR
1223 static CONF_PARSER tls_client_config[] = {
1224 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1225 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1226 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1227 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1228 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1229 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1230 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1231 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1232 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1233 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1234 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1235 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1236 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1237 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1238 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1240 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1241 #ifndef OPENSSL_NO_ECDH
1242 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1246 #ifdef SSL_OP_NO_TLSv1
1247 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1250 #ifdef SSL_OP_NO_TLSv1_1
1251 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1254 #ifdef SSL_OP_NO_TLSv1_2
1255 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1257 CONF_PARSER_TERMINATOR
1262 * TODO: Check for the type of key exchange * like conf->dh_key
1264 static int load_dh_params(SSL_CTX *ctx, char *file)
1269 if (!file) return 0;
1271 if ((bio = BIO_new_file(file, "r")) == NULL) {
1272 ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
1276 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1279 WARN(LOG_PREFIX ": Unable to set DH parameters. DH cipher suites may not work!");
1280 WARN(LOG_PREFIX ": Fix this by running the OpenSSL command listed in eap.conf");
1284 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1285 ERROR(LOG_PREFIX ": Unable to set DH parameters");
1296 * Print debugging messages, and free data.
1298 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1300 char buffer[2 * MAX_SESSION_SIZE + 1];
1301 fr_tls_server_conf_t *conf;
1303 tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1305 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1307 DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
1315 DEBUG2(LOG_PREFIX ": Removing session %s from the cache", buffer);
1317 /* remove session and any cached VPs */
1318 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1319 conf->session_cache_path, FR_DIR_SEP, buffer);
1320 rv = unlink(filename);
1322 DEBUG2(LOG_PREFIX ": Could not remove persisted session file %s: %s",
1323 filename, fr_syserror(errno));
1325 /* VPs might be absent; might not have been written to disk yet */
1326 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1327 conf->session_cache_path, FR_DIR_SEP, buffer);
1334 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1336 char buffer[2 * MAX_SESSION_SIZE + 1];
1337 fr_tls_server_conf_t *conf;
1338 unsigned char *sess_blob = NULL;
1340 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1342 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1344 RWDEBUG("Failed to find TLS configuration in session");
1348 tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1351 int fd, rv, todo, blob_len;
1355 RDEBUG2("Serialising session %s, and storing in cache", buffer);
1357 /* find out what length data we need */
1358 blob_len = i2d_SSL_SESSION(sess, NULL);
1360 /* something went wrong */
1361 RWDEBUG("Session serialisation failed, couldn't determine required buffer length");
1366 /* Do not convert to TALLOC - Thread safety */
1367 /* alloc and convert to ASN.1 */
1368 sess_blob = malloc(blob_len);
1370 RWDEBUG("Session serialisation failed, couldn't allocate buffer (%d bytes)", blob_len);
1373 /* openssl mutates &p */
1375 rv = i2d_SSL_SESSION(sess, &p);
1376 if (rv != blob_len) {
1377 RWDEBUG("Session serialisation failed");
1381 /* open output file */
1382 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1383 conf->session_cache_path, FR_DIR_SEP, buffer);
1384 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1386 RERROR("Session serialisation failed, failed opening session file %s: %s",
1387 filename, fr_syserror(errno));
1394 rv = write(fd, p, todo);
1396 RWDEBUG("Failed writing session: %s", fr_syserror(errno));
1404 RWDEBUG("Wrote session %s to %s (%d bytes)", buffer, filename, blob_len);
1413 static SSL_SESSION *cbtls_get_session(SSL *ssl, unsigned char *data, int len, int *copy)
1416 char buffer[2 * MAX_SESSION_SIZE + 1];
1417 fr_tls_server_conf_t *conf;
1418 TALLOC_CTX *talloc_ctx;
1420 SSL_SESSION *sess = NULL;
1421 unsigned char *sess_data = NULL;
1422 PAIR_LIST *pairlist = NULL;
1424 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1426 rad_assert(request != NULL);
1429 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1431 fr_bin2hex(buffer, data, size);
1433 RDEBUG2("Peer requested cached session: %s", buffer);
1437 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1439 RWDEBUG("Failed to find TLS configuration in session");
1443 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1449 unsigned char const **o;
1454 VALUE_PAIR *vps = NULL;
1456 /* read in the cached VPs from the .vps file */
1457 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1458 conf->session_cache_path, FR_DIR_SEP, buffer);
1459 rv = pairlist_read(talloc_ctx, filename, &pairlist, 1);
1461 /* not safe to un-persist a session w/o VPs */
1462 RWDEBUG("Failed loading persisted VPs for session %s", buffer);
1466 /* load the actual SSL session */
1467 snprintf(filename, sizeof(filename), "%s%c%s.asn1", conf->session_cache_path, FR_DIR_SEP, buffer);
1468 fd = open(filename, O_RDONLY);
1470 RWDEBUG("No persisted session file %s: %s", filename, fr_syserror(errno));
1474 rv = fstat(fd, &st);
1476 RWDEBUG("Failed stating persisted session file %s: %s", filename, fr_syserror(errno));
1481 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1483 RWDEBUG("Failed allocating buffer for persisted session (%d bytes)", (int) st.st_size);
1491 rv = read(fd, q, todo);
1493 RWDEBUG("Failed reading persisted session: %s", fr_syserror(errno));
1503 * OpenSSL mutates what's passed in, so we assign sess_data to q,
1504 * so the value of q gets mutated, and not the value of sess_data.
1506 * We then need a pointer to hold &q, but it can't be const, because
1507 * clang complains about lack of consting in nested pointer types.
1509 * So we memcpy the value of that pointer, to one that
1510 * does have a const, which we then pass into d2i_SSL_SESSION *sigh*.
1514 memcpy(&o, &p, sizeof(o));
1515 sess = d2i_SSL_SESSION(NULL, o, st.st_size);
1517 RWDEBUG("Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1521 /* move the cached VPs into the session */
1522 fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &pairlist->reply, 0, 0, TAG_ANY);
1524 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
1525 RWDEBUG("Successfully restored session %s", buffer);
1526 rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
1529 if (sess_data) talloc_free(sess_data);
1530 if (pairlist) pairlist_free(&pairlist);
1535 #ifdef HAVE_OPENSSL_OCSP_H
1537 /** Extract components of OCSP responser URL from a certificate
1539 * @param[in] cert to extract URL from.
1540 * @param[out] host_out Portion of the URL (must be freed with free()).
1541 * @param[out] port_out Port portion of the URL (must be freed with free()).
1542 * @param[out] path_out Path portion of the URL (must be freed with free()).
1543 * @param[out] is_https Whether the responder should be contacted using https.
1545 * - 0 if no valid URL is contained in the certificate.
1546 * - 1 if a URL was found and parsed.
1547 * - -1 if at least one URL was found, but none could be parsed.
1549 static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out,
1550 char **path_out, int *is_https)
1553 bool found_uri = false;
1555 AUTHORITY_INFO_ACCESS *aia;
1556 ACCESS_DESCRIPTION *ad;
1558 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1560 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1561 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1562 if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
1563 if (ad->location->type != GEN_URI) continue;
1566 if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
1567 port_out, path_out, is_https)) return 1;
1569 return found_uri ? -1 : 0;
1573 * This function sends a OCSP request to a defined OCSP responder
1574 * and checks the OCSP response for correctness.
1577 /* Maximum leeway in validity period: default 5 minutes */
1578 #define MAX_VALIDITY_PERIOD (5 * 60)
1581 OCSP_STATUS_FAILED = 0,
1583 OCSP_STATUS_SKIPPED = 2,
1586 static ocsp_status_t ocsp_check(REQUEST *request, X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1587 fr_tls_server_conf_t *conf)
1589 OCSP_CERTID *certid;
1591 OCSP_RESPONSE *resp = NULL;
1592 OCSP_BASICRESP *bresp = NULL;
1596 char hostheader[1024];
1598 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1599 BIO *cbio, *bio_out;
1600 ocsp_status_t ocsp_status = OCSP_STATUS_FAILED;
1602 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1604 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1608 struct timeval when;
1613 * Create OCSP Request
1615 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1616 req = OCSP_REQUEST_new();
1617 OCSP_request_add0_id(req, certid);
1618 if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
1621 * Send OCSP Request and get OCSP Response
1624 /* Get OCSP responder URL */
1625 if (conf->ocsp_override_url) {
1629 memcpy(&url, &conf->ocsp_url, sizeof(url));
1630 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1631 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1632 if (!host || !port || !path) {
1633 RWDEBUG("ocsp: Host or port or path missing from configured URL \"%s\". Not doing OCSP", url);
1639 ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1642 RWDEBUG("ocsp: Invalid URL in certificate. Not doing OCSP");
1646 if (conf->ocsp_url) {
1647 RWDEBUG("ocsp: No OCSP URL in certificate, falling back to configured URL");
1650 RWDEBUG("ocsp: No OCSP URL in certificate. Not doing OCSP");
1658 RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
1660 /* Check host and port length are sane, then create Host: HTTP header */
1661 if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1662 RWDEBUG("ocsp: Host and port too long");
1665 snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1667 /* Setup BIO socket to OCSP responder */
1668 cbio = BIO_new_connect(host);
1671 if (rad_debug_lvl) {
1672 if (default_log.dst == L_DST_STDOUT) {
1673 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1674 } else if (default_log.dst == L_DST_STDERR) {
1675 bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1679 BIO_set_conn_port(cbio, port);
1680 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1681 BIO_do_connect(cbio);
1683 /* Send OCSP request and wait for response */
1684 resp = OCSP_sendreq_bio(cbio, path, req);
1686 REDEBUG("ocsp: Couldn't get OCSP response");
1687 ocsp_status = OCSP_STATUS_SKIPPED;
1691 if (conf->ocsp_timeout)
1692 BIO_set_nbio(cbio, 1);
1694 rc = BIO_do_connect(cbio);
1695 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1696 REDEBUG("ocsp: Couldn't connect to OCSP responder");
1697 ocsp_status = OCSP_STATUS_SKIPPED;
1701 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1703 REDEBUG("ocsp: Couldn't create OCSP request");
1704 ocsp_status = OCSP_STATUS_SKIPPED;
1708 if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1709 REDEBUG("ocsp: Couldn't set Host header");
1710 ocsp_status = OCSP_STATUS_SKIPPED;
1714 if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1715 REDEBUG("ocsp: Couldn't add data to OCSP request");
1716 ocsp_status = OCSP_STATUS_SKIPPED;
1720 gettimeofday(&when, NULL);
1721 when.tv_sec += conf->ocsp_timeout;
1724 rc = OCSP_sendreq_nbio(&resp, ctx);
1725 if (conf->ocsp_timeout) {
1726 gettimeofday(&now, NULL);
1727 if (!timercmp(&now, &when, <))
1730 } while ((rc == -1) && BIO_should_retry(cbio));
1732 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1733 REDEBUG("ocsp: Response timed out");
1734 ocsp_status = OCSP_STATUS_SKIPPED;
1738 OCSP_REQ_CTX_free(ctx);
1741 REDEBUG("ocsp: Couldn't get OCSP response");
1742 ocsp_status = OCSP_STATUS_SKIPPED;
1747 /* Verify OCSP response status */
1748 status = OCSP_response_status(resp);
1749 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1750 REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
1753 bresp = OCSP_response_get1_basic(resp);
1754 if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1755 REDEBUG("ocsp: Response has wrong nonce value");
1758 if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1759 REDEBUG("ocsp: Couldn't verify OCSP basic response");
1763 /* Verify OCSP cert status */
1764 if (!OCSP_resp_find_status(bresp, certid, &status, &reason, &rev, &thisupd, &nextupd)) {
1765 REDEBUG("ocsp: No Status found");
1769 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1771 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1772 ERR_print_errors(bio_out);
1778 BIO_puts(bio_out, "\tThis Update: ");
1779 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1780 BIO_puts(bio_out, "\n");
1782 BIO_puts(bio_out, "\tNext Update: ");
1783 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1784 BIO_puts(bio_out, "\n");
1789 case V_OCSP_CERTSTATUS_GOOD:
1790 RDEBUG2("ocsp: Cert status: good");
1791 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1792 vp->vp_integer = 1; /* yes */
1793 ocsp_status = OCSP_STATUS_OK;
1797 /* REVOKED / UNKNOWN */
1798 REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
1799 if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
1802 BIO_puts(bio_out, "\tRevocation Time: ");
1803 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1804 BIO_puts(bio_out, "\n");
1810 /* Free OCSP Stuff */
1811 OCSP_REQUEST_free(req);
1812 OCSP_RESPONSE_free(resp);
1817 if (bio_out) BIO_free(bio_out);
1818 OCSP_BASICRESP_free(bresp);
1820 switch (ocsp_status) {
1821 case OCSP_STATUS_OK:
1822 RDEBUG2("ocsp: Certificate is valid");
1825 case OCSP_STATUS_SKIPPED:
1827 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1828 vp->vp_integer = 2; /* skipped */
1829 if (conf->ocsp_softfail) {
1830 RWDEBUG("ocsp: Unable to check certificate, assuming it's valid");
1831 RWDEBUG("ocsp: This may be insecure");
1833 /* Remove OpenSSL errors from queue or handshake will fail */
1834 while (ERR_get_error());
1836 ocsp_status = OCSP_STATUS_SKIPPED;
1838 REDEBUG("ocsp: Unable to check certificate, failing");
1839 ocsp_status = OCSP_STATUS_FAILED;
1844 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1845 vp->vp_integer = 0; /* no */
1846 REDEBUG("ocsp: Certificate has been expired/revoked");
1852 #endif /* HAVE_OPENSSL_OCSP_H */
1855 * For creating certificate attributes.
1857 static char const *cert_attr_names[8][2] = {
1858 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1859 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1860 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1861 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1862 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1863 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1864 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1865 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1868 #define FR_TLS_SERIAL (0)
1869 #define FR_TLS_EXPIRATION (1)
1870 #define FR_TLS_SUBJECT (2)
1871 #define FR_TLS_ISSUER (3)
1872 #define FR_TLS_CN (4)
1873 #define FR_TLS_SAN_EMAIL (5)
1874 #define FR_TLS_SAN_DNS (6)
1875 #define FR_TLS_SAN_UPN (7)
1878 * Before trusting a certificate, you must make sure that the
1879 * certificate is 'valid'. There are several steps that your
1880 * application can take in determining if a certificate is
1881 * valid. Commonly used steps are:
1883 * 1.Verifying the certificate's signature, and verifying that
1884 * the certificate has been issued by a trusted Certificate
1887 * 2.Verifying that the certificate is valid for the present date
1888 * (i.e. it is being presented within its validity dates).
1890 * 3.Verifying that the certificate has not been revoked by its
1891 * issuing Certificate Authority, by checking with respect to a
1892 * Certificate Revocation List (CRL).
1894 * 4.Verifying that the credentials presented by the certificate
1895 * fulfill additional requirements specific to the application,
1896 * such as with respect to access control lists or with respect
1897 * to OCSP (Online Certificate Status Processing).
1899 * NOTE: This callback will be called multiple times based on the
1900 * depth of the root certificate chain
1902 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1904 char subject[1024]; /* Used for the subject name */
1905 char issuer[1024]; /* Used for the issuer name */
1906 char attribute[1024];
1908 char common_name[1024];
1912 X509_CINF *client_inf;
1913 STACK_OF(X509_EXTENSION) *ext_list;
1915 int err, depth, lookup, loc;
1916 fr_tls_server_conf_t *conf;
1919 ASN1_INTEGER *sn = NULL;
1920 ASN1_TIME *asn_time = NULL;
1923 #ifdef HAVE_OPENSSL_OCSP_H
1924 X509_STORE *ocsp_store = NULL;
1926 bool do_verify = false;
1929 TALLOC_CTX *talloc_ctx;
1933 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1934 err = X509_STORE_CTX_get_error(ctx);
1935 depth = X509_STORE_CTX_get_error_depth(ctx);
1940 * Log client/issuing cert. If there's an error, log
1943 if ((lookup > 1) && !my_ok) lookup = 1;
1946 * Retrieve the pointer to the SSL of the connection currently treated
1947 * and the application specific data stored into the SSL object.
1949 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1950 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1951 if (!conf) return 1;
1953 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1954 rad_assert(request != NULL);
1955 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1957 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1958 #ifdef HAVE_OPENSSL_OCSP_H
1959 ocsp_store = conf->ocsp_store;
1962 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1965 * Get the Serial Number
1968 sn = X509_get_serialNumber(client_cert);
1970 RDEBUG2("Creating attributes from certificate OIDs");
1974 * For this next bit, we create the attributes *only* if
1975 * we're at the client or issuing certificate, AND we
1976 * have a user identity. i.e. we don't create the
1977 * attributes for RadSec connections.
1979 if (certs && identity &&
1980 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1984 for (i = 0; i < sn->length; i++) {
1985 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1988 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1989 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1994 * Get the Expiration Date
1997 asn_time = X509_get_notAfter(client_cert);
1998 if (certs && identity && (lookup <= 1) && asn_time &&
1999 (asn_time->length < (int) sizeof(buf))) {
2000 memcpy(buf, (char*) asn_time->data, asn_time->length);
2001 buf[asn_time->length] = '\0';
2002 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
2003 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2007 * Get the Subject & Issuer
2009 subject[0] = issuer[0] = '\0';
2010 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
2012 subject[sizeof(subject) - 1] = '\0';
2013 if (certs && identity && (lookup <= 1) && subject[0]) {
2014 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
2015 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2018 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
2020 issuer[sizeof(issuer) - 1] = '\0';
2021 if (certs && identity && (lookup <= 1) && issuer[0]) {
2022 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
2023 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2027 * Get the Common Name, if there is a subject.
2029 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
2030 NID_commonName, common_name, sizeof(common_name));
2031 common_name[sizeof(common_name) - 1] = '\0';
2032 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
2033 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
2034 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2038 * Get the RFC822 Subject Alternative Name
2040 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
2041 if (certs && (lookup <= 1) && (loc >= 0)) {
2042 X509_EXTENSION *ext = NULL;
2043 GENERAL_NAMES *names = NULL;
2046 if ((ext = X509_get_ext(client_cert, loc)) &&
2047 (names = X509V3_EXT_d2i(ext))) {
2048 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
2049 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2051 switch (name->type) {
2054 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
2055 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
2056 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2058 #endif /* GEN_EMAIL */
2061 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
2062 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
2063 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2065 #endif /* GEN_DNS */
2066 #ifdef GEN_OTHERNAME
2068 /* look for a MS UPN */
2069 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
2070 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
2071 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
2072 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
2073 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
2074 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2077 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
2082 #endif /* GEN_OTHERNAME */
2084 /* XXX TODO handle other SAN types */
2090 sk_GENERAL_NAME_free(names);
2094 * If the CRL has expired, that might still be OK.
2097 (conf->allow_expired_crl) &&
2098 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
2100 X509_STORE_CTX_set_error( ctx, 0 );
2104 char const *p = X509_verify_cert_error_string(err);
2105 RERROR("SSL says error %d : %s", err, p);
2111 client_inf = client_cert->cert_info;
2112 ext_list = client_inf->extensions;
2118 * Grab the X509 extensions, and create attributes out of them.
2119 * For laziness, we re-use the OpenSSL names
2121 if (certs && (sk_X509_EXTENSION_num(ext_list) > 0)) {
2126 out = BIO_new(BIO_s_mem());
2127 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
2129 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
2131 X509_EXTENSION *ext;
2133 ext = sk_X509_EXTENSION_value(ext_list, i);
2135 obj = X509_EXTENSION_get_object(ext);
2136 i2a_ASN1_OBJECT(out, obj);
2137 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
2138 if (len <= 0) continue;
2140 attribute[16 + len] = '\0';
2142 for (p = attribute + 16; *p != '\0'; p++) {
2143 if (*p == ' ') *p = '-';
2146 X509V3_EXT_print(out, ext, 0, 0);
2147 len = BIO_read(out, value , sizeof(value) - 1);
2148 if (len <= 0) continue;
2152 vp = fr_pair_make(talloc_ctx, certs, attribute, value, T_OP_ADD);
2154 RDEBUG3("Skipping %s += '%s'. Please check that both the "
2155 "attribute and value are defined in the dictionaries",
2159 * rdebug_pair_list indents (so pre REXDENT())
2162 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
2172 switch (ctx->error) {
2173 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2174 RERROR("issuer=%s", issuer);
2177 case X509_V_ERR_CERT_NOT_YET_VALID:
2178 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2179 RERROR("notBefore=");
2181 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
2185 case X509_V_ERR_CERT_HAS_EXPIRED:
2186 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2187 RERROR("notAfter=");
2189 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
2195 * If we're at the actual client cert, apply additional
2200 * If the conf tells us to, check cert issuer
2201 * against the specified value and fail
2202 * verification if they don't match.
2204 if (conf->check_cert_issuer &&
2205 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
2206 AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
2207 issuer, conf->check_cert_issuer);
2212 * If the conf tells us to, check the CN in the
2213 * cert against xlat'ed value, but only if the
2214 * previous checks passed.
2216 if (my_ok && conf->check_cert_cn) {
2217 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
2218 /* if this fails, fail the verification */
2221 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
2222 if (strcmp(cn_str, common_name) != 0) {
2223 AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
2224 common_name, cn_str);
2228 } /* check_cert_cn */
2230 #ifdef HAVE_OPENSSL_OCSP_H
2233 * No OCSP, allow external verification.
2235 if (!conf->ocsp_enable) {
2239 RDEBUG2("Starting OCSP Request");
2240 if ((X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) ||
2243 * Allow for external verify.
2245 RERROR("Couldn't get issuer_cert for %s", common_name);
2250 * Do the full OCSP checks.
2252 * If they fail, don't run the external verify. We don't want
2253 * to allow admins to force authentication success for bad
2256 * If the OCSP checks succeed, check whether we still want to
2257 * run the external verification routine. If it's marked as
2258 * "skip verify on OK", then we don't do verify.
2260 my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
2261 if (my_ok != OCSP_STATUS_FAILED) {
2262 do_verify = !conf->verify_skip_if_ocsp_ok;
2269 if ((my_ok != OCSP_STATUS_FAILED)
2270 #ifdef HAVE_OPENSSL_OCSP_H
2273 ) while (conf->verify_client_cert_cmd) {
2278 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
2279 conf->verify_tmp_dir, main_config.name);
2280 fd = mkstemp(filename);
2282 RDEBUG("Failed creating file in %s: %s",
2283 conf->verify_tmp_dir, fr_syserror(errno));
2287 fp = fdopen(fd, "w");
2290 RDEBUG("Failed opening file %s: %s",
2291 filename, fr_syserror(errno));
2295 if (!PEM_write_X509(fp, client_cert)) {
2297 RDEBUG("Failed writing certificate to file");
2302 if (!pair_make_request("TLS-Client-Cert-Filename",
2303 filename, T_OP_SET)) {
2304 RDEBUG("Failed creating TLS-Client-Cert-Filename");
2309 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2310 if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2311 request->packet->vps,
2312 true, true, EXEC_TIMEOUT) != 0) {
2313 AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
2316 RDEBUG("Client certificate CN %s passed external validation", common_name);
2325 if (certs && request && !my_ok) {
2326 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
2329 if (RDEBUG_ENABLED3) {
2330 RDEBUG3("chain-depth : %d", depth);
2331 RDEBUG3("error : %d", err);
2333 if (identity) RDEBUG3("identity : %s", *identity);
2334 RDEBUG3("common name : %s", common_name);
2335 RDEBUG3("subject : %s", subject);
2336 RDEBUG3("issuer : %s", issuer);
2337 RDEBUG3("verify return : %d", my_ok);
2340 return (my_ok != 0);
2344 #ifdef HAVE_OPENSSL_OCSP_H
2346 * Create Global X509 revocation store and use it to verify
2349 * - Load the trusted CAs
2350 * - Load the trusted issuer certificates
2352 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2354 X509_STORE *store = NULL;
2356 store = X509_STORE_new();
2358 /* Load the CAs we trust */
2359 if (conf->ca_file || conf->ca_path)
2360 if (!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2361 tls_error_log(NULL, "Error reading Trusted root CA list \"%s\"", conf->ca_file);
2365 #ifdef X509_V_FLAG_CRL_CHECK
2366 if (conf->check_crl)
2367 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2369 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2370 if (conf->check_all_crl)
2371 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
2375 #endif /* HAVE_OPENSSL_OCSP_H */
2377 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2378 #ifndef OPENSSL_NO_ECDH
2379 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
2384 if (!ecdh_curve || !*ecdh_curve) return 0;
2386 nid = OBJ_sn2nid(ecdh_curve);
2388 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
2392 ecdh = EC_KEY_new_by_curve_name(nid);
2394 ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
2398 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2400 if (!disable_single_dh_use) {
2401 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2412 * DIE OPENSSL DIE DIE DIE
2414 * What a palaver, just to free some data attached the
2415 * session. We need to do this because the "remove" callback
2416 * is called when refcount > 0 sometimes, if another thread
2417 * is using the session
2419 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2420 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2421 UNUSED long argl, UNUSED void *argp)
2423 VALUE_PAIR *vp = data_ptr;
2426 DEBUG2(LOG_PREFIX ": Freeing cached session VPs");
2428 fr_pair_list_free(&vp);
2431 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2432 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2433 UNUSED long argl, UNUSED void *argp)
2435 VALUE_PAIR **certs = data_ptr;
2438 DEBUG2(LOG_PREFIX ": Freeing cached session Certificates");
2440 fr_pair_list_free(certs);
2443 /** Add all the default ciphers and message digests reate our context.
2445 * This should be called exactly once from main, before reading the main config
2446 * or initialising any modules.
2448 void tls_global_init(void)
2450 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
2451 SSL_library_init(); /* initialize library */
2452 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2453 OPENSSL_config(NULL);
2456 * Initialize the index for the certificates.
2458 fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2461 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2462 /** Check for vulnerable versions of libssl
2464 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2465 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2467 int tls_global_version_check(char const *acknowledged)
2473 return 0; /* Painless Security customization */
2475 if (strcmp(acknowledged, "yes") == 0) return 0;
2477 /* Check for bad versions */
2478 v = (uint64_t) SSLeay();
2480 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2481 libssl_defect_t *defect = &libssl_defects[i];
2483 if ((v >= defect->low) && (v <= defect->high)) {
2485 * If the CVE is acknowledged, allow it.
2487 if (!bad && (strcmp(acknowledged, defect->id) == 0)) return 0;
2489 ERROR("Refusing to start with libssl version %s (in range %s)",
2490 ssl_version(), ssl_version_range(defect->low, defect->high));
2491 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2492 ERROR("%s", defect->comment);
2495 * Only warn about the first one...
2498 INFO("Once you have verified libssl has been correctly patched, "
2499 "set security.allow_vulnerable_openssl = '%s'", defect->id);
2512 /** Free any memory alloced by libssl
2515 void tls_global_cleanup(void)
2517 ERR_remove_state(0);
2519 CONF_modules_unload(1);
2522 CRYPTO_cleanup_all_ex_data();
2525 /** Create SSL context
2527 * - Load the trusted CAs
2528 * - Load the Private key & the certificate
2529 * - Set the Context options & Verify options
2531 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2534 X509_STORE *certstore;
2535 int verify_mode = SSL_VERIFY_NONE;
2536 int ctx_options = 0;
2537 int ctx_tls_versions = 0;
2541 * SHA256 is in all versions of OpenSSL, but isn't
2542 * initialized by default. It's needed for WiMAX
2545 #ifdef HAVE_OPENSSL_EVP_SHA256
2546 EVP_add_digest(EVP_sha256());
2549 ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
2551 tls_error_log(NULL, "Failed creating TLS context");
2556 * Save the config on the context so that callbacks which
2557 * only get SSL_CTX* e.g. session persistence, can get it
2559 SSL_CTX_set_app_data(ctx, conf);
2562 * Identify the type of certificates that needs to be loaded
2564 if (conf->file_type) {
2565 type = SSL_FILETYPE_PEM;
2567 type = SSL_FILETYPE_ASN1;
2571 * Set the password to load private key
2573 if (conf->private_key_password) {
2576 * We don't want to put the private key password in eap.conf, so check
2577 * for our special string which indicates we should get the password
2580 char const* special_string = "Apple:UseCertAdmin";
2581 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2584 long const max_password_len = 128;
2585 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2586 conf->private_key_file);
2588 DEBUG2(LOG_PREFIX ": Getting private key passphrase using command \"%s\"", cmd);
2590 FILE* cmd_pipe = popen(cmd, "r");
2592 ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
2593 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2597 rad_const_free(conf->private_key_password);
2598 password = talloc_array(conf, char, max_password_len);
2600 ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
2601 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2606 fgets(password, max_password_len, cmd_pipe);
2609 /* Get rid of newline at end of password. */
2610 password[strlen(password) - 1] = '\0';
2612 DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
2613 conf->private_key_password = password;
2620 memcpy(&password, &conf->private_key_password, sizeof(password));
2621 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2622 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2626 #ifdef PSK_MAX_IDENTITY_LEN
2629 * No dynamic query exists. There MUST be a
2630 * statically configured identity and password.
2632 if (conf->psk_query && !*conf->psk_query) {
2633 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
2638 * Set the callback only if we can check things.
2640 if (conf->psk_identity || conf->psk_query) {
2641 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2644 } else if (conf->psk_query) {
2645 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2650 * Now check that if PSK is being used, the config is valid.
2652 if ((conf->psk_identity && !conf->psk_password) ||
2653 (!conf->psk_identity && conf->psk_password) ||
2654 (conf->psk_identity && !*conf->psk_identity) ||
2655 (conf->psk_password && !*conf->psk_password)) {
2656 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
2660 if (conf->psk_identity) {
2661 size_t psk_len, hex_len;
2662 uint8_t buffer[PSK_MAX_PSK_LEN];
2664 if (conf->certificate_file ||
2665 conf->private_key_password || conf->private_key_file ||
2666 conf->ca_file || conf->ca_path) {
2667 ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
2672 SSL_CTX_set_psk_client_callback(ctx,
2673 psk_client_callback);
2676 psk_len = strlen(conf->psk_password);
2677 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2678 ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
2683 * Check the password now, so that we don't have
2684 * errors at run-time.
2686 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2687 if (psk_len != (2 * hex_len)) {
2688 ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
2695 (void) client; /* -Wunused */
2699 * Load our keys and certificates
2701 * If certificates are of type PEM then we can make use
2702 * of cert chain authentication using openssl api call
2703 * SSL_CTX_use_certificate_chain_file. Please see how
2704 * the cert chain needs to be given in PEM from
2707 if (!conf->certificate_file) goto load_ca;
2709 if (type == SSL_FILETYPE_PEM) {
2710 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2711 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2712 conf->certificate_file);
2716 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2717 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2718 conf->certificate_file);
2722 /* Load the CAs we trust */
2724 if (conf->ca_file || conf->ca_path) {
2725 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2726 tls_error_log(NULL, "Failed reading Trusted root CA list \"%s\"",
2731 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2733 if (conf->private_key_file) {
2734 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2735 tls_error_log(NULL, "Failed reading private key file \"%s\"",
2736 conf->private_key_file);
2741 * Check if the loaded private key is the right one
2743 if (!SSL_CTX_check_private_key(ctx)) {
2744 ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
2749 #ifdef PSK_MAX_IDENTITY_LEN
2754 * We never want SSLv2 or SSLv3.
2756 ctx_options |= SSL_OP_NO_SSLv2;
2757 ctx_options |= SSL_OP_NO_SSLv3;
2760 * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2761 * Though they can be *globally* disabled if necessary.x
2763 #ifdef SSL_OP_NO_TLSv1
2764 if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
2766 ctx_tls_versions |= SSL_OP_NO_TLSv1;
2768 #ifdef SSL_OP_NO_TLSv1_1
2769 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2771 ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
2773 #ifdef SSL_OP_NO_TLSv1_2
2775 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2777 ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
2781 if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
2782 ERROR(LOG_PREFIX ": You have disabled all available TLS versions. EAP will not work");
2786 #ifdef SSL_OP_NO_TICKET
2787 ctx_options |= SSL_OP_NO_TICKET;
2790 if (!conf->disable_single_dh_use) {
2792 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2793 * small subgroup attacks and forward secrecy. Always
2794 * using SSL_OP_SINGLE_DH_USE has an impact on the
2795 * computer time needed during negotiation, but it is not
2798 ctx_options |= SSL_OP_SINGLE_DH_USE;
2802 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2803 * in Windows Vista client.
2804 * http://www.openssl.org/~bodo/tls-cbc.txt
2805 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2807 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2809 SSL_CTX_set_options(ctx, ctx_options);
2812 * TODO: Set the RSA & DH
2813 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2814 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2818 * set the message callback to identify the type of
2819 * message. For every new session, there can be a
2820 * different callback argument.
2822 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2826 * Set eliptical curve crypto configuration.
2828 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2829 #ifndef OPENSSL_NO_ECDH
2830 if (set_ecdh_curve(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) {
2837 * OpenSSL will automatically create certificate chains,
2838 * unless we tell it to not do that. The problem is that
2839 * it sometimes gets the chains right from a certificate
2840 * signature view, but wrong from the clients view.
2842 if (!conf->auto_chain) {
2843 SSL_CTX_set_mode(ctx, SSL_MODE_NO_AUTO_CHAIN);
2846 /* Set Info callback */
2847 SSL_CTX_set_info_callback(ctx, cbtls_info);
2850 * Callbacks, etc. for session resumption.
2852 if (conf->session_cache_enable) {
2854 * Cache sessions on disk if requested.
2856 if (conf->session_cache_path) {
2857 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2858 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2859 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2862 SSL_CTX_set_quiet_shutdown(ctx, 1);
2863 if (fr_tls_ex_index_vps < 0)
2864 fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2868 * Check the certificates for revocation.
2870 #ifdef X509_V_FLAG_CRL_CHECK
2871 if (conf->check_crl) {
2872 certstore = SSL_CTX_get_cert_store(ctx);
2873 if (certstore == NULL) {
2874 tls_error_log(NULL, "Error reading Certificate Store");
2877 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2879 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2880 if (conf->check_all_crl)
2881 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
2888 * Always verify the peer certificate
2890 verify_mode |= SSL_VERIFY_PEER;
2891 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2892 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2893 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2895 if (conf->verify_depth) {
2896 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2899 /* Load randomness */
2900 if (conf->random_file) {
2901 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2902 tls_error_log(NULL, "Failed loading randomness");
2908 * Set the cipher list if we were told to
2910 if (conf->cipher_list) {
2911 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2912 tls_error_log(NULL, "Failed setting cipher list");
2918 * Setup session caching
2920 if (conf->session_cache_enable) {
2922 * Create a unique context Id per EAP-TLS configuration.
2924 if (conf->session_id_name) {
2925 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2926 "FR eap %s", conf->session_id_name);
2928 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2933 * Cache it, and DON'T auto-clear it.
2935 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2937 SSL_CTX_set_session_id_context(ctx,
2938 (unsigned char *) conf->session_context_id,
2939 (unsigned int) strlen(conf->session_context_id));
2942 * Our timeout is in hours, this is in seconds.
2944 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2947 * Set the maximum number of entries in the
2950 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2953 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2961 * Free TLS client/server config
2962 * Should not be called outside this code, as a callback is
2963 * added to automatically free the data when the CONF_SECTION
2966 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2968 if (conf->ctx) SSL_CTX_free(conf->ctx);
2970 #ifdef HAVE_OPENSSL_OCSP_H
2971 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2972 conf->ocsp_store = NULL;
2976 memset(conf, 0, sizeof(*conf));
2981 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2983 fr_tls_server_conf_t *conf;
2985 conf = talloc_zero(ctx, fr_tls_server_conf_t);
2987 ERROR(LOG_PREFIX ": Out of memory");
2991 talloc_set_destructor(conf, _tls_server_conf_free);
2996 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2998 fr_tls_server_conf_t *conf;
3001 * If cs has already been parsed there should be a cached copy
3002 * of conf already stored, so just return that.
3004 conf = cf_data_find(cs, "tls-conf");
3006 DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3010 conf = tls_server_conf_alloc(cs);
3012 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
3019 * Save people from their own stupidity.
3021 if (conf->fragment_size < 100) conf->fragment_size = 100;
3023 if (!conf->private_key_file) {
3024 ERROR(LOG_PREFIX ": TLS Server requires a private key file");
3028 if (!conf->certificate_file) {
3029 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
3036 conf->ctx = tls_init_ctx(conf, 0);
3037 if (conf->ctx == NULL) {
3041 #ifdef HAVE_OPENSSL_OCSP_H
3043 * Initialize OCSP Revocation Store
3045 if (conf->ocsp_enable) {
3046 conf->ocsp_store = init_revocation_store(conf);
3047 if (conf->ocsp_store == NULL) goto error;
3049 #endif /*HAVE_OPENSSL_OCSP_H*/
3053 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
3054 if (load_dh_params(conf->ctx, dh_file) < 0) {
3059 if (conf->verify_tmp_dir) {
3060 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
3061 ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
3062 conf->verify_tmp_dir, fr_syserror(errno));
3067 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
3068 ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
3072 #ifdef SSL_OP_NO_TLSv1_2
3074 * OpenSSL 1.0.1f and 1.0.1g get the MS-MPPE keys wrong.
3076 #if (OPENSSL_VERSION_NUMBER >= 0x10010060L) && (OPENSSL_VERSION_NUMBER < 0x10010060L)
3077 conf->disable_tlsv1_2 = true;
3078 WARN(LOG_PREFIX ": Disabling TLSv1.2 due to OpenSSL bugs");
3083 * Cache conf in cs in case we're asked to parse this again.
3085 cf_data_add(cs, "tls-conf", conf, NULL);
3090 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
3092 fr_tls_server_conf_t *conf;
3094 conf = cf_data_find(cs, "tls-conf");
3096 DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3100 conf = tls_server_conf_alloc(cs);
3102 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
3109 * Save people from their own stupidity.
3111 if (conf->fragment_size < 100) conf->fragment_size = 100;
3116 conf->ctx = tls_init_ctx(conf, 1);
3117 if (conf->ctx == NULL) {
3124 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
3125 if (load_dh_params(conf->ctx, dh_file) < 0) {
3130 cf_data_add(cs, "tls-conf", conf, NULL);
3135 int tls_success(tls_session_t *ssn, REQUEST *request)
3137 VALUE_PAIR *vp, *vps = NULL;
3138 fr_tls_server_conf_t *conf;
3139 TALLOC_CTX *talloc_ctx;
3141 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
3142 rad_assert(conf != NULL);
3144 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
3147 * If there's no session resumption, delete the entry
3148 * from the cache. This means either it's disabled
3149 * globally for this SSL context, OR we were told to
3150 * disable it for this user.
3152 * This also means you can't turn it on just for one
3155 if ((!ssn->allow_session_resumption) ||
3156 (((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
3157 (vp->vp_integer == 0))) {
3158 SSL_CTX_remove_session(ssn->ctx,
3160 ssn->allow_session_resumption = false;
3163 * If we're in a resumed session and it's
3166 if (SSL_session_reused(ssn->ssl)) {
3167 RDEBUG("Forcibly stopping session resumption as it is not allowed");
3172 * Else resumption IS allowed, so we store the
3173 * user data in the cache.
3175 } else if (!SSL_session_reused(ssn->ssl)) {
3177 char buffer[2 * MAX_SESSION_SIZE + 1];
3179 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3181 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
3182 if (vp) fr_pair_add(&vps, vp);
3184 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
3185 if (vp) fr_pair_add(&vps, vp);
3187 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
3188 if (vp) fr_pair_add(&vps, vp);
3190 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
3191 if (vp) fr_pair_add(&vps, vp);
3193 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
3194 if (vp) fr_pair_add(&vps, vp);
3196 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3199 * Hmm... the certs should probably be session data.
3203 * @todo: some go into reply, others into
3206 fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
3209 * Save the certs in the packet, so that we can see them.
3211 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3215 SSL_SESSION_set_ex_data(ssn->ssl_session, fr_tls_ex_index_vps, vps);
3216 rdebug_pair_list(L_DBG_LVL_2, request, vps, " caching ");
3218 if (conf->session_cache_path) {
3219 /* write the VPs to the cache file */
3220 char filename[256], buf[1024];
3223 RDEBUG2("Saving session %s in the disk cache", buffer);
3225 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
3226 FR_DIR_SEP, buffer);
3227 vp_file = fopen(filename, "w");
3228 if (vp_file == NULL) {
3229 RWDEBUG("Could not write session VPs to persistent cache: %s",
3230 fr_syserror(errno));
3232 VALUE_PAIR *prev = NULL;
3234 /* generate a dummy user-style entry which is easy to read back */
3235 fprintf(vp_file, "# SSL cached session\n");
3236 fprintf(vp_file, "%s\n\t", buffer);
3238 for (vp = fr_cursor_init(&cursor, &vps);
3240 vp = fr_cursor_next(&cursor)) {
3242 * Terminate the previous line.
3244 if (prev) fprintf(vp_file, ",\n\t");
3249 vp_prints(buf, sizeof(buf), vp);
3250 fputs(buf, vp_file);
3255 * Terminate the final line.
3257 fprintf(vp_file, "\n");
3261 RDEBUG("Failed to find 'persist_dir' in TLS configuration. Session will not be cached on disk.");
3264 RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
3265 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3269 * Else the session WAS allowed. Copy the cached reply.
3272 char buffer[2 * MAX_SESSION_SIZE + 1];
3274 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3277 * The "restore VPs from OpenSSL cache" code is
3278 * now in eaptls_process()
3281 if (conf->session_cache_path) {
3282 /* "touch" the cached session/vp file */
3285 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
3286 conf->session_cache_path, FR_DIR_SEP, buffer);
3287 utime(filename, NULL);
3288 snprintf(filename, sizeof(filename), "%s%c%s.vps",
3289 conf->session_cache_path, FR_DIR_SEP, buffer);
3290 utime(filename, NULL);
3294 * Mark the request as resumed.
3296 pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
3303 void tls_fail(tls_session_t *ssn)
3306 * Force the session to NOT be cached.
3308 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3311 fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
3318 * Decrypt the complete record.
3320 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
3321 ssn->dirty_in.used);
3322 if (err != (int) ssn->dirty_in.used) {
3323 record_init(&ssn->dirty_in);
3324 RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
3329 * Clear the dirty buffer now that we are done with it
3330 * and init the clean_out buffer to store decrypted data
3332 record_init(&ssn->dirty_in);
3333 record_init(&ssn->clean_out);
3336 * Read (and decrypt) the tunneled data from the
3337 * SSL session, and put it into the decrypted
3340 err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
3344 RDEBUG("SSL_read Error");
3346 code = SSL_get_error(ssn->ssl, err);
3348 case SSL_ERROR_WANT_READ:
3349 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
3350 return FR_TLS_MORE_FRAGMENTS;
3352 case SSL_ERROR_WANT_WRITE:
3353 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
3357 REDEBUG("Error in fragmentation logic");
3358 tls_error_io_log(request, ssn, err,
3359 "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)");
3365 if (err == 0) RWDEBUG("No data inside of the tunnel");
3368 * Passed all checks, successfully decrypted data
3370 ssn->clean_out.used = err;
3373 * Add the certificates to intermediate packets, so that
3374 * the inner tunnel policies can use them.
3376 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3378 if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3385 * Acknowledge received is for one of the following messages sent earlier
3386 * 1. Handshake completed Message, so now send, EAP-Success
3387 * 2. Alert Message, now send, EAP-Failure
3388 * 3. Fragment Message, now send, next Fragment
3390 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
3393 REDEBUG("Unexpected ACK received: No ongoing SSL session");
3394 return FR_TLS_INVALID;
3396 if (!ssn->info.initialized) {
3397 RDEBUG("No SSL info available. Waiting for more SSL data");
3398 return FR_TLS_REQUEST;
3401 if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3402 REDEBUG("Unexpected ACK received: We sent no previous messages");
3403 return FR_TLS_INVALID;
3406 switch (ssn->info.content_type) {
3408 RDEBUG2("Peer ACKed our alert");
3412 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3413 RDEBUG2("Peer ACKed our handshake fragment. handshake is finished");
3416 * From now on all the content is
3417 * application data set it here as nobody else
3420 ssn->info.content_type = application_data;
3421 return FR_TLS_SUCCESS;
3422 } /* else more data to send */
3424 RDEBUG2("Peer ACKed our handshake fragment");
3425 /* Fragmentation handler, send next fragment */
3426 return FR_TLS_REQUEST;
3428 case application_data:
3429 RDEBUG2("Peer ACKed our application data fragment");
3430 return FR_TLS_REQUEST;
3433 * For the rest of the conditions, switch over
3434 * to the default section below.
3437 REDEBUG("Invalid ACK received: %d", ssn->info.content_type);
3438 return FR_TLS_INVALID;
3441 #endif /* WITH_TLS */