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 (newest first)*/
72 static libssl_defect_t libssl_defects[] =
75 .low = 0x010001000, /* 1.0.1 */
76 .high = 0x01000106f, /* 1.0.1f */
77 .id = "CVE-2014-0160",
79 .comment = "For more information see http://heartbleed.com"
82 #endif /* ENABLE_OPENSSL_VERSION_CHECK */
84 FR_NAME_NUMBER const fr_tls_status_table[] = {
85 { "invalid", FR_TLS_INVALID },
86 { "request", FR_TLS_REQUEST },
87 { "response", FR_TLS_RESPONSE },
88 { "success", FR_TLS_SUCCESS },
89 { "fail", FR_TLS_FAIL },
90 { "noop", FR_TLS_NOOP },
92 { "start", FR_TLS_START },
94 { "ack", FR_TLS_ACK },
95 { "first fragment", FR_TLS_FIRST_FRAGMENT },
96 { "more fragments", FR_TLS_MORE_FRAGMENTS },
97 { "length included", FR_TLS_LENGTH_INCLUDED },
98 { "more fragments with length", FR_TLS_MORE_FRAGMENTS_WITH_LENGTH },
99 { "handled", FR_TLS_HANDLED },
103 /* index we use to store cached session VPs
104 * needs to be dynamic so we can supply a "free" function
106 int fr_tls_ex_index_vps = -1;
107 int fr_tls_ex_index_certs = -1;
110 static void session_close(tls_session_t *ssn);
111 static void session_init(tls_session_t *ssn);
114 static void record_init(record_t *buf);
115 static void record_close(record_t *buf);
116 static unsigned int record_plus(record_t *buf, void const *ptr,
118 static unsigned int record_minus(record_t *buf, void *ptr,
121 #ifdef PSK_MAX_IDENTITY_LEN
122 static bool identity_is_safe(const char *identity)
126 if (!identity) return true;
128 while ((c = *(identity++)) != '\0') {
129 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
130 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
140 DIAG_OFF(format-nonliteral)
141 /** Print errors in the TLS thread local error stack
143 * Drains the thread local OpenSSL error queue, and prints out errors.
145 * @param[in] request The current request (may be NULL).
146 * @param[in] msg Error message describing the operation being attempted.
147 * @param[in] ap Arguments for msg.
148 * @return the number of errors drained from the stack.
150 static int tls_verror_log(REQUEST *request, char const *msg, va_list ap)
161 * Pop the first error, so ERR_peek_error()
162 * can be used to determine if there are
165 error = ERR_get_error_line(&file, &line);
168 p = talloc_vasprintf(request, msg, ap);
171 * Single line mode (there's only one error)
173 if (error && !ERR_peek_error()) {
174 ERR_error_string_n(error, buffer, sizeof(buffer));
177 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
178 ROPTIONAL(REDEBUG, ERROR, "%s: %s[%i]:%s", p, file, line, buffer);
180 ROPTIONAL(REDEBUG, ERROR, "%s: %s", p, buffer);
189 * Print the error we were given, irrespective
190 * of whether there were any OpenSSL errors.
192 ROPTIONAL(RERROR, ERROR, "%s", p);
197 * Stack mode (there are multiple errors)
199 if (!error) return 0;
201 ERR_error_string_n(error, buffer, sizeof(buffer));
203 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
204 ROPTIONAL(REDEBUG, ERROR, "%s[%i]:%s", file, line, buffer);
206 ROPTIONAL(REDEBUG, ERROR, "%s", buffer);
209 } while ((error = ERR_get_error_line(&file, &line)));
213 DIAG_ON(format-nonliteral)
215 /** Print errors in the TLS thread local error stack
217 * Drains the thread local OpenSSL error queue, and prints out errors.
219 * @param[in] request The current request (may be NULL).
220 * @param[in] msg Error message describing the operation being attempted.
221 * @param[in] ... Arguments for msg.
222 * @return the number of errors drained from the stack.
224 int tls_error_log(REQUEST *request, char const *msg, ...)
230 ret = tls_verror_log(request, msg, ap);
236 /** Print errors raised by OpenSSL I/O functions
238 * Drains the thread local OpenSSL error queue, and prints out errors
239 * based on the SSL handle and the return code of the I/O function.
241 * OpenSSL lists I/O functions to be:
249 * @param request The current request (may be NULL).
250 * @param session The current tls_session.
251 * @param ret from the I/O operation.
252 * @param msg Error message describing the operation being attempted.
253 * @param ... Arguments for msg.
255 * - 0 TLS session cannot continue.
256 * - 1 TLS session may still be viable.
258 int tls_error_io_log(REQUEST *request, tls_session_t *session, int ret, char const *msg, ...)
263 if (ERR_peek_error()) {
265 tls_verror_log(request, msg, ap);
269 error = SSL_get_error(session->ssl, ret);
272 * These seem to be harmless and already "dealt
273 * with" by our non-blocking environment. NB:
274 * "ZERO_RETURN" is the clean "error"
275 * indicating a successfully closed SSL
276 * tunnel. We let this happen because our IO
277 * loop should not appear to have broken on
278 * this condition - and outside the IO loop, the
279 * "shutdown" state is checked.
281 * Don't print anything if we ignore the error.
284 case SSL_ERROR_WANT_READ:
285 case SSL_ERROR_WANT_WRITE:
286 case SSL_ERROR_WANT_X509_LOOKUP:
287 case SSL_ERROR_ZERO_RETURN:
291 * These seem to be indications of a genuine
292 * error that should result in the SSL tunnel
293 * being regarded as "dead".
295 case SSL_ERROR_SYSCALL:
296 ROPTIONAL(REDEBUG, ERROR, "System call (I/O) error (%i)", ret);
300 ROPTIONAL(REDEBUG, ERROR, "TLS protocol error (%i)", ret);
304 * For any other errors that (a) exist, and (b)
305 * crop up - we need to interpret what to do with
306 * them - so "politely inform" the caller that
307 * the code needs updating here.
310 ROPTIONAL(REDEBUG, ERROR, "TLS session error %i (%i)", error, ret);
318 * When a client uses TLS-PSK to talk to a server, this callback
319 * is used by the server to determine the PSK to use.
321 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
323 unsigned int max_psk_len)
325 unsigned int psk_len = 0;
326 fr_tls_server_conf_t *conf;
329 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
330 FR_TLS_EX_INDEX_CONF);
333 request = (REQUEST *)SSL_get_ex_data(ssl,
334 FR_TLS_EX_INDEX_REQUEST);
335 if (request && conf->psk_query) {
338 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
341 * The passed identity is weird. Deny it.
343 if (!identity_is_safe(identity)) {
344 RWDEBUG("Invalid characters in PSK identity %s", identity);
348 vp = pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
351 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
354 RWDEBUG("PSK expansion returned an empty string.");
359 * The returned key is truncated at MORE than
360 * OpenSSL can handle. That way we can detect
361 * the truncation, and complain about it.
363 if (hex_len > (2 * max_psk_len)) {
364 RWDEBUG("Returned PSK is too long (%u > %u)",
365 (unsigned int) hex_len, 2 * max_psk_len);
370 * Leave the TLS-PSK-Identity in the request, and
371 * convert the expansion from printable string
374 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
377 if (!conf->psk_identity) {
378 DEBUG("No static PSK identity set. Rejecting the user");
383 * No REQUEST, or no dynamic query. Just look for a
386 if (strcmp(identity, conf->psk_identity) != 0) {
387 ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
392 psk_len = strlen(conf->psk_password);
393 if (psk_len > (2 * max_psk_len)) return 0;
395 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
398 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
399 char *identity, unsigned int max_identity_len,
400 unsigned char *psk, unsigned int max_psk_len)
402 unsigned int psk_len;
403 fr_tls_server_conf_t *conf;
405 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
406 FR_TLS_EX_INDEX_CONF);
409 psk_len = strlen(conf->psk_password);
410 if (psk_len > (2 * max_psk_len)) return 0;
412 strlcpy(identity, conf->psk_identity, max_identity_len);
414 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
419 #define MAX_SESSION_SIZE (256)
422 void tls_session_id(SSL_SESSION *ssn, char *buffer, size_t bufsize)
424 #if OPENSSL_VERSION_NUMBER < 0x10001000L
427 size = ssn->session_id_length;
428 if (size > bufsize) size = bufsize;
430 fr_bin2hex(buffer, ssn->session_id, size);
435 p = SSL_SESSION_get_id(ssn, &size);
436 if (size > bufsize) size = bufsize;
438 fr_bin2hex(buffer, p, size);
445 static int _tls_session_free(tls_session_t *ssn)
448 * Free any opaque TTLS or PEAP data.
450 if ((ssn->opaque) && (ssn->free_opaque)) {
451 ssn->free_opaque(ssn->opaque);
460 tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
464 tls_session_t *ssn = NULL;
467 ssn = talloc_zero(ctx, tls_session_t);
468 if (!ssn) return NULL;
470 talloc_set_destructor(ssn, _tls_session_free);
472 ssn->ctx = conf->ctx;
474 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
476 ssn->ssl = SSL_new(ssn->ctx);
482 request = request_alloc(ssn);
483 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
486 * Add the message callback to identify what type of
487 * message/handshake is passed
489 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
490 SSL_set_msg_callback_arg(ssn->ssl, ssn);
491 SSL_set_info_callback(ssn->ssl, cbtls_info);
494 * Always verify the peer certificate.
496 DEBUG2("Requiring Server certificate");
497 verify_mode = SSL_VERIFY_PEER;
498 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
499 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
501 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
502 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
503 SSL_set_fd(ssn->ssl, fd);
504 ret = SSL_connect(ssn->ssl);
506 tls_error_io_log(NULL, ssn, ret, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_connect)");
512 ssn->mtu = conf->fragment_size;
518 /** Create a new TLS session
520 * Configures a new TLS session, configuring options, setting callbacks etc...
522 * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
523 * session is tied to another talloc'd object.
524 * @param conf to use to configure the tls session.
525 * @param request The current #REQUEST.
526 * @param client_cert Whether to require a client_cert.
527 * @return a new session on success, or NULL on error.
529 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
531 tls_session_t *state = NULL;
536 rad_assert(request != NULL);
538 RDEBUG2("Initiating new EAP-TLS session");
541 * Manually flush the sessions every so often. If HALF
542 * of the session lifetime has passed since we last
543 * flushed, then flush it again.
545 * FIXME: Also do it every N sessions?
547 if (conf->session_cache_enable &&
548 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
549 RDEBUG2("Flushing SSL sessions (of #%ld)", SSL_CTX_sess_number(conf->ctx));
551 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
552 conf->session_last_flushed = request->timestamp;
555 new_tls = SSL_new(conf->ctx);
556 if (new_tls == NULL) {
557 tls_error_log(request, "Error creating new TLS session");
561 /* We use the SSL's "app_data" to indicate a call-back */
562 SSL_set_app_data(new_tls, NULL);
564 if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
565 RERROR("Error allocating memory for SSL state");
569 talloc_set_destructor(state, _tls_session_free);
571 state->ctx = conf->ctx;
572 state->ssl = new_tls;
575 * Initialize callbacks
577 state->record_init = record_init;
578 state->record_close = record_close;
579 state->record_plus = record_plus;
580 state->record_minus = record_minus;
583 * Create & hook the BIOs to handle the dirty side of the
584 * SSL. This is *very important* as we want to handle
585 * the transmission part. Now the only IO interface
586 * that SSL is aware of, is our defined BIO buffers.
588 * This means that all SSL IO is done to/from memory,
589 * and we can update those BIOs from the packets we've
592 state->into_ssl = BIO_new(BIO_s_mem());
593 state->from_ssl = BIO_new(BIO_s_mem());
594 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
597 * Add the message callback to identify what type of
598 * message/handshake is passed
600 SSL_set_msg_callback(new_tls, cbtls_msg);
601 SSL_set_msg_callback_arg(new_tls, state);
602 SSL_set_info_callback(new_tls, cbtls_info);
605 * In Server mode we only accept.
607 SSL_set_accept_state(state->ssl);
610 * Verify the peer certificate, if asked.
613 RDEBUG2("Setting verify mode to require certificate from client");
614 verify_mode = SSL_VERIFY_PEER;
615 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
616 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
618 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
620 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
621 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
622 state->length_flag = conf->include_length;
625 * We use default fragment size, unless the Framed-MTU
626 * tells us it's too big. Note that we do NOT account
627 * for the EAP-TLS headers if conf->fragment_size is
628 * large, because that config item looks to be confusing.
630 * i.e. it should REALLY be called MTU, and the code here
631 * should figure out what that means for TLS fragment size.
632 * asking the administrator to know the internal details
633 * of EAP-TLS in order to calculate fragment sizes is
636 state->mtu = conf->fragment_size;
637 vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
638 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->mtu)) {
639 state->mtu = vp->vp_integer;
642 if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
648 * We are the server, we always get the dirty data
649 * (Handshake data is also considered as dirty data)
650 * During handshake, since SSL API handles itself,
651 * After clean-up, dirty_out will be filled with
652 * the data required for handshaking. So we check
653 * if dirty_out is empty then we simply send it back.
654 * As of now, if handshake is successful, then we keep going,
657 * Fill the Bio with the dirty data to clean it
658 * Get the cleaned data from SSL, if it is not Handshake data
660 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
664 if (ssn->invalid_hb_used) return 0;
666 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
667 if (err != (int) ssn->dirty_in.used) {
668 REDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
669 record_init(&ssn->dirty_in);
672 record_init(&ssn->dirty_in);
674 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
675 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
677 ssn->clean_out.used += err;
681 if (!tls_error_io_log(request, ssn, err, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)")) return 0;
683 /* Some Extra STATE information for easy debugging */
684 if (SSL_is_init_finished(ssn->ssl)) RDEBUG2("SSL Connection Established");
685 if (SSL_in_init(ssn->ssl)) RDEBUG2("In SSL Handshake Phase");
686 if (SSL_in_before(ssn->ssl)) RDEBUG2("Before SSL Handshake Phase");
687 if (SSL_in_accept_init(ssn->ssl)) RDEBUG2("In SSL Accept mode");
688 if (SSL_in_connect_init(ssn->ssl)) RDEBUG2("In SSL Connect mode");
690 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
692 * Cache the SSL_SESSION pointer.
694 if (!ssn->ssl_session && SSL_is_init_finished(ssn->ssl)) {
695 ssn->ssl_session = SSL_get_session(ssn->ssl);
696 if (!ssn->ssl_session) {
697 RDEBUG("Failed getting SSL session");
703 err = BIO_ctrl_pending(ssn->from_ssl);
705 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
706 sizeof(ssn->dirty_out.data));
708 ssn->dirty_out.used = err;
710 } else if (BIO_should_retry(ssn->from_ssl)) {
711 record_init(&ssn->dirty_in);
712 RDEBUG2("Asking for more data in tunnel");
716 tls_error_log(NULL, NULL);
717 record_init(&ssn->dirty_in);
721 RDEBUG2("SSL Application Data");
722 /* Its clean application data, do whatever we want */
723 record_init(&ssn->clean_out);
726 /* We are done with dirty_in, reinitialize it */
727 record_init(&ssn->dirty_in);
732 * Take cleartext user data, and encrypt it into the output buffer,
733 * to send to the client at the other end of the SSL connection.
735 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
740 * If there's un-encrypted data in 'clean_in', then write
741 * that data to the SSL session, and then call the BIO function
742 * to get that encrypted data from the SSL session, into
743 * a buffer which we can then package into an EAP packet.
745 * Based on Server's logic this clean_in is expected to
746 * contain the data to send to the client.
748 if (ssn->clean_in.used > 0) {
751 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
752 record_minus(&ssn->clean_in, NULL, written);
754 /* Get the dirty data from Bio to send it */
755 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
756 sizeof(ssn->dirty_out.data));
758 ssn->dirty_out.used = err;
760 if (!tls_error_io_log(request, ssn, err,
761 "Failed in " STRINGIFY(__FUNCTION__) " (SSL_write)")) {
770 static void session_init(tls_session_t *ssn)
773 ssn->into_ssl = ssn->from_ssl = NULL;
774 record_init(&ssn->clean_in);
775 record_init(&ssn->clean_out);
776 record_init(&ssn->dirty_in);
777 record_init(&ssn->dirty_out);
779 memset(&ssn->info, 0, sizeof(ssn->info));
782 ssn->fragment = false;
783 ssn->tls_msg_len = 0;
784 ssn->length_flag = false;
786 ssn->free_opaque = NULL;
789 static void session_close(tls_session_t *ssn)
791 SSL_set_quiet_shutdown(ssn->ssl, 1);
792 SSL_shutdown(ssn->ssl);
799 record_close(&ssn->clean_in);
800 record_close(&ssn->clean_out);
801 record_close(&ssn->dirty_in);
802 record_close(&ssn->dirty_out);
806 static void record_init(record_t *rec)
811 static void record_close(record_t *rec)
818 * Copy data to the intermediate buffer, before we send
821 static unsigned int record_plus(record_t *rec, void const *ptr,
824 unsigned int added = MAX_RECORD_SIZE - rec->used;
830 memcpy(rec->data + rec->used, ptr, added);
836 * Take data from the buffer, and give it to the caller.
838 static unsigned int record_minus(record_t *rec, void *ptr,
841 unsigned int taken = rec->used;
848 memcpy(ptr, rec->data, taken);
852 * This is pretty bad...
854 if (rec->used > 0) memmove(rec->data, rec->data + taken, rec->used);
859 void tls_session_information(tls_session_t *tls_session)
861 char const *str_write_p, *str_version, *str_content_type = "";
862 char const *str_details1 = "", *str_details2= "";
867 * Don't print this out in the normal course of
870 if (rad_debug_lvl == 0) return;
872 str_write_p = tls_session->info.origin ? ">>> send" : "<<< recv";
874 switch (tls_session->info.version) {
876 str_version = "SSL 2.0 ";
879 str_version = "SSL 3.0 ";
882 str_version = "TLS 1.0 ";
884 #ifdef TLS1_1_VERSION
886 str_version = "TLS 1.1 ";
889 #ifdef TLS1_2_VERSION
891 str_version = "TLS 1.2 ";
896 str_version = "TLS 1.3 ";
901 sprintf(buffer, "UNKNOWN TLS VERSION ?%04X?", tls_session->info.version);
902 str_version = buffer;
906 if (tls_session->info.version == SSL3_VERSION ||
907 tls_session->info.version == TLS1_VERSION) {
908 switch (tls_session->info.content_type) {
909 case SSL3_RT_CHANGE_CIPHER_SPEC:
910 str_content_type = "ChangeCipherSpec";
914 str_content_type = "Alert";
917 case SSL3_RT_HANDSHAKE:
918 str_content_type = "Handshake";
921 case SSL3_RT_APPLICATION_DATA:
922 str_content_type = "ApplicationData";
926 str_content_type = "UnknownContentType";
930 if (tls_session->info.content_type == SSL3_RT_ALERT) {
931 str_details1 = ", ???";
933 if (tls_session->info.record_len == 2) {
935 switch (tls_session->info.alert_level) {
936 case SSL3_AL_WARNING:
937 str_details1 = ", warning";
940 str_details1 = ", fatal";
944 str_details2 = " ???";
945 switch (tls_session->info.alert_description) {
946 case SSL3_AD_CLOSE_NOTIFY:
947 str_details2 = " close_notify";
950 case SSL3_AD_UNEXPECTED_MESSAGE:
951 str_details2 = " unexpected_message";
954 case SSL3_AD_BAD_RECORD_MAC:
955 str_details2 = " bad_record_mac";
958 case TLS1_AD_DECRYPTION_FAILED:
959 str_details2 = " decryption_failed";
962 case TLS1_AD_RECORD_OVERFLOW:
963 str_details2 = " record_overflow";
966 case SSL3_AD_DECOMPRESSION_FAILURE:
967 str_details2 = " decompression_failure";
970 case SSL3_AD_HANDSHAKE_FAILURE:
971 str_details2 = " handshake_failure";
974 case SSL3_AD_BAD_CERTIFICATE:
975 str_details2 = " bad_certificate";
978 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
979 str_details2 = " unsupported_certificate";
982 case SSL3_AD_CERTIFICATE_REVOKED:
983 str_details2 = " certificate_revoked";
986 case SSL3_AD_CERTIFICATE_EXPIRED:
987 str_details2 = " certificate_expired";
990 case SSL3_AD_CERTIFICATE_UNKNOWN:
991 str_details2 = " certificate_unknown";
994 case SSL3_AD_ILLEGAL_PARAMETER:
995 str_details2 = " illegal_parameter";
998 case TLS1_AD_UNKNOWN_CA:
999 str_details2 = " unknown_ca";
1002 case TLS1_AD_ACCESS_DENIED:
1003 str_details2 = " access_denied";
1006 case TLS1_AD_DECODE_ERROR:
1007 str_details2 = " decode_error";
1010 case TLS1_AD_DECRYPT_ERROR:
1011 str_details2 = " decrypt_error";
1014 case TLS1_AD_EXPORT_RESTRICTION:
1015 str_details2 = " export_restriction";
1018 case TLS1_AD_PROTOCOL_VERSION:
1019 str_details2 = " protocol_version";
1022 case TLS1_AD_INSUFFICIENT_SECURITY:
1023 str_details2 = " insufficient_security";
1026 case TLS1_AD_INTERNAL_ERROR:
1027 str_details2 = " internal_error";
1030 case TLS1_AD_USER_CANCELLED:
1031 str_details2 = " user_canceled";
1034 case TLS1_AD_NO_RENEGOTIATION:
1035 str_details2 = " no_renegotiation";
1041 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
1042 str_details1 = "???";
1044 if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
1045 case SSL3_MT_HELLO_REQUEST:
1046 str_details1 = ", HelloRequest";
1049 case SSL3_MT_CLIENT_HELLO:
1050 str_details1 = ", ClientHello";
1053 case SSL3_MT_SERVER_HELLO:
1054 str_details1 = ", ServerHello";
1057 case SSL3_MT_CERTIFICATE:
1058 str_details1 = ", Certificate";
1061 case SSL3_MT_SERVER_KEY_EXCHANGE:
1062 str_details1 = ", ServerKeyExchange";
1065 case SSL3_MT_CERTIFICATE_REQUEST:
1066 str_details1 = ", CertificateRequest";
1069 case SSL3_MT_SERVER_DONE:
1070 str_details1 = ", ServerHelloDone";
1073 case SSL3_MT_CERTIFICATE_VERIFY:
1074 str_details1 = ", CertificateVerify";
1077 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1078 str_details1 = ", ClientKeyExchange";
1081 case SSL3_MT_FINISHED:
1082 str_details1 = ", Finished";
1088 snprintf(tls_session->info.info_description,
1089 sizeof(tls_session->info.info_description),
1090 "%s %s%s [length %04lx]%s%s\n",
1091 str_write_p, str_version, str_content_type,
1092 (unsigned long)tls_session->info.record_len,
1093 str_details1, str_details2);
1095 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
1096 ROPTIONAL(RDEBUG2, DEBUG2, "%s", tls_session->info.info_description);
1099 static CONF_PARSER cache_config[] = {
1100 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
1102 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
1103 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
1105 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
1106 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
1107 CONF_PARSER_TERMINATOR
1110 static CONF_PARSER verify_config[] = {
1111 { "skip_if_ocsp_ok", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, verify_skip_if_ocsp_ok), "no" },
1112 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
1113 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
1114 CONF_PARSER_TERMINATOR
1117 #ifdef HAVE_OPENSSL_OCSP_H
1118 static CONF_PARSER ocsp_config[] = {
1119 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
1120 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
1121 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
1122 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
1123 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
1124 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
1125 CONF_PARSER_TERMINATOR
1129 static CONF_PARSER tls_server_config[] = {
1130 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1131 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
1132 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1133 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1134 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1135 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1136 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
1137 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1138 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1139 #ifdef PSK_MAX_IDENTITY_LEN
1140 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
1141 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
1142 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
1144 { "dh_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, dh_file), NULL },
1145 { "random_file", FR_CONF_OFFSET(PW_TYPE_FILE_EXISTS, fr_tls_server_conf_t, random_file), NULL },
1146 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1147 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1148 { "auto_chain", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, auto_chain), "yes" },
1149 { "disable_single_dh_use", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_single_dh_use), NULL },
1150 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1151 #ifdef X509_V_FLAG_CRL_CHECK_ALL
1152 { "check_all_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), "no" },
1154 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
1155 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1156 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1157 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1158 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
1160 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1161 #ifndef OPENSSL_NO_ECDH
1162 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1166 #ifdef SSL_OP_NO_TLSv1
1167 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1170 #ifdef SSL_OP_NO_TLSv1_1
1171 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1174 #ifdef SSL_OP_NO_TLSv1_2
1175 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1178 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
1180 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
1182 #ifdef HAVE_OPENSSL_OCSP_H
1183 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
1185 CONF_PARSER_TERMINATOR
1189 static CONF_PARSER tls_client_config[] = {
1190 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1191 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1192 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1193 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1194 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1195 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1196 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1197 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1198 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1199 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1200 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1201 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1202 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1203 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1204 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1206 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1207 #ifndef OPENSSL_NO_ECDH
1208 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1212 #ifdef SSL_OP_NO_TLSv1
1213 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1216 #ifdef SSL_OP_NO_TLSv1_1
1217 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1220 #ifdef SSL_OP_NO_TLSv1_2
1221 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1223 CONF_PARSER_TERMINATOR
1228 * TODO: Check for the type of key exchange * like conf->dh_key
1230 static int load_dh_params(SSL_CTX *ctx, char *file)
1235 if (!file) return 0;
1237 if ((bio = BIO_new_file(file, "r")) == NULL) {
1238 ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
1242 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1245 WARN(LOG_PREFIX ": Unable to set DH parameters. DH cipher suites may not work!");
1246 WARN(LOG_PREFIX ": Fix this by running the OpenSSL command listed in eap.conf");
1250 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1251 ERROR(LOG_PREFIX ": Unable to set DH parameters");
1262 * Print debugging messages, and free data.
1264 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1266 char buffer[2 * MAX_SESSION_SIZE + 1];
1267 fr_tls_server_conf_t *conf;
1269 tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1271 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1273 DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
1281 DEBUG2(LOG_PREFIX ": Removing session %s from the cache", buffer);
1283 /* remove session and any cached VPs */
1284 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1285 conf->session_cache_path, FR_DIR_SEP, buffer);
1286 rv = unlink(filename);
1288 DEBUG2(LOG_PREFIX ": Could not remove persisted session file %s: %s",
1289 filename, fr_syserror(errno));
1291 /* VPs might be absent; might not have been written to disk yet */
1292 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1293 conf->session_cache_path, FR_DIR_SEP, buffer);
1300 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1302 char buffer[2 * MAX_SESSION_SIZE + 1];
1303 fr_tls_server_conf_t *conf;
1304 unsigned char *sess_blob = NULL;
1306 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1308 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1310 RWDEBUG("Failed to find TLS configuration in session");
1314 tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1317 int fd, rv, todo, blob_len;
1321 RDEBUG2("Serialising session %s, and storing in cache", buffer);
1323 /* find out what length data we need */
1324 blob_len = i2d_SSL_SESSION(sess, NULL);
1326 /* something went wrong */
1327 RWDEBUG("Session serialisation failed, couldn't determine required buffer length");
1332 /* Do not convert to TALLOC - Thread safety */
1333 /* alloc and convert to ASN.1 */
1334 sess_blob = malloc(blob_len);
1336 RWDEBUG("Session serialisation failed, couldn't allocate buffer (%d bytes)", blob_len);
1339 /* openssl mutates &p */
1341 rv = i2d_SSL_SESSION(sess, &p);
1342 if (rv != blob_len) {
1343 RWDEBUG("Session serialisation failed");
1347 /* open output file */
1348 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1349 conf->session_cache_path, FR_DIR_SEP, buffer);
1350 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1352 RERROR("Session serialisation failed, failed opening session file %s: %s",
1353 filename, fr_syserror(errno));
1360 rv = write(fd, p, todo);
1362 RWDEBUG("Failed writing session: %s", fr_syserror(errno));
1370 RWDEBUG("Wrote session %s to %s (%d bytes)", buffer, filename, blob_len);
1379 static SSL_SESSION *cbtls_get_session(SSL *ssl, unsigned char *data, int len, int *copy)
1382 char buffer[2 * MAX_SESSION_SIZE + 1];
1383 fr_tls_server_conf_t *conf;
1384 TALLOC_CTX *talloc_ctx;
1386 SSL_SESSION *sess = NULL;
1387 unsigned char *sess_data = NULL;
1388 PAIR_LIST *pairlist = NULL;
1390 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1392 rad_assert(request != NULL);
1395 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1397 fr_bin2hex(buffer, data, size);
1399 RDEBUG2("Peer requested cached session: %s", buffer);
1403 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1405 RWDEBUG("Failed to find TLS configuration in session");
1409 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1415 unsigned char const **o;
1420 VALUE_PAIR *vps = NULL;
1422 /* read in the cached VPs from the .vps file */
1423 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1424 conf->session_cache_path, FR_DIR_SEP, buffer);
1425 rv = pairlist_read(talloc_ctx, filename, &pairlist, 1);
1427 /* not safe to un-persist a session w/o VPs */
1428 RWDEBUG("Failed loading persisted VPs for session %s", buffer);
1432 /* load the actual SSL session */
1433 snprintf(filename, sizeof(filename), "%s%c%s.asn1", conf->session_cache_path, FR_DIR_SEP, buffer);
1434 fd = open(filename, O_RDONLY);
1436 RWDEBUG("No persisted session file %s: %s", filename, fr_syserror(errno));
1440 rv = fstat(fd, &st);
1442 RWDEBUG("Failed stating persisted session file %s: %s", filename, fr_syserror(errno));
1447 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1449 RWDEBUG("Failed allocating buffer for persisted session (%d bytes)", (int) st.st_size);
1457 rv = read(fd, q, todo);
1459 RWDEBUG("Failed reading persisted session: %s", fr_syserror(errno));
1469 * OpenSSL mutates what's passed in, so we assign sess_data to q,
1470 * so the value of q gets mutated, and not the value of sess_data.
1472 * We then need a pointer to hold &q, but it can't be const, because
1473 * clang complains about lack of consting in nested pointer types.
1475 * So we memcpy the value of that pointer, to one that
1476 * does have a const, which we then pass into d2i_SSL_SESSION *sigh*.
1480 memcpy(&o, &p, sizeof(o));
1481 sess = d2i_SSL_SESSION(NULL, o, st.st_size);
1483 RWDEBUG("Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1487 /* move the cached VPs into the session */
1488 fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &pairlist->reply, 0, 0, TAG_ANY);
1490 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
1491 RWDEBUG("Successfully restored session %s", buffer);
1492 rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
1495 if (sess_data) talloc_free(sess_data);
1496 if (pairlist) pairlist_free(&pairlist);
1501 #ifdef HAVE_OPENSSL_OCSP_H
1503 /** Extract components of OCSP responser URL from a certificate
1505 * @param[in] cert to extract URL from.
1506 * @param[out] host_out Portion of the URL (must be freed with free()).
1507 * @param[out] port_out Port portion of the URL (must be freed with free()).
1508 * @param[out] path_out Path portion of the URL (must be freed with free()).
1509 * @param[out] is_https Whether the responder should be contacted using https.
1511 * - 0 if no valid URL is contained in the certificate.
1512 * - 1 if a URL was found and parsed.
1513 * - -1 if at least one URL was found, but none could be parsed.
1515 static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out,
1516 char **path_out, int *is_https)
1519 bool found_uri = false;
1521 AUTHORITY_INFO_ACCESS *aia;
1522 ACCESS_DESCRIPTION *ad;
1524 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1526 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1527 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1528 if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
1529 if (ad->location->type != GEN_URI) continue;
1532 if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
1533 port_out, path_out, is_https)) return 1;
1535 return found_uri ? -1 : 0;
1539 * This function sends a OCSP request to a defined OCSP responder
1540 * and checks the OCSP response for correctness.
1543 /* Maximum leeway in validity period: default 5 minutes */
1544 #define MAX_VALIDITY_PERIOD (5 * 60)
1547 OCSP_STATUS_FAILED = 0,
1549 OCSP_STATUS_SKIPPED = 2,
1552 static ocsp_status_t ocsp_check(REQUEST *request, X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1553 fr_tls_server_conf_t *conf)
1555 OCSP_CERTID *certid;
1557 OCSP_RESPONSE *resp = NULL;
1558 OCSP_BASICRESP *bresp = NULL;
1562 char hostheader[1024];
1564 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1565 BIO *cbio, *bio_out;
1566 ocsp_status_t ocsp_status = OCSP_STATUS_FAILED;
1568 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1570 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1574 struct timeval when;
1579 * Create OCSP Request
1581 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1582 req = OCSP_REQUEST_new();
1583 OCSP_request_add0_id(req, certid);
1584 if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
1587 * Send OCSP Request and get OCSP Response
1590 /* Get OCSP responder URL */
1591 if (conf->ocsp_override_url) {
1595 memcpy(&url, &conf->ocsp_url, sizeof(url));
1596 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1597 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1598 if (!host || !port || !path) {
1599 RWDEBUG("ocsp: Host or port or path missing from configured URL \"%s\". Not doing OCSP", url);
1605 ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1608 RWDEBUG("ocsp: Invalid URL in certificate. Not doing OCSP");
1612 if (conf->ocsp_url) {
1613 RWDEBUG("ocsp: No OCSP URL in certificate, falling back to configured URL");
1616 RWDEBUG("ocsp: No OCSP URL in certificate. Not doing OCSP");
1624 RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
1626 /* Check host and port length are sane, then create Host: HTTP header */
1627 if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1628 RWDEBUG("ocsp: Host and port too long");
1631 snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1633 /* Setup BIO socket to OCSP responder */
1634 cbio = BIO_new_connect(host);
1637 if (rad_debug_lvl) {
1638 if (default_log.dst == L_DST_STDOUT) {
1639 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1640 } else if (default_log.dst == L_DST_STDERR) {
1641 bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1645 BIO_set_conn_port(cbio, port);
1646 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1647 BIO_do_connect(cbio);
1649 /* Send OCSP request and wait for response */
1650 resp = OCSP_sendreq_bio(cbio, path, req);
1652 REDEBUG("ocsp: Couldn't get OCSP response");
1653 ocsp_status = OCSP_STATUS_SKIPPED;
1657 if (conf->ocsp_timeout)
1658 BIO_set_nbio(cbio, 1);
1660 rc = BIO_do_connect(cbio);
1661 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1662 REDEBUG("ocsp: Couldn't connect to OCSP responder");
1663 ocsp_status = OCSP_STATUS_SKIPPED;
1667 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1669 REDEBUG("ocsp: Couldn't create OCSP request");
1670 ocsp_status = OCSP_STATUS_SKIPPED;
1674 if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1675 REDEBUG("ocsp: Couldn't set Host header");
1676 ocsp_status = OCSP_STATUS_SKIPPED;
1680 if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1681 REDEBUG("ocsp: Couldn't add data to OCSP request");
1682 ocsp_status = OCSP_STATUS_SKIPPED;
1686 gettimeofday(&when, NULL);
1687 when.tv_sec += conf->ocsp_timeout;
1690 rc = OCSP_sendreq_nbio(&resp, ctx);
1691 if (conf->ocsp_timeout) {
1692 gettimeofday(&now, NULL);
1693 if (!timercmp(&now, &when, <))
1696 } while ((rc == -1) && BIO_should_retry(cbio));
1698 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1699 REDEBUG("ocsp: Response timed out");
1700 ocsp_status = OCSP_STATUS_SKIPPED;
1704 OCSP_REQ_CTX_free(ctx);
1707 REDEBUG("ocsp: Couldn't get OCSP response");
1708 ocsp_status = OCSP_STATUS_SKIPPED;
1713 /* Verify OCSP response status */
1714 status = OCSP_response_status(resp);
1715 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1716 REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
1719 bresp = OCSP_response_get1_basic(resp);
1720 if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1721 REDEBUG("ocsp: Response has wrong nonce value");
1724 if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1725 REDEBUG("ocsp: Couldn't verify OCSP basic response");
1729 /* Verify OCSP cert status */
1730 if (!OCSP_resp_find_status(bresp, certid, &status, &reason, &rev, &thisupd, &nextupd)) {
1731 REDEBUG("ocsp: No Status found");
1735 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1737 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1738 ERR_print_errors(bio_out);
1744 BIO_puts(bio_out, "\tThis Update: ");
1745 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1746 BIO_puts(bio_out, "\n");
1748 BIO_puts(bio_out, "\tNext Update: ");
1749 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1750 BIO_puts(bio_out, "\n");
1755 case V_OCSP_CERTSTATUS_GOOD:
1756 RDEBUG2("ocsp: Cert status: good");
1757 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1758 vp->vp_integer = 1; /* yes */
1759 ocsp_status = OCSP_STATUS_OK;
1763 /* REVOKED / UNKNOWN */
1764 REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
1765 if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
1768 BIO_puts(bio_out, "\tRevocation Time: ");
1769 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1770 BIO_puts(bio_out, "\n");
1776 /* Free OCSP Stuff */
1777 OCSP_REQUEST_free(req);
1778 OCSP_RESPONSE_free(resp);
1783 if (bio_out) BIO_free(bio_out);
1784 OCSP_BASICRESP_free(bresp);
1786 switch (ocsp_status) {
1787 case OCSP_STATUS_OK:
1788 RDEBUG2("ocsp: Certificate is valid");
1791 case OCSP_STATUS_SKIPPED:
1793 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1794 vp->vp_integer = 2; /* skipped */
1795 if (conf->ocsp_softfail) {
1796 RWDEBUG("ocsp: Unable to check certificate, assuming it's valid");
1797 RWDEBUG("ocsp: This may be insecure");
1799 /* Remove OpenSSL errors from queue or handshake will fail */
1800 while (ERR_get_error());
1802 ocsp_status = OCSP_STATUS_SKIPPED;
1804 REDEBUG("ocsp: Unable to check certificate, failing");
1805 ocsp_status = OCSP_STATUS_FAILED;
1810 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1811 vp->vp_integer = 0; /* no */
1812 REDEBUG("ocsp: Certificate has been expired/revoked");
1818 #endif /* HAVE_OPENSSL_OCSP_H */
1821 * For creating certificate attributes.
1823 static char const *cert_attr_names[8][2] = {
1824 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1825 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1826 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1827 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1828 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1829 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1830 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1831 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1834 #define FR_TLS_SERIAL (0)
1835 #define FR_TLS_EXPIRATION (1)
1836 #define FR_TLS_SUBJECT (2)
1837 #define FR_TLS_ISSUER (3)
1838 #define FR_TLS_CN (4)
1839 #define FR_TLS_SAN_EMAIL (5)
1840 #define FR_TLS_SAN_DNS (6)
1841 #define FR_TLS_SAN_UPN (7)
1844 * Before trusting a certificate, you must make sure that the
1845 * certificate is 'valid'. There are several steps that your
1846 * application can take in determining if a certificate is
1847 * valid. Commonly used steps are:
1849 * 1.Verifying the certificate's signature, and verifying that
1850 * the certificate has been issued by a trusted Certificate
1853 * 2.Verifying that the certificate is valid for the present date
1854 * (i.e. it is being presented within its validity dates).
1856 * 3.Verifying that the certificate has not been revoked by its
1857 * issuing Certificate Authority, by checking with respect to a
1858 * Certificate Revocation List (CRL).
1860 * 4.Verifying that the credentials presented by the certificate
1861 * fulfill additional requirements specific to the application,
1862 * such as with respect to access control lists or with respect
1863 * to OCSP (Online Certificate Status Processing).
1865 * NOTE: This callback will be called multiple times based on the
1866 * depth of the root certificate chain
1868 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1870 char subject[1024]; /* Used for the subject name */
1871 char issuer[1024]; /* Used for the issuer name */
1872 char attribute[1024];
1874 char common_name[1024];
1878 X509_CINF *client_inf;
1879 STACK_OF(X509_EXTENSION) *ext_list;
1881 int err, depth, lookup, loc;
1882 fr_tls_server_conf_t *conf;
1885 ASN1_INTEGER *sn = NULL;
1886 ASN1_TIME *asn_time = NULL;
1889 #ifdef HAVE_OPENSSL_OCSP_H
1890 X509_STORE *ocsp_store = NULL;
1894 TALLOC_CTX *talloc_ctx;
1898 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1899 err = X509_STORE_CTX_get_error(ctx);
1900 depth = X509_STORE_CTX_get_error_depth(ctx);
1905 * Log client/issuing cert. If there's an error, log
1908 if ((lookup > 1) && !my_ok) lookup = 1;
1911 * Retrieve the pointer to the SSL of the connection currently treated
1912 * and the application specific data stored into the SSL object.
1914 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1915 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1916 if (!conf) return 1;
1918 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1919 rad_assert(request != NULL);
1920 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1922 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1923 #ifdef HAVE_OPENSSL_OCSP_H
1924 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1927 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1930 * Get the Serial Number
1933 sn = X509_get_serialNumber(client_cert);
1935 RDEBUG2("Creating attributes from certificate OIDs");
1939 * For this next bit, we create the attributes *only* if
1940 * we're at the client or issuing certificate, AND we
1941 * have a user identity. i.e. we don't create the
1942 * attributes for RadSec connections.
1944 if (certs && identity &&
1945 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1949 for (i = 0; i < sn->length; i++) {
1950 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1953 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1954 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1959 * Get the Expiration Date
1962 asn_time = X509_get_notAfter(client_cert);
1963 if (certs && identity && (lookup <= 1) && asn_time &&
1964 (asn_time->length < (int) sizeof(buf))) {
1965 memcpy(buf, (char*) asn_time->data, asn_time->length);
1966 buf[asn_time->length] = '\0';
1967 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1968 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1972 * Get the Subject & Issuer
1974 subject[0] = issuer[0] = '\0';
1975 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1977 subject[sizeof(subject) - 1] = '\0';
1978 if (certs && identity && (lookup <= 1) && subject[0]) {
1979 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1980 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1983 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1985 issuer[sizeof(issuer) - 1] = '\0';
1986 if (certs && identity && (lookup <= 1) && issuer[0]) {
1987 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1988 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1992 * Get the Common Name, if there is a subject.
1994 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1995 NID_commonName, common_name, sizeof(common_name));
1996 common_name[sizeof(common_name) - 1] = '\0';
1997 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1998 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1999 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2003 * Get the RFC822 Subject Alternative Name
2005 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
2006 if (certs && (lookup <= 1) && (loc >= 0)) {
2007 X509_EXTENSION *ext = NULL;
2008 GENERAL_NAMES *names = NULL;
2011 if ((ext = X509_get_ext(client_cert, loc)) &&
2012 (names = X509V3_EXT_d2i(ext))) {
2013 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
2014 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2016 switch (name->type) {
2019 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
2020 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
2021 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2023 #endif /* GEN_EMAIL */
2026 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
2027 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
2028 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2030 #endif /* GEN_DNS */
2031 #ifdef GEN_OTHERNAME
2033 /* look for a MS UPN */
2034 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
2035 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
2036 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
2037 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
2038 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
2039 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2042 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
2047 #endif /* GEN_OTHERNAME */
2049 /* XXX TODO handle other SAN types */
2055 sk_GENERAL_NAME_free(names);
2059 * If the CRL has expired, that might still be OK.
2062 (conf->allow_expired_crl) &&
2063 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
2065 X509_STORE_CTX_set_error( ctx, 0 );
2069 char const *p = X509_verify_cert_error_string(err);
2070 RERROR("SSL says error %d : %s", err, p);
2076 client_inf = client_cert->cert_info;
2077 ext_list = client_inf->extensions;
2083 * Grab the X509 extensions, and create attributes out of them.
2084 * For laziness, we re-use the OpenSSL names
2086 if (certs && (sk_X509_EXTENSION_num(ext_list) > 0)) {
2091 out = BIO_new(BIO_s_mem());
2092 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
2094 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
2096 X509_EXTENSION *ext;
2098 ext = sk_X509_EXTENSION_value(ext_list, i);
2100 obj = X509_EXTENSION_get_object(ext);
2101 i2a_ASN1_OBJECT(out, obj);
2102 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
2103 if (len <= 0) continue;
2105 attribute[16 + len] = '\0';
2107 for (p = attribute + 16; *p != '\0'; p++) {
2108 if (*p == ' ') *p = '-';
2111 X509V3_EXT_print(out, ext, 0, 0);
2112 len = BIO_read(out, value , sizeof(value) - 1);
2113 if (len <= 0) continue;
2117 vp = fr_pair_make(talloc_ctx, certs, attribute, value, T_OP_ADD);
2119 RDEBUG3("Skipping %s += '%s'. Please check that both the "
2120 "attribute and value are defined in the dictionaries",
2124 * rdebug_pair_list indents (so pre REXDENT())
2127 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
2137 switch (ctx->error) {
2138 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2139 RERROR("issuer=%s", issuer);
2142 case X509_V_ERR_CERT_NOT_YET_VALID:
2143 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2144 RERROR("notBefore=");
2146 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
2150 case X509_V_ERR_CERT_HAS_EXPIRED:
2151 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2152 RERROR("notAfter=");
2154 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
2160 * If we're at the actual client cert, apply additional
2165 * If the conf tells us to, check cert issuer
2166 * against the specified value and fail
2167 * verification if they don't match.
2169 if (conf->check_cert_issuer &&
2170 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
2171 AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
2172 issuer, conf->check_cert_issuer);
2177 * If the conf tells us to, check the CN in the
2178 * cert against xlat'ed value, but only if the
2179 * previous checks passed.
2181 if (my_ok && conf->check_cert_cn) {
2182 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
2183 /* if this fails, fail the verification */
2186 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
2187 if (strcmp(cn_str, common_name) != 0) {
2188 AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
2189 common_name, cn_str);
2193 } /* check_cert_cn */
2195 #ifdef HAVE_OPENSSL_OCSP_H
2196 if (my_ok && conf->ocsp_enable){
2197 RDEBUG2("Starting OCSP Request");
2198 if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
2199 RERROR("Couldn't get issuer_cert for %s", common_name);
2201 my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
2207 * If OCSP returns fail (0), the certificate has expired.
2208 * Don't run the verify routines/
2210 * If OCSP returns success (1), we MAY want to run the verify section.
2211 * but only if verify_skip_if_ocsp_ok is false.
2213 * If OCSP returns skipped (2), we run the verify command, unless
2214 * conf->verify_skip_if_ocsp_ok is true.
2217 #ifdef HAVE_OPENSSL_OCSP_H
2218 && conf->ocsp_enable && (my_ok != OCSP_STATUS_OK) && conf->verify_skip_if_ocsp_ok
2220 ) while (conf->verify_client_cert_cmd) {
2225 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
2226 conf->verify_tmp_dir, main_config.name);
2227 fd = mkstemp(filename);
2229 RDEBUG("Failed creating file in %s: %s",
2230 conf->verify_tmp_dir, fr_syserror(errno));
2234 fp = fdopen(fd, "w");
2237 RDEBUG("Failed opening file %s: %s",
2238 filename, fr_syserror(errno));
2242 if (!PEM_write_X509(fp, client_cert)) {
2244 RDEBUG("Failed writing certificate to file");
2249 if (!pair_make_request("TLS-Client-Cert-Filename",
2250 filename, T_OP_SET)) {
2251 RDEBUG("Failed creating TLS-Client-Cert-Filename");
2256 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2257 if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2258 request->packet->vps,
2259 true, true, EXEC_TIMEOUT) != 0) {
2260 AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
2263 RDEBUG("Client certificate CN %s passed external validation", common_name);
2272 if (certs && request && !my_ok) {
2273 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
2276 if (RDEBUG_ENABLED3) {
2277 RDEBUG3("chain-depth : %d", depth);
2278 RDEBUG3("error : %d", err);
2280 if (identity) RDEBUG3("identity : %s", *identity);
2281 RDEBUG3("common name : %s", common_name);
2282 RDEBUG3("subject : %s", subject);
2283 RDEBUG3("issuer : %s", issuer);
2284 RDEBUG3("verify return : %d", my_ok);
2287 return (my_ok != 0);
2291 #ifdef HAVE_OPENSSL_OCSP_H
2293 * Create Global X509 revocation store and use it to verify
2296 * - Load the trusted CAs
2297 * - Load the trusted issuer certificates
2299 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2301 X509_STORE *store = NULL;
2303 store = X509_STORE_new();
2305 /* Load the CAs we trust */
2306 if (conf->ca_file || conf->ca_path)
2307 if (!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2308 tls_error_log(NULL, "Error reading Trusted root CA list \"%s\"", conf->ca_file);
2312 #ifdef X509_V_FLAG_CRL_CHECK
2313 if (conf->check_crl)
2314 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2316 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2317 if (conf->check_all_crl)
2318 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
2322 #endif /* HAVE_OPENSSL_OCSP_H */
2324 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2325 #ifndef OPENSSL_NO_ECDH
2326 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
2331 if (!ecdh_curve || !*ecdh_curve) return 0;
2333 nid = OBJ_sn2nid(ecdh_curve);
2335 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
2339 ecdh = EC_KEY_new_by_curve_name(nid);
2341 ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
2345 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2347 if (!disable_single_dh_use) {
2348 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2359 * DIE OPENSSL DIE DIE DIE
2361 * What a palaver, just to free some data attached the
2362 * session. We need to do this because the "remove" callback
2363 * is called when refcount > 0 sometimes, if another thread
2364 * is using the session
2366 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2367 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2368 UNUSED long argl, UNUSED void *argp)
2370 VALUE_PAIR *vp = data_ptr;
2373 DEBUG2(LOG_PREFIX ": Freeing cached session VPs");
2375 fr_pair_list_free(&vp);
2378 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2379 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2380 UNUSED long argl, UNUSED void *argp)
2382 VALUE_PAIR **certs = data_ptr;
2385 DEBUG2(LOG_PREFIX ": Freeing cached session Certificates");
2387 fr_pair_list_free(certs);
2390 /** Add all the default ciphers and message digests reate our context.
2392 * This should be called exactly once from main, before reading the main config
2393 * or initialising any modules.
2395 void tls_global_init(void)
2397 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
2398 SSL_library_init(); /* initialize library */
2399 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2400 OPENSSL_config(NULL);
2403 * Initialize the index for the certificates.
2405 fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2408 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2409 /** Check for vulnerable versions of libssl
2411 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2412 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2414 int tls_global_version_check(char const *acknowledged)
2418 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2422 /* Check for bad versions */
2423 v = (uint64_t) SSLeay();
2425 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2426 libssl_defect_t *defect = &libssl_defects[i];
2428 if ((v >= defect->low) && (v <= defect->high)) {
2429 ERROR("Refusing to start with libssl version %s (in range %s)",
2430 ssl_version(), ssl_version_range(defect->low, defect->high));
2431 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2432 ERROR("%s", defect->comment);
2439 INFO("Once you have verified libssl has been correctly patched, "
2440 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2449 /** Free any memory alloced by libssl
2452 void tls_global_cleanup(void)
2454 ERR_remove_state(0);
2456 CONF_modules_unload(1);
2459 CRYPTO_cleanup_all_ex_data();
2462 /** Create SSL context
2464 * - Load the trusted CAs
2465 * - Load the Private key & the certificate
2466 * - Set the Context options & Verify options
2468 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2471 X509_STORE *certstore;
2472 int verify_mode = SSL_VERIFY_NONE;
2473 int ctx_options = 0;
2474 int ctx_tls_versions = 0;
2478 * SHA256 is in all versions of OpenSSL, but isn't
2479 * initialized by default. It's needed for WiMAX
2482 #ifdef HAVE_OPENSSL_EVP_SHA256
2483 EVP_add_digest(EVP_sha256());
2486 ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
2488 tls_error_log(NULL, "Failed creating TLS context");
2493 * Save the config on the context so that callbacks which
2494 * only get SSL_CTX* e.g. session persistence, can get it
2496 SSL_CTX_set_app_data(ctx, conf);
2499 * Identify the type of certificates that needs to be loaded
2501 if (conf->file_type) {
2502 type = SSL_FILETYPE_PEM;
2504 type = SSL_FILETYPE_ASN1;
2508 * Set the password to load private key
2510 if (conf->private_key_password) {
2513 * We don't want to put the private key password in eap.conf, so check
2514 * for our special string which indicates we should get the password
2517 char const* special_string = "Apple:UseCertAdmin";
2518 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2521 long const max_password_len = 128;
2522 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2523 conf->private_key_file);
2525 DEBUG2(LOG_PREFIX ": Getting private key passphrase using command \"%s\"", cmd);
2527 FILE* cmd_pipe = popen(cmd, "r");
2529 ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
2530 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2534 rad_const_free(conf->private_key_password);
2535 password = talloc_array(conf, char, max_password_len);
2537 ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
2538 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2543 fgets(password, max_password_len, cmd_pipe);
2546 /* Get rid of newline at end of password. */
2547 password[strlen(password) - 1] = '\0';
2549 DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
2550 conf->private_key_password = password;
2557 memcpy(&password, &conf->private_key_password, sizeof(password));
2558 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2559 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2563 #ifdef PSK_MAX_IDENTITY_LEN
2566 * No dynamic query exists. There MUST be a
2567 * statically configured identity and password.
2569 if (conf->psk_query && !*conf->psk_query) {
2570 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
2575 * Set the callback only if we can check things.
2577 if (conf->psk_identity || conf->psk_query) {
2578 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2581 } else if (conf->psk_query) {
2582 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2587 * Now check that if PSK is being used, the config is valid.
2589 if ((conf->psk_identity && !conf->psk_password) ||
2590 (!conf->psk_identity && conf->psk_password) ||
2591 (conf->psk_identity && !*conf->psk_identity) ||
2592 (conf->psk_password && !*conf->psk_password)) {
2593 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
2597 if (conf->psk_identity) {
2598 size_t psk_len, hex_len;
2599 uint8_t buffer[PSK_MAX_PSK_LEN];
2601 if (conf->certificate_file ||
2602 conf->private_key_password || conf->private_key_file ||
2603 conf->ca_file || conf->ca_path) {
2604 ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
2609 SSL_CTX_set_psk_client_callback(ctx,
2610 psk_client_callback);
2613 psk_len = strlen(conf->psk_password);
2614 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2615 ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
2620 * Check the password now, so that we don't have
2621 * errors at run-time.
2623 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2624 if (psk_len != (2 * hex_len)) {
2625 ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
2632 (void) client; /* -Wunused */
2636 * Load our keys and certificates
2638 * If certificates are of type PEM then we can make use
2639 * of cert chain authentication using openssl api call
2640 * SSL_CTX_use_certificate_chain_file. Please see how
2641 * the cert chain needs to be given in PEM from
2644 if (!conf->certificate_file) goto load_ca;
2646 if (type == SSL_FILETYPE_PEM) {
2647 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2648 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2649 conf->certificate_file);
2653 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2654 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2655 conf->certificate_file);
2659 /* Load the CAs we trust */
2661 if (conf->ca_file || conf->ca_path) {
2662 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2663 tls_error_log(NULL, "Failed reading Trusted root CA list \"%s\"",
2668 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2670 if (conf->private_key_file) {
2671 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2672 tls_error_log(NULL, "Failed reading private key file \"%s\"",
2673 conf->private_key_file);
2678 * Check if the loaded private key is the right one
2680 if (!SSL_CTX_check_private_key(ctx)) {
2681 ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
2686 #ifdef PSK_MAX_IDENTITY_LEN
2691 * We never want SSLv2 or SSLv3.
2693 ctx_options |= SSL_OP_NO_SSLv2;
2694 ctx_options |= SSL_OP_NO_SSLv3;
2697 * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2698 * Though they can be *globally* disabled if necessary.x
2700 #ifdef SSL_OP_NO_TLSv1
2701 if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
2703 ctx_tls_versions |= SSL_OP_NO_TLSv1;
2705 #ifdef SSL_OP_NO_TLSv1_1
2706 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2708 ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
2710 #ifdef SSL_OP_NO_TLSv1_2
2712 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2714 ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
2718 if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
2719 ERROR(LOG_PREFIX ": You have disabled all available TLS versions. EAP will not work");
2723 #ifdef SSL_OP_NO_TICKET
2724 ctx_options |= SSL_OP_NO_TICKET;
2727 if (!conf->disable_single_dh_use) {
2729 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2730 * small subgroup attacks and forward secrecy. Always
2731 * using SSL_OP_SINGLE_DH_USE has an impact on the
2732 * computer time needed during negotiation, but it is not
2735 ctx_options |= SSL_OP_SINGLE_DH_USE;
2739 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2740 * in Windows Vista client.
2741 * http://www.openssl.org/~bodo/tls-cbc.txt
2742 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2744 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2746 SSL_CTX_set_options(ctx, ctx_options);
2749 * TODO: Set the RSA & DH
2750 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2751 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2755 * set the message callback to identify the type of
2756 * message. For every new session, there can be a
2757 * different callback argument.
2759 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2763 * Set eliptical curve crypto configuration.
2765 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2766 #ifndef OPENSSL_NO_ECDH
2767 if (set_ecdh_curve(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) {
2774 * OpenSSL will automatically create certificate chains,
2775 * unless we tell it to not do that. The problem is that
2776 * it sometimes gets the chains right from a certificate
2777 * signature view, but wrong from the clients view.
2779 if (!conf->auto_chain) {
2780 SSL_CTX_set_mode(ctx, SSL_MODE_NO_AUTO_CHAIN);
2783 /* Set Info callback */
2784 SSL_CTX_set_info_callback(ctx, cbtls_info);
2787 * Callbacks, etc. for session resumption.
2789 if (conf->session_cache_enable) {
2791 * Cache sessions on disk if requested.
2793 if (conf->session_cache_path) {
2794 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2795 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2796 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2799 SSL_CTX_set_quiet_shutdown(ctx, 1);
2800 if (fr_tls_ex_index_vps < 0)
2801 fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2805 * Check the certificates for revocation.
2807 #ifdef X509_V_FLAG_CRL_CHECK
2808 if (conf->check_crl) {
2809 certstore = SSL_CTX_get_cert_store(ctx);
2810 if (certstore == NULL) {
2811 tls_error_log(NULL, "Error reading Certificate Store");
2814 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2816 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2817 if (conf->check_all_crl)
2818 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
2825 * Always verify the peer certificate
2827 verify_mode |= SSL_VERIFY_PEER;
2828 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2829 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2830 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2832 if (conf->verify_depth) {
2833 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2836 /* Load randomness */
2837 if (conf->random_file) {
2838 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2839 tls_error_log(NULL, "Failed loading randomness");
2845 * Set the cipher list if we were told to
2847 if (conf->cipher_list) {
2848 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2849 tls_error_log(NULL, "Failed setting cipher list");
2855 * Setup session caching
2857 if (conf->session_cache_enable) {
2859 * Create a unique context Id per EAP-TLS configuration.
2861 if (conf->session_id_name) {
2862 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2863 "FR eap %s", conf->session_id_name);
2865 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2870 * Cache it, and DON'T auto-clear it.
2872 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2874 SSL_CTX_set_session_id_context(ctx,
2875 (unsigned char *) conf->session_context_id,
2876 (unsigned int) strlen(conf->session_context_id));
2879 * Our timeout is in hours, this is in seconds.
2881 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2884 * Set the maximum number of entries in the
2887 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2890 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2898 * Free TLS client/server config
2899 * Should not be called outside this code, as a callback is
2900 * added to automatically free the data when the CONF_SECTION
2903 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2905 if (conf->ctx) SSL_CTX_free(conf->ctx);
2907 #ifdef HAVE_OPENSSL_OCSP_H
2908 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2909 conf->ocsp_store = NULL;
2913 memset(conf, 0, sizeof(*conf));
2918 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2920 fr_tls_server_conf_t *conf;
2922 conf = talloc_zero(ctx, fr_tls_server_conf_t);
2924 ERROR(LOG_PREFIX ": Out of memory");
2928 talloc_set_destructor(conf, _tls_server_conf_free);
2933 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2935 fr_tls_server_conf_t *conf;
2938 * If cs has already been parsed there should be a cached copy
2939 * of conf already stored, so just return that.
2941 conf = cf_data_find(cs, "tls-conf");
2943 DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
2947 conf = tls_server_conf_alloc(cs);
2949 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2956 * Save people from their own stupidity.
2958 if (conf->fragment_size < 100) conf->fragment_size = 100;
2960 if (!conf->private_key_file) {
2961 ERROR(LOG_PREFIX ": TLS Server requires a private key file");
2965 if (!conf->certificate_file) {
2966 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
2973 conf->ctx = tls_init_ctx(conf, 0);
2974 if (conf->ctx == NULL) {
2978 #ifdef HAVE_OPENSSL_OCSP_H
2980 * Initialize OCSP Revocation Store
2982 if (conf->ocsp_enable) {
2983 conf->ocsp_store = init_revocation_store(conf);
2984 if (conf->ocsp_store == NULL) goto error;
2986 #endif /*HAVE_OPENSSL_OCSP_H*/
2990 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2991 if (load_dh_params(conf->ctx, dh_file) < 0) {
2996 if (conf->verify_tmp_dir) {
2997 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2998 ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
2999 conf->verify_tmp_dir, fr_syserror(errno));
3004 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
3005 ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
3009 #ifdef SSL_OP_NO_TLSv1_2
3011 * OpenSSL 1.0.1f and 1.0.1g get the MS-MPPE keys wrong.
3013 #if (OPENSSL_VERSION_NUMBER >= 0x10010060L) && (OPENSSL_VERSION_NUMBER < 0x10010060L)
3014 conf->disable_tlsv1_2 = true;
3015 WARN(LOG_PREFIX ": Disabling TLSv1.2 due to OpenSSL bugs");
3020 * Cache conf in cs in case we're asked to parse this again.
3022 cf_data_add(cs, "tls-conf", conf, NULL);
3027 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
3029 fr_tls_server_conf_t *conf;
3031 conf = cf_data_find(cs, "tls-conf");
3033 DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3037 conf = tls_server_conf_alloc(cs);
3039 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
3046 * Save people from their own stupidity.
3048 if (conf->fragment_size < 100) conf->fragment_size = 100;
3053 conf->ctx = tls_init_ctx(conf, 1);
3054 if (conf->ctx == NULL) {
3061 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
3062 if (load_dh_params(conf->ctx, dh_file) < 0) {
3067 cf_data_add(cs, "tls-conf", conf, NULL);
3072 int tls_success(tls_session_t *ssn, REQUEST *request)
3074 VALUE_PAIR *vp, *vps = NULL;
3075 fr_tls_server_conf_t *conf;
3076 TALLOC_CTX *talloc_ctx;
3078 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
3079 rad_assert(conf != NULL);
3081 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
3084 * If there's no session resumption, delete the entry
3085 * from the cache. This means either it's disabled
3086 * globally for this SSL context, OR we were told to
3087 * disable it for this user.
3089 * This also means you can't turn it on just for one
3092 if ((!ssn->allow_session_resumption) ||
3093 (((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
3094 (vp->vp_integer == 0))) {
3095 SSL_CTX_remove_session(ssn->ctx,
3097 ssn->allow_session_resumption = false;
3100 * If we're in a resumed session and it's
3103 if (SSL_session_reused(ssn->ssl)) {
3104 RDEBUG("Forcibly stopping session resumption as it is not allowed");
3109 * Else resumption IS allowed, so we store the
3110 * user data in the cache.
3112 } else if (!SSL_session_reused(ssn->ssl)) {
3114 char buffer[2 * MAX_SESSION_SIZE + 1];
3116 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3118 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
3119 if (vp) fr_pair_add(&vps, vp);
3121 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
3122 if (vp) fr_pair_add(&vps, vp);
3124 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
3125 if (vp) fr_pair_add(&vps, vp);
3127 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
3128 if (vp) fr_pair_add(&vps, vp);
3130 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
3131 if (vp) fr_pair_add(&vps, vp);
3133 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3136 * Hmm... the certs should probably be session data.
3140 * @todo: some go into reply, others into
3143 fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
3146 * Save the certs in the packet, so that we can see them.
3148 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3152 SSL_SESSION_set_ex_data(ssn->ssl_session, fr_tls_ex_index_vps, vps);
3153 rdebug_pair_list(L_DBG_LVL_2, request, vps, " caching ");
3155 if (conf->session_cache_path) {
3156 /* write the VPs to the cache file */
3157 char filename[256], buf[1024];
3160 RDEBUG2("Saving session %s in the disk cache", buffer);
3162 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
3163 FR_DIR_SEP, buffer);
3164 vp_file = fopen(filename, "w");
3165 if (vp_file == NULL) {
3166 RWDEBUG("Could not write session VPs to persistent cache: %s",
3167 fr_syserror(errno));
3169 VALUE_PAIR *prev = NULL;
3171 /* generate a dummy user-style entry which is easy to read back */
3172 fprintf(vp_file, "# SSL cached session\n");
3173 fprintf(vp_file, "%s\n\t", buffer);
3175 for (vp = fr_cursor_init(&cursor, &vps);
3177 vp = fr_cursor_next(&cursor)) {
3179 * Terminate the previous line.
3181 if (prev) fprintf(vp_file, ",\n\t");
3186 vp_prints(buf, sizeof(buf), vp);
3187 fputs(buf, vp_file);
3192 * Terminate the final line.
3194 fprintf(vp_file, "\n");
3198 RDEBUG("Failed to find 'persist_dir' in TLS configuration. Session will not be cached on disk.");
3201 RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
3202 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3206 * Else the session WAS allowed. Copy the cached reply.
3209 char buffer[2 * MAX_SESSION_SIZE + 1];
3211 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3214 * The "restore VPs from OpenSSL cache" code is
3215 * now in eaptls_process()
3218 if (conf->session_cache_path) {
3219 /* "touch" the cached session/vp file */
3222 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
3223 conf->session_cache_path, FR_DIR_SEP, buffer);
3224 utime(filename, NULL);
3225 snprintf(filename, sizeof(filename), "%s%c%s.vps",
3226 conf->session_cache_path, FR_DIR_SEP, buffer);
3227 utime(filename, NULL);
3231 * Mark the request as resumed.
3233 pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
3240 void tls_fail(tls_session_t *ssn)
3243 * Force the session to NOT be cached.
3245 SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3248 fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
3255 * Decrypt the complete record.
3257 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
3258 ssn->dirty_in.used);
3259 if (err != (int) ssn->dirty_in.used) {
3260 record_init(&ssn->dirty_in);
3261 RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
3266 * Clear the dirty buffer now that we are done with it
3267 * and init the clean_out buffer to store decrypted data
3269 record_init(&ssn->dirty_in);
3270 record_init(&ssn->clean_out);
3273 * Read (and decrypt) the tunneled data from the
3274 * SSL session, and put it into the decrypted
3277 err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
3281 RDEBUG("SSL_read Error");
3283 code = SSL_get_error(ssn->ssl, err);
3285 case SSL_ERROR_WANT_READ:
3286 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
3287 return FR_TLS_MORE_FRAGMENTS;
3289 case SSL_ERROR_WANT_WRITE:
3290 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
3294 REDEBUG("Error in fragmentation logic");
3295 tls_error_io_log(request, ssn, err,
3296 "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)");
3302 if (err == 0) RWDEBUG("No data inside of the tunnel");
3305 * Passed all checks, successfully decrypted data
3307 ssn->clean_out.used = err;
3310 * Add the certificates to intermediate packets, so that
3311 * the inner tunnel policies can use them.
3313 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3315 if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3322 * Acknowledge received is for one of the following messages sent earlier
3323 * 1. Handshake completed Message, so now send, EAP-Success
3324 * 2. Alert Message, now send, EAP-Failure
3325 * 3. Fragment Message, now send, next Fragment
3327 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
3330 REDEBUG("Unexpected ACK received: No ongoing SSL session");
3331 return FR_TLS_INVALID;
3333 if (!ssn->info.initialized) {
3334 RDEBUG("No SSL info available. Waiting for more SSL data");
3335 return FR_TLS_REQUEST;
3338 if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3339 REDEBUG("Unexpected ACK received: We sent no previous messages");
3340 return FR_TLS_INVALID;
3343 switch (ssn->info.content_type) {
3345 RDEBUG2("Peer ACKed our alert");
3349 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3350 RDEBUG2("Peer ACKed our handshake fragment. handshake is finished");
3353 * From now on all the content is
3354 * application data set it here as nobody else
3357 ssn->info.content_type = application_data;
3358 return FR_TLS_SUCCESS;
3359 } /* else more data to send */
3361 RDEBUG2("Peer ACKed our handshake fragment");
3362 /* Fragmentation handler, send next fragment */
3363 return FR_TLS_REQUEST;
3365 case application_data:
3366 RDEBUG2("Peer ACKed our application data fragment");
3367 return FR_TLS_REQUEST;
3370 * For the rest of the conditions, switch over
3371 * to the default section below.
3374 REDEBUG("Invalid ACK received: %d", ssn->info.content_type);
3375 return FR_TLS_INVALID;
3378 #endif /* WITH_TLS */