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 == '.')) {
142 * When a client uses TLS-PSK to talk to a server, this callback
143 * is used by the server to determine the PSK to use.
145 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
147 unsigned int max_psk_len)
149 unsigned int psk_len = 0;
150 fr_tls_server_conf_t *conf;
153 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
154 FR_TLS_EX_INDEX_CONF);
157 request = (REQUEST *)SSL_get_ex_data(ssl,
158 FR_TLS_EX_INDEX_REQUEST);
159 if (request && conf->psk_query) {
162 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
165 * The passed identity is weird. Deny it.
167 if (!identity_is_safe(identity)) {
168 RWDEBUG("Invalid characters in PSK identity %s", identity);
172 vp = pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
175 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
178 RWDEBUG("PSK expansion returned an empty string.");
183 * The returned key is truncated at MORE than
184 * OpenSSL can handle. That way we can detect
185 * the truncation, and complain about it.
187 if (hex_len > (2 * max_psk_len)) {
188 RWDEBUG("Returned PSK is too long (%u > %u)",
189 (unsigned int) hex_len, 2 * max_psk_len);
194 * Leave the TLS-PSK-Identity in the request, and
195 * convert the expansion from printable string
198 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
201 if (!conf->psk_identity) {
202 DEBUG("No static PSK identity set. Rejecting the user");
207 * No REQUEST, or no dynamic query. Just look for a
210 if (strcmp(identity, conf->psk_identity) != 0) {
211 ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
216 psk_len = strlen(conf->psk_password);
217 if (psk_len > (2 * max_psk_len)) return 0;
219 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
222 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
223 char *identity, unsigned int max_identity_len,
224 unsigned char *psk, unsigned int max_psk_len)
226 unsigned int psk_len;
227 fr_tls_server_conf_t *conf;
229 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
230 FR_TLS_EX_INDEX_CONF);
233 psk_len = strlen(conf->psk_password);
234 if (psk_len > (2 * max_psk_len)) return 0;
236 strlcpy(identity, conf->psk_identity, max_identity_len);
238 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
243 static int _tls_session_free(tls_session_t *ssn)
246 * Free any opaque TTLS or PEAP data.
248 if ((ssn->opaque) && (ssn->free_opaque)) {
249 ssn->free_opaque(ssn->opaque);
258 tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
261 tls_session_t *ssn = NULL;
264 ssn = talloc_zero(ctx, tls_session_t);
265 if (!ssn) return NULL;
267 talloc_set_destructor(ssn, _tls_session_free);
269 ssn->ctx = conf->ctx;
271 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
273 ssn->ssl = SSL_new(ssn->ctx);
279 request = request_alloc(ssn);
280 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
283 * Add the message callback to identify what type of
284 * message/handshake is passed
286 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
287 SSL_set_msg_callback_arg(ssn->ssl, ssn);
288 SSL_set_info_callback(ssn->ssl, cbtls_info);
291 * Always verify the peer certificate.
293 DEBUG2("Requiring Server certificate");
294 verify_mode = SSL_VERIFY_PEER;
295 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
296 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
298 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
299 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
300 SSL_set_fd(ssn->ssl, fd);
301 if (SSL_connect(ssn->ssl) <= 0) {
303 while ((err = ERR_get_error())) {
304 ERROR("tls: %s", ERR_error_string(err, NULL));
311 ssn->mtu = conf->fragment_size;
316 /** Create a new TLS session
318 * Configures a new TLS session, configuring options, setting callbacks etc...
320 * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
321 * session is tied to another talloc'd object.
322 * @param conf to use to configure the tls session.
323 * @param request The current #REQUEST.
324 * @param client_cert Whether to require a client_cert.
325 * @return a new session on success, or NULL on error.
327 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
329 tls_session_t *state = NULL;
334 rad_assert(request != NULL);
336 RDEBUG2("Initiating new EAP-TLS session");
339 * Manually flush the sessions every so often. If HALF
340 * of the session lifetime has passed since we last
341 * flushed, then flush it again.
343 * FIXME: Also do it every N sessions?
345 if (conf->session_cache_enable &&
346 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
347 RDEBUG2("Flushing SSL sessions (of #%ld)", SSL_CTX_sess_number(conf->ctx));
349 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
350 conf->session_last_flushed = request->timestamp;
353 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
354 RERROR("Error creating new SSL session: %s", ERR_error_string(ERR_get_error(), NULL));
358 /* We use the SSL's "app_data" to indicate a call-back */
359 SSL_set_app_data(new_tls, NULL);
361 if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
362 RERROR("Error allocating memory for SSL state");
366 talloc_set_destructor(state, _tls_session_free);
368 state->ctx = conf->ctx;
369 state->ssl = new_tls;
372 * Initialize callbacks
374 state->record_init = record_init;
375 state->record_close = record_close;
376 state->record_plus = record_plus;
377 state->record_minus = record_minus;
380 * Create & hook the BIOs to handle the dirty side of the
381 * SSL. This is *very important* as we want to handle
382 * the transmission part. Now the only IO interface
383 * that SSL is aware of, is our defined BIO buffers.
385 * This means that all SSL IO is done to/from memory,
386 * and we can update those BIOs from the packets we've
389 state->into_ssl = BIO_new(BIO_s_mem());
390 state->from_ssl = BIO_new(BIO_s_mem());
391 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
394 * Add the message callback to identify what type of
395 * message/handshake is passed
397 SSL_set_msg_callback(new_tls, cbtls_msg);
398 SSL_set_msg_callback_arg(new_tls, state);
399 SSL_set_info_callback(new_tls, cbtls_info);
402 * In Server mode we only accept.
404 SSL_set_accept_state(state->ssl);
407 * Verify the peer certificate, if asked.
410 RDEBUG2("Setting verify mode to require certificate from client");
411 verify_mode = SSL_VERIFY_PEER;
412 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
413 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
415 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
417 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
418 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
419 state->length_flag = conf->include_length;
422 * We use default fragment size, unless the Framed-MTU
423 * tells us it's too big. Note that we do NOT account
424 * for the EAP-TLS headers if conf->fragment_size is
425 * large, because that config item looks to be confusing.
427 * i.e. it should REALLY be called MTU, and the code here
428 * should figure out what that means for TLS fragment size.
429 * asking the administrator to know the internal details
430 * of EAP-TLS in order to calculate fragment sizes is
433 state->mtu = conf->fragment_size;
434 vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
435 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->mtu)) {
436 state->mtu = vp->vp_integer;
439 if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
445 * Print out some text describing the error.
447 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
452 if ((l = ERR_get_error()) != 0) {
453 char const *p = ERR_error_string(l, NULL);
455 if (p) ROPTIONAL(REDEBUG, ERROR, "SSL says: %s", p);
458 e = SSL_get_error(s, ret);
461 * These seem to be harmless and already "dealt
462 * with" by our non-blocking environment. NB:
463 * "ZERO_RETURN" is the clean "error"
464 * indicating a successfully closed SSL
465 * tunnel. We let this happen because our IO
466 * loop should not appear to have broken on
467 * this condition - and outside the IO loop, the
468 * "shutdown" state is checked.
470 * Don't print anything if we ignore the error.
473 case SSL_ERROR_WANT_READ:
474 case SSL_ERROR_WANT_WRITE:
475 case SSL_ERROR_WANT_X509_LOOKUP:
476 case SSL_ERROR_ZERO_RETURN:
480 * These seem to be indications of a genuine
481 * error that should result in the SSL tunnel
482 * being regarded as "dead".
484 case SSL_ERROR_SYSCALL:
485 ROPTIONAL(REDEBUG, ERROR, "%s failed in a system call (%d), TLS session failed", text, ret);
489 ROPTIONAL(REDEBUG, ERROR, "%s failed inside of TLS (%d), TLS session failed", text, ret);
493 * For any other errors that (a) exist, and (b)
494 * crop up - we need to interpret what to do with
495 * them - so "politely inform" the caller that
496 * the code needs updating here.
499 ROPTIONAL(REDEBUG, ERROR, "FATAL SSL error: %d", e);
507 * We are the server, we always get the dirty data
508 * (Handshake data is also considered as dirty data)
509 * During handshake, since SSL API handles itself,
510 * After clean-up, dirty_out will be filled with
511 * the data required for handshaking. So we check
512 * if dirty_out is empty then we simply send it back.
513 * As of now, if handshake is successful, then we keep going,
516 * Fill the Bio with the dirty data to clean it
517 * Get the cleaned data from SSL, if it is not Handshake data
519 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
523 if (ssn->invalid_hb_used) return 0;
525 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
526 if (err != (int) ssn->dirty_in.used) {
527 REDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
528 record_init(&ssn->dirty_in);
531 record_init(&ssn->dirty_in);
533 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
534 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
536 ssn->clean_out.used += err;
540 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) return 0;
542 /* Some Extra STATE information for easy debugging */
543 if (SSL_is_init_finished(ssn->ssl)) RDEBUG2("SSL Connection Established");
544 if (SSL_in_init(ssn->ssl)) RDEBUG2("In SSL Handshake Phase");
545 if (SSL_in_before(ssn->ssl)) RDEBUG2("Before SSL Handshake Phase");
546 if (SSL_in_accept_init(ssn->ssl)) RDEBUG2("In SSL Accept mode");
547 if (SSL_in_connect_init(ssn->ssl)) RDEBUG2("In SSL Connect mode");
549 err = BIO_ctrl_pending(ssn->from_ssl);
551 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
552 sizeof(ssn->dirty_out.data));
554 ssn->dirty_out.used = err;
556 } else if (BIO_should_retry(ssn->from_ssl)) {
557 record_init(&ssn->dirty_in);
558 RDEBUG2("Asking for more data in tunnel");
562 int_ssl_check(request, ssn->ssl, err, "BIO_read");
563 record_init(&ssn->dirty_in);
567 RDEBUG2("SSL Application Data");
568 /* Its clean application data, do whatever we want */
569 record_init(&ssn->clean_out);
572 /* We are done with dirty_in, reinitialize it */
573 record_init(&ssn->dirty_in);
578 * Take cleartext user data, and encrypt it into the output buffer,
579 * to send to the client at the other end of the SSL connection.
581 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
586 * If there's un-encrypted data in 'clean_in', then write
587 * that data to the SSL session, and then call the BIO function
588 * to get that encrypted data from the SSL session, into
589 * a buffer which we can then package into an EAP packet.
591 * Based on Server's logic this clean_in is expected to
592 * contain the data to send to the client.
594 if (ssn->clean_in.used > 0) {
597 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
598 record_minus(&ssn->clean_in, NULL, written);
600 /* Get the dirty data from Bio to send it */
601 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
602 sizeof(ssn->dirty_out.data));
604 ssn->dirty_out.used = err;
606 int_ssl_check(request, ssn->ssl, err, "handshake_send");
613 static void session_init(tls_session_t *ssn)
616 ssn->into_ssl = ssn->from_ssl = NULL;
617 record_init(&ssn->clean_in);
618 record_init(&ssn->clean_out);
619 record_init(&ssn->dirty_in);
620 record_init(&ssn->dirty_out);
622 memset(&ssn->info, 0, sizeof(ssn->info));
625 ssn->fragment = false;
626 ssn->tls_msg_len = 0;
627 ssn->length_flag = false;
629 ssn->free_opaque = NULL;
632 static void session_close(tls_session_t *ssn)
634 SSL_set_quiet_shutdown(ssn->ssl, 1);
635 SSL_shutdown(ssn->ssl);
642 record_close(&ssn->clean_in);
643 record_close(&ssn->clean_out);
644 record_close(&ssn->dirty_in);
645 record_close(&ssn->dirty_out);
649 static void record_init(record_t *rec)
654 static void record_close(record_t *rec)
661 * Copy data to the intermediate buffer, before we send
664 static unsigned int record_plus(record_t *rec, void const *ptr,
667 unsigned int added = MAX_RECORD_SIZE - rec->used;
673 memcpy(rec->data + rec->used, ptr, added);
679 * Take data from the buffer, and give it to the caller.
681 static unsigned int record_minus(record_t *rec, void *ptr,
684 unsigned int taken = rec->used;
691 memcpy(ptr, rec->data, taken);
695 * This is pretty bad...
698 memmove(rec->data, rec->data + taken, rec->used);
702 void tls_session_information(tls_session_t *tls_session)
704 char const *str_write_p, *str_version, *str_content_type = "";
705 char const *str_details1 = "", *str_details2= "";
710 * Don't print this out in the normal course of
713 if (rad_debug_lvl == 0) {
717 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
719 switch (tls_session->info.version) {
721 str_version = "SSL 2.0 ";
724 str_version = "SSL 3.0 ";
727 str_version = "TLS 1.0 ";
729 #ifdef TLS1_1_VERSION
731 str_version = "TLS 1.1 ";
734 #ifdef TLS1_2_VERSION
736 str_version = "TLS 1.2 ";
741 str_version = "TLS 1.3 ";
746 sprintf(buffer, "UNKNOWN TLS VERSION ?%04X?", tls_session->info.version);
747 str_version = buffer;
751 if (tls_session->info.version == SSL3_VERSION ||
752 tls_session->info.version == TLS1_VERSION) {
753 switch (tls_session->info.content_type) {
754 case SSL3_RT_CHANGE_CIPHER_SPEC:
755 str_content_type = "ChangeCipherSpec";
759 str_content_type = "Alert";
762 case SSL3_RT_HANDSHAKE:
763 str_content_type = "Handshake";
766 case SSL3_RT_APPLICATION_DATA:
767 str_content_type = "ApplicationData";
771 str_content_type = "UnknownContentType";
775 if (tls_session->info.content_type == SSL3_RT_ALERT) {
776 str_details1 = ", ???";
778 if (tls_session->info.record_len == 2) {
780 switch (tls_session->info.alert_level) {
781 case SSL3_AL_WARNING:
782 str_details1 = ", warning";
785 str_details1 = ", fatal";
789 str_details2 = " ???";
790 switch (tls_session->info.alert_description) {
791 case SSL3_AD_CLOSE_NOTIFY:
792 str_details2 = " close_notify";
795 case SSL3_AD_UNEXPECTED_MESSAGE:
796 str_details2 = " unexpected_message";
799 case SSL3_AD_BAD_RECORD_MAC:
800 str_details2 = " bad_record_mac";
803 case TLS1_AD_DECRYPTION_FAILED:
804 str_details2 = " decryption_failed";
807 case TLS1_AD_RECORD_OVERFLOW:
808 str_details2 = " record_overflow";
811 case SSL3_AD_DECOMPRESSION_FAILURE:
812 str_details2 = " decompression_failure";
815 case SSL3_AD_HANDSHAKE_FAILURE:
816 str_details2 = " handshake_failure";
819 case SSL3_AD_BAD_CERTIFICATE:
820 str_details2 = " bad_certificate";
823 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
824 str_details2 = " unsupported_certificate";
827 case SSL3_AD_CERTIFICATE_REVOKED:
828 str_details2 = " certificate_revoked";
831 case SSL3_AD_CERTIFICATE_EXPIRED:
832 str_details2 = " certificate_expired";
835 case SSL3_AD_CERTIFICATE_UNKNOWN:
836 str_details2 = " certificate_unknown";
839 case SSL3_AD_ILLEGAL_PARAMETER:
840 str_details2 = " illegal_parameter";
843 case TLS1_AD_UNKNOWN_CA:
844 str_details2 = " unknown_ca";
847 case TLS1_AD_ACCESS_DENIED:
848 str_details2 = " access_denied";
851 case TLS1_AD_DECODE_ERROR:
852 str_details2 = " decode_error";
855 case TLS1_AD_DECRYPT_ERROR:
856 str_details2 = " decrypt_error";
859 case TLS1_AD_EXPORT_RESTRICTION:
860 str_details2 = " export_restriction";
863 case TLS1_AD_PROTOCOL_VERSION:
864 str_details2 = " protocol_version";
867 case TLS1_AD_INSUFFICIENT_SECURITY:
868 str_details2 = " insufficient_security";
871 case TLS1_AD_INTERNAL_ERROR:
872 str_details2 = " internal_error";
875 case TLS1_AD_USER_CANCELLED:
876 str_details2 = " user_canceled";
879 case TLS1_AD_NO_RENEGOTIATION:
880 str_details2 = " no_renegotiation";
886 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
887 str_details1 = "???";
889 if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
890 case SSL3_MT_HELLO_REQUEST:
891 str_details1 = ", HelloRequest";
894 case SSL3_MT_CLIENT_HELLO:
895 str_details1 = ", ClientHello";
898 case SSL3_MT_SERVER_HELLO:
899 str_details1 = ", ServerHello";
902 case SSL3_MT_CERTIFICATE:
903 str_details1 = ", Certificate";
906 case SSL3_MT_SERVER_KEY_EXCHANGE:
907 str_details1 = ", ServerKeyExchange";
910 case SSL3_MT_CERTIFICATE_REQUEST:
911 str_details1 = ", CertificateRequest";
914 case SSL3_MT_SERVER_DONE:
915 str_details1 = ", ServerHelloDone";
918 case SSL3_MT_CERTIFICATE_VERIFY:
919 str_details1 = ", CertificateVerify";
922 case SSL3_MT_CLIENT_KEY_EXCHANGE:
923 str_details1 = ", ClientKeyExchange";
926 case SSL3_MT_FINISHED:
927 str_details1 = ", Finished";
933 snprintf(tls_session->info.info_description,
934 sizeof(tls_session->info.info_description),
935 "%s %s%s [length %04lx]%s%s\n",
936 str_write_p, str_version, str_content_type,
937 (unsigned long)tls_session->info.record_len,
938 str_details1, str_details2);
940 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
942 RDEBUG2("%s", tls_session->info.info_description);
944 DEBUG2("%s", tls_session->info.info_description);
948 static CONF_PARSER cache_config[] = {
949 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
951 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
952 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
954 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
955 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
956 CONF_PARSER_TERMINATOR
959 static CONF_PARSER verify_config[] = {
960 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
961 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
962 CONF_PARSER_TERMINATOR
965 #ifdef HAVE_OPENSSL_OCSP_H
966 static CONF_PARSER ocsp_config[] = {
967 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
968 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
969 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
970 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
971 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
972 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
973 CONF_PARSER_TERMINATOR
977 static CONF_PARSER tls_server_config[] = {
978 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
979 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
980 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
981 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
982 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
983 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
984 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
985 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
986 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
987 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
988 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
989 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
990 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
991 #ifdef PSK_MAX_IDENTITY_LEN
992 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
993 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
994 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
996 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
997 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
998 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
999 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1000 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1001 #ifdef X509_V_FLAG_CRL_CHECK_ALL
1002 { "check_all_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), "no" },
1004 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
1005 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1006 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1007 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1008 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
1010 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1011 #ifndef OPENSSL_NO_ECDH
1012 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1016 #ifdef SSL_OP_NO_TLSv1
1017 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1020 #ifdef SSL_OP_NO_TLSv1_1
1021 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1024 #ifdef SSL_OP_NO_TLSv1_2
1025 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1028 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
1030 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
1032 #ifdef HAVE_OPENSSL_OCSP_H
1033 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
1035 CONF_PARSER_TERMINATOR
1039 static CONF_PARSER tls_client_config[] = {
1040 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
1041 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
1042 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
1043 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
1044 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1045 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1046 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1047 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1048 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1049 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1050 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1051 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1052 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1053 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1054 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1055 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1056 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1057 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1058 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1060 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1061 #ifndef OPENSSL_NO_ECDH
1062 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1066 #ifdef SSL_OP_NO_TLSv1
1067 { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1070 #ifdef SSL_OP_NO_TLSv1_1
1071 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1074 #ifdef SSL_OP_NO_TLSv1_2
1075 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1077 CONF_PARSER_TERMINATOR
1082 * TODO: Check for the type of key exchange * like conf->dh_key
1084 static int load_dh_params(SSL_CTX *ctx, char *file)
1089 if (!file) return 0;
1091 if ((bio = BIO_new_file(file, "r")) == NULL) {
1092 ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
1096 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1099 WARN(LOG_PREFIX ": Unable to set DH parameters. DH cipher suites may not work!");
1100 WARN(LOG_PREFIX ": Fix this by running the OpenSSL command listed in eap.conf");
1104 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1105 ERROR(LOG_PREFIX ": Unable to set DH parameters");
1116 * Print debugging messages, and free data.
1118 #define MAX_SESSION_SIZE (256)
1120 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1123 char buffer[2 * MAX_SESSION_SIZE + 1];
1124 fr_tls_server_conf_t *conf;
1126 size = sess->session_id_length;
1127 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1129 fr_bin2hex(buffer, sess->session_id, size);
1131 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1133 DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
1141 DEBUG2(LOG_PREFIX ": Removing session %s from the cache", buffer);
1143 /* remove session and any cached VPs */
1144 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1145 conf->session_cache_path, FR_DIR_SEP, buffer);
1146 rv = unlink(filename);
1148 DEBUG2(LOG_PREFIX ": Could not remove persisted session file %s: %s",
1149 filename, fr_syserror(errno));
1151 /* VPs might be absent; might not have been written to disk yet */
1152 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1153 conf->session_cache_path, FR_DIR_SEP, buffer);
1160 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1163 char buffer[2 * MAX_SESSION_SIZE + 1];
1164 fr_tls_server_conf_t *conf;
1165 unsigned char *sess_blob = NULL;
1167 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1169 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1171 RWDEBUG("Failed to find TLS configuration in session");
1175 size = sess->session_id_length;
1176 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1178 fr_bin2hex(buffer, sess->session_id, size);
1181 int fd, rv, todo, blob_len;
1185 RDEBUG2("Serialising session %s, and storing in cache", buffer);
1187 /* find out what length data we need */
1188 blob_len = i2d_SSL_SESSION(sess, NULL);
1190 /* something went wrong */
1191 RWDEBUG("Session serialisation failed, couldn't determine required buffer length");
1196 /* Do not convert to TALLOC - Thread safety */
1197 /* alloc and convert to ASN.1 */
1198 sess_blob = malloc(blob_len);
1200 RWDEBUG("Session serialisation failed, couldn't allocate buffer (%d bytes)", blob_len);
1203 /* openssl mutates &p */
1205 rv = i2d_SSL_SESSION(sess, &p);
1206 if (rv != blob_len) {
1207 RWDEBUG("Session serialisation failed");
1211 /* open output file */
1212 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1213 conf->session_cache_path, FR_DIR_SEP, buffer);
1214 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1216 RERROR("Session serialisation failed, failed opening session file %s: %s",
1217 filename, fr_syserror(errno));
1224 rv = write(fd, p, todo);
1226 RWDEBUG("Failed writing session: %s", fr_syserror(errno));
1234 RWDEBUG("Wrote session %s to %s (%d bytes)", buffer, filename, blob_len);
1243 static SSL_SESSION *cbtls_get_session(SSL *ssl, unsigned char *data, int len, int *copy)
1246 char buffer[2 * MAX_SESSION_SIZE + 1];
1247 fr_tls_server_conf_t *conf;
1248 TALLOC_CTX *talloc_ctx;
1250 SSL_SESSION *sess = NULL;
1251 unsigned char *sess_data = NULL;
1252 PAIR_LIST *pairlist = NULL;
1254 REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1256 rad_assert(request != NULL);
1259 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1261 fr_bin2hex(buffer, data, size);
1263 RDEBUG2("Peer requested cached session: %s", buffer);
1267 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1269 RWDEBUG("Failed to find TLS configuration in session");
1273 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1280 VALUE_PAIR *vps = NULL;
1282 /* read in the cached VPs from the .vps file */
1283 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1284 conf->session_cache_path, FR_DIR_SEP, buffer);
1285 rv = pairlist_read(talloc_ctx, filename, &pairlist, 1);
1287 /* not safe to un-persist a session w/o VPs */
1288 RWDEBUG("Failed loading persisted VPs for session %s", buffer);
1292 /* load the actual SSL session */
1293 snprintf(filename, sizeof(filename), "%s%c%s.asn1", conf->session_cache_path, FR_DIR_SEP, buffer);
1294 fd = open(filename, O_RDONLY);
1296 RWDEBUG("No persisted session file %s: %s", filename, fr_syserror(errno));
1300 rv = fstat(fd, &st);
1302 RWDEBUG("Failed stating persisted session file %s: %s", filename, fr_syserror(errno));
1307 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1309 RWDEBUG("Failed allocating buffer for persisted session (%d bytes)", (int) st.st_size);
1317 rv = read(fd, p, todo);
1319 RWDEBUG("Failed reading persisted session: %s", fr_syserror(errno));
1328 /* openssl mutates &p */
1330 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1333 RWDEBUG("Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1337 /* move the cached VPs into the session */
1338 fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &pairlist->reply, 0, 0, TAG_ANY);
1340 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
1341 RWDEBUG("Successfully restored session %s", buffer);
1342 rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
1345 if (sess_data) talloc_free(sess_data);
1346 if (pairlist) pairlist_free(&pairlist);
1351 #ifdef HAVE_OPENSSL_OCSP_H
1353 /** Extract components of OCSP responser URL from a certificate
1355 * @param[in] cert to extract URL from.
1356 * @param[out] host_out Portion of the URL (must be freed with free()).
1357 * @param[out] port_out Port portion of the URL (must be freed with free()).
1358 * @param[out] path_out Path portion of the URL (must be freed with free()).
1359 * @param[out] is_https Whether the responder should be contacted using https.
1361 * - 0 if no valid URL is contained in the certificate.
1362 * - 1 if a URL was found and parsed.
1363 * - -1 if at least one URL was found, but none could be parsed.
1365 static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out,
1366 char **path_out, int *is_https)
1369 bool found_uri = false;
1371 AUTHORITY_INFO_ACCESS *aia;
1372 ACCESS_DESCRIPTION *ad;
1374 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1376 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1377 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1378 if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
1379 if (ad->location->type != GEN_URI) continue;
1382 if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
1383 port_out, path_out, is_https)) return 1;
1385 return found_uri ? -1 : 0;
1389 * This function sends a OCSP request to a defined OCSP responder
1390 * and checks the OCSP response for correctness.
1393 /* Maximum leeway in validity period: default 5 minutes */
1394 #define MAX_VALIDITY_PERIOD (5 * 60)
1396 static int ocsp_check(REQUEST *request, X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1397 fr_tls_server_conf_t *conf)
1399 OCSP_CERTID *certid;
1401 OCSP_RESPONSE *resp = NULL;
1402 OCSP_BASICRESP *bresp = NULL;
1406 char hostheader[1024];
1408 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1409 BIO *cbio, *bio_out;
1412 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1414 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1418 struct timeval when;
1422 * Create OCSP Request
1424 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1425 req = OCSP_REQUEST_new();
1426 OCSP_request_add0_id(req, certid);
1427 if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
1430 * Send OCSP Request and get OCSP Response
1433 /* Get OCSP responder URL */
1434 if (conf->ocsp_override_url) {
1438 memcpy(&url, &conf->ocsp_url, sizeof(url));
1439 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1440 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1441 if (!host || !port || !path) {
1442 RWDEBUG("ocsp: Host or port or path missing from configured URL \"%s\". Not doing OCSP", url);
1449 ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1452 RWDEBUG("ocsp: Invalid URL in certificate. Not doing OCSP");
1456 if (conf->ocsp_url) {
1457 RWDEBUG("ocsp: No OCSP URL in certificate, falling back to configured URL");
1460 RWDEBUG("ocsp: No OCSP URL in certificate. Not doing OCSP");
1469 RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
1471 /* Check host and port length are sane, then create Host: HTTP header */
1472 if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1473 RWDEBUG("ocsp: Host and port too long");
1476 snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1478 /* Setup BIO socket to OCSP responder */
1479 cbio = BIO_new_connect(host);
1482 if (rad_debug_lvl) {
1483 if (default_log.dst == L_DST_STDOUT) {
1484 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1485 } else if (default_log.dst == L_DST_STDERR) {
1486 bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1490 BIO_set_conn_port(cbio, port);
1491 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1492 BIO_do_connect(cbio);
1494 /* Send OCSP request and wait for response */
1495 resp = OCSP_sendreq_bio(cbio, path, req);
1497 REDEBUG("ocsp: Couldn't get OCSP response");
1502 if (conf->ocsp_timeout)
1503 BIO_set_nbio(cbio, 1);
1505 rc = BIO_do_connect(cbio);
1506 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1507 REDEBUG("ocsp: Couldn't connect to OCSP responder");
1512 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1514 REDEBUG("ocsp: Couldn't create OCSP request");
1519 if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1520 REDEBUG("ocsp: Couldn't set Host header");
1525 if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1526 REDEBUG("ocsp: Couldn't add data to OCSP request");
1531 gettimeofday(&when, NULL);
1532 when.tv_sec += conf->ocsp_timeout;
1535 rc = OCSP_sendreq_nbio(&resp, ctx);
1536 if (conf->ocsp_timeout) {
1537 gettimeofday(&now, NULL);
1538 if (!timercmp(&now, &when, <))
1541 } while ((rc == -1) && BIO_should_retry(cbio));
1543 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1544 REDEBUG("ocsp: Response timed out");
1549 OCSP_REQ_CTX_free(ctx);
1552 REDEBUG("ocsp: Couldn't get OCSP response");
1558 /* Verify OCSP response status */
1559 status = OCSP_response_status(resp);
1560 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1561 REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
1564 bresp = OCSP_response_get1_basic(resp);
1565 if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1566 REDEBUG("ocsp: Response has wrong nonce value");
1569 if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1570 REDEBUG("ocsp: Couldn't verify OCSP basic response");
1574 /* Verify OCSP cert status */
1575 if (!OCSP_resp_find_status(bresp, certid, &status, &reason, &rev, &thisupd, &nextupd)) {
1576 REDEBUG("ocsp: No Status found");
1580 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1582 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1583 ERR_print_errors(bio_out);
1589 BIO_puts(bio_out, "\tThis Update: ");
1590 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1591 BIO_puts(bio_out, "\n");
1593 BIO_puts(bio_out, "\tNext Update: ");
1594 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1595 BIO_puts(bio_out, "\n");
1600 case V_OCSP_CERTSTATUS_GOOD:
1601 RDEBUG2("ocsp: Cert status: good");
1606 /* REVOKED / UNKNOWN */
1607 REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
1608 if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
1611 BIO_puts(bio_out, "\tRevocation Time: ");
1612 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1613 BIO_puts(bio_out, "\n");
1619 /* Free OCSP Stuff */
1620 OCSP_REQUEST_free(req);
1621 OCSP_RESPONSE_free(resp);
1626 if (bio_out) BIO_free(bio_out);
1627 OCSP_BASICRESP_free(bresp);
1632 RDEBUG2("ocsp: Certificate is valid");
1636 if (conf->ocsp_softfail) {
1637 RWDEBUG("ocsp: Unable to check certificate, assuming it's valid");
1638 RWDEBUG("ocsp: This may be insecure");
1641 REDEBUG("ocsp: Unable to check certificate, failing");
1647 REDEBUG("ocsp: Certificate has been expired/revoked");
1653 #endif /* HAVE_OPENSSL_OCSP_H */
1656 * For creating certificate attributes.
1658 static char const *cert_attr_names[8][2] = {
1659 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1660 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1661 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1662 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1663 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1664 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1665 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1666 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1669 #define FR_TLS_SERIAL (0)
1670 #define FR_TLS_EXPIRATION (1)
1671 #define FR_TLS_SUBJECT (2)
1672 #define FR_TLS_ISSUER (3)
1673 #define FR_TLS_CN (4)
1674 #define FR_TLS_SAN_EMAIL (5)
1675 #define FR_TLS_SAN_DNS (6)
1676 #define FR_TLS_SAN_UPN (7)
1679 * Before trusting a certificate, you must make sure that the
1680 * certificate is 'valid'. There are several steps that your
1681 * application can take in determining if a certificate is
1682 * valid. Commonly used steps are:
1684 * 1.Verifying the certificate's signature, and verifying that
1685 * the certificate has been issued by a trusted Certificate
1688 * 2.Verifying that the certificate is valid for the present date
1689 * (i.e. it is being presented within its validity dates).
1691 * 3.Verifying that the certificate has not been revoked by its
1692 * issuing Certificate Authority, by checking with respect to a
1693 * Certificate Revocation List (CRL).
1695 * 4.Verifying that the credentials presented by the certificate
1696 * fulfill additional requirements specific to the application,
1697 * such as with respect to access control lists or with respect
1698 * to OCSP (Online Certificate Status Processing).
1700 * NOTE: This callback will be called multiple times based on the
1701 * depth of the root certificate chain
1703 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1705 char subject[1024]; /* Used for the subject name */
1706 char issuer[1024]; /* Used for the issuer name */
1707 char attribute[1024];
1709 char common_name[1024];
1713 X509_CINF *client_inf;
1714 STACK_OF(X509_EXTENSION) *ext_list;
1716 int err, depth, lookup, loc;
1717 fr_tls_server_conf_t *conf;
1720 ASN1_INTEGER *sn = NULL;
1721 ASN1_TIME *asn_time = NULL;
1724 #ifdef HAVE_OPENSSL_OCSP_H
1725 X509_STORE *ocsp_store = NULL;
1729 TALLOC_CTX *talloc_ctx;
1733 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1734 err = X509_STORE_CTX_get_error(ctx);
1735 depth = X509_STORE_CTX_get_error_depth(ctx);
1740 * Log client/issuing cert. If there's an error, log
1743 if ((lookup > 1) && !my_ok) lookup = 1;
1746 * Retrieve the pointer to the SSL of the connection currently treated
1747 * and the application specific data stored into the SSL object.
1749 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1750 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1751 if (!conf) return 1;
1753 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1754 rad_assert(request != NULL);
1755 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1757 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1758 #ifdef HAVE_OPENSSL_OCSP_H
1759 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1762 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1765 * Get the Serial Number
1768 sn = X509_get_serialNumber(client_cert);
1770 RDEBUG2("Creating attributes from certificate OIDs");
1774 * For this next bit, we create the attributes *only* if
1775 * we're at the client or issuing certificate, AND we
1776 * have a user identity. i.e. we don't create the
1777 * attributes for RadSec connections.
1779 if (certs && identity &&
1780 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1784 for (i = 0; i < sn->length; i++) {
1785 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1788 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1789 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1794 * Get the Expiration Date
1797 asn_time = X509_get_notAfter(client_cert);
1798 if (certs && identity && (lookup <= 1) && asn_time &&
1799 (asn_time->length < (int) sizeof(buf))) {
1800 memcpy(buf, (char*) asn_time->data, asn_time->length);
1801 buf[asn_time->length] = '\0';
1802 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1803 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1807 * Get the Subject & Issuer
1809 subject[0] = issuer[0] = '\0';
1810 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1812 subject[sizeof(subject) - 1] = '\0';
1813 if (certs && identity && (lookup <= 1) && subject[0]) {
1814 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1815 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1818 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1820 issuer[sizeof(issuer) - 1] = '\0';
1821 if (certs && identity && (lookup <= 1) && issuer[0]) {
1822 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1823 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1827 * Get the Common Name, if there is a subject.
1829 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1830 NID_commonName, common_name, sizeof(common_name));
1831 common_name[sizeof(common_name) - 1] = '\0';
1832 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1833 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1834 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1838 * Get the RFC822 Subject Alternative Name
1840 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1841 if (certs && (lookup <= 1) && (loc >= 0)) {
1842 X509_EXTENSION *ext = NULL;
1843 GENERAL_NAMES *names = NULL;
1846 if ((ext = X509_get_ext(client_cert, loc)) &&
1847 (names = X509V3_EXT_d2i(ext))) {
1848 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1849 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1851 switch (name->type) {
1854 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1855 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1856 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1858 #endif /* GEN_EMAIL */
1861 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1862 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1863 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1865 #endif /* GEN_DNS */
1866 #ifdef GEN_OTHERNAME
1868 /* look for a MS UPN */
1869 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1870 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1871 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1872 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1873 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1874 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1877 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
1882 #endif /* GEN_OTHERNAME */
1884 /* XXX TODO handle other SAN types */
1890 sk_GENERAL_NAME_free(names);
1894 * If the CRL has expired, that might still be OK.
1897 (conf->allow_expired_crl) &&
1898 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1900 X509_STORE_CTX_set_error( ctx, 0 );
1904 char const *p = X509_verify_cert_error_string(err);
1905 RERROR("SSL says error %d : %s", err, p);
1911 client_inf = client_cert->cert_info;
1912 ext_list = client_inf->extensions;
1918 * Grab the X509 extensions, and create attributes out of them.
1919 * For laziness, we re-use the OpenSSL names
1921 if (certs && (sk_X509_EXTENSION_num(ext_list) > 0)) {
1926 out = BIO_new(BIO_s_mem());
1927 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1929 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1931 X509_EXTENSION *ext;
1933 ext = sk_X509_EXTENSION_value(ext_list, i);
1935 obj = X509_EXTENSION_get_object(ext);
1936 i2a_ASN1_OBJECT(out, obj);
1937 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1938 if (len <= 0) continue;
1940 attribute[16 + len] = '\0';
1942 for (p = attribute + 16; *p != '\0'; p++) {
1943 if (*p == ' ') *p = '-';
1946 X509V3_EXT_print(out, ext, 0, 0);
1947 len = BIO_read(out, value , sizeof(value) - 1);
1948 if (len <= 0) continue;
1952 vp = fr_pair_make(talloc_ctx, certs, attribute, value, T_OP_ADD);
1954 RDEBUG3("Skipping %s += '%s'. Please check that both the "
1955 "attribute and value are defined in the dictionaries",
1959 * rdebug_pair_list indents (so pre REXDENT())
1962 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
1972 switch (ctx->error) {
1973 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1974 RERROR("issuer=%s", issuer);
1977 case X509_V_ERR_CERT_NOT_YET_VALID:
1978 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1979 RERROR("notBefore=");
1981 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1985 case X509_V_ERR_CERT_HAS_EXPIRED:
1986 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1987 RERROR("notAfter=");
1989 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1995 * If we're at the actual client cert, apply additional
2000 * If the conf tells us to, check cert issuer
2001 * against the specified value and fail
2002 * verification if they don't match.
2004 if (conf->check_cert_issuer &&
2005 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
2006 AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
2007 issuer, conf->check_cert_issuer);
2012 * If the conf tells us to, check the CN in the
2013 * cert against xlat'ed value, but only if the
2014 * previous checks passed.
2016 if (my_ok && conf->check_cert_cn) {
2017 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
2018 /* if this fails, fail the verification */
2021 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
2022 if (strcmp(cn_str, common_name) != 0) {
2023 AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
2024 common_name, cn_str);
2028 } /* check_cert_cn */
2030 #ifdef HAVE_OPENSSL_OCSP_H
2031 if (my_ok && conf->ocsp_enable){
2032 RDEBUG2("Starting OCSP Request");
2033 if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
2034 RERROR("Couldn't get issuer_cert for %s", common_name);
2036 my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
2041 while (conf->verify_client_cert_cmd) {
2046 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
2047 conf->verify_tmp_dir, progname);
2048 fd = mkstemp(filename);
2050 RDEBUG("Failed creating file in %s: %s",
2051 conf->verify_tmp_dir, fr_syserror(errno));
2055 fp = fdopen(fd, "w");
2058 RDEBUG("Failed opening file %s: %s",
2059 filename, fr_syserror(errno));
2063 if (!PEM_write_X509(fp, client_cert)) {
2065 RDEBUG("Failed writing certificate to file");
2070 if (!pair_make_request("TLS-Client-Cert-Filename",
2071 filename, T_OP_SET)) {
2072 RDEBUG("Failed creating TLS-Client-Cert-Filename");
2077 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2078 if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2079 request->packet->vps,
2080 true, true, EXEC_TIMEOUT) != 0) {
2081 AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
2084 RDEBUG("Client certificate CN %s passed external validation", common_name);
2095 if (RDEBUG_ENABLED3) {
2096 RDEBUG3("chain-depth : %d", depth);
2097 RDEBUG3("error : %d", err);
2099 if (identity) RDEBUG3("identity : %s", *identity);
2100 RDEBUG3("common name : %s", common_name);
2101 RDEBUG3("subject : %s", subject);
2102 RDEBUG3("issuer : %s", issuer);
2103 RDEBUG3("verify return : %d", my_ok);
2109 #ifdef HAVE_OPENSSL_OCSP_H
2111 * Create Global X509 revocation store and use it to verify
2114 * - Load the trusted CAs
2115 * - Load the trusted issuer certificates
2117 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2119 X509_STORE *store = NULL;
2121 store = X509_STORE_new();
2123 /* Load the CAs we trust */
2124 if (conf->ca_file || conf->ca_path)
2125 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2126 ERROR(LOG_PREFIX ": X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
2127 ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file );
2131 #ifdef X509_V_FLAG_CRL_CHECK
2132 if (conf->check_crl)
2133 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2135 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2136 if (conf->check_all_crl)
2137 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
2141 #endif /* HAVE_OPENSSL_OCSP_H */
2143 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2144 #ifndef OPENSSL_NO_ECDH
2145 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
2150 if (!ecdh_curve || !*ecdh_curve) return 0;
2152 nid = OBJ_sn2nid(ecdh_curve);
2154 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
2158 ecdh = EC_KEY_new_by_curve_name(nid);
2160 ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
2164 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2166 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2176 * DIE OPENSSL DIE DIE DIE
2178 * What a palaver, just to free some data attached the
2179 * session. We need to do this because the "remove" callback
2180 * is called when refcount > 0 sometimes, if another thread
2181 * is using the session
2183 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2184 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2185 UNUSED long argl, UNUSED void *argp)
2187 VALUE_PAIR *vp = data_ptr;
2190 DEBUG2(LOG_PREFIX ": Freeing cached session VPs");
2192 fr_pair_list_free(&vp);
2195 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2196 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2197 UNUSED long argl, UNUSED void *argp)
2199 VALUE_PAIR **certs = data_ptr;
2202 DEBUG2(LOG_PREFIX ": Freeing cached session Certificates");
2204 fr_pair_list_free(certs);
2207 /** Add all the default ciphers and message digests reate our context.
2209 * This should be called exactly once from main, before reading the main config
2210 * or initialising any modules.
2212 void tls_global_init(void)
2214 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
2215 SSL_library_init(); /* initialize library */
2216 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2217 OPENSSL_config(NULL);
2220 * Initialize the index for the certificates.
2222 fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2225 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2226 /** Check for vulnerable versions of libssl
2228 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2229 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2231 int tls_global_version_check(char const *acknowledged)
2235 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2239 /* Check for bad versions */
2240 v = (uint64_t) SSLeay();
2242 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2243 libssl_defect_t *defect = &libssl_defects[i];
2245 if ((v >= defect->low) && (v <= defect->high)) {
2246 ERROR("Refusing to start with libssl version %s (in range %s)",
2247 ssl_version(), ssl_version_range(defect->low, defect->high));
2248 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2249 ERROR("%s", defect->comment);
2256 INFO("Once you have verified libssl has been correctly patched, "
2257 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2266 /** Free any memory alloced by libssl
2269 void tls_global_cleanup(void)
2271 ERR_remove_state(0);
2273 CONF_modules_unload(1);
2276 CRYPTO_cleanup_all_ex_data();
2279 /** Create SSL context
2281 * - Load the trusted CAs
2282 * - Load the Private key & the certificate
2283 * - Set the Context options & Verify options
2285 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2288 X509_STORE *certstore;
2289 int verify_mode = SSL_VERIFY_NONE;
2290 int ctx_options = 0;
2291 int ctx_tls_versions = 0;
2295 * SHA256 is in all versions of OpenSSL, but isn't
2296 * initialized by default. It's needed for WiMAX
2299 #ifdef HAVE_OPENSSL_EVP_SHA256
2300 EVP_add_digest(EVP_sha256());
2303 ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
2306 while ((err = ERR_get_error())) {
2307 ERROR(LOG_PREFIX ": Failed creating SSL context: %s", ERR_error_string(err, NULL));
2313 * Save the config on the context so that callbacks which
2314 * only get SSL_CTX* e.g. session persistence, can get it
2316 SSL_CTX_set_app_data(ctx, conf);
2319 * Identify the type of certificates that needs to be loaded
2321 if (conf->file_type) {
2322 type = SSL_FILETYPE_PEM;
2324 type = SSL_FILETYPE_ASN1;
2328 * Set the password to load private key
2330 if (conf->private_key_password) {
2333 * We don't want to put the private key password in eap.conf, so check
2334 * for our special string which indicates we should get the password
2337 char const* special_string = "Apple:UseCertAdmin";
2338 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2341 long const max_password_len = 128;
2342 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2343 conf->private_key_file);
2345 DEBUG2(LOG_PREFIX ": Getting private key passphrase using command \"%s\"", cmd);
2347 FILE* cmd_pipe = popen(cmd, "r");
2349 ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
2350 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2354 rad_const_free(conf->private_key_password);
2355 password = talloc_array(conf, char, max_password_len);
2357 ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
2358 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2363 fgets(password, max_password_len, cmd_pipe);
2366 /* Get rid of newline at end of password. */
2367 password[strlen(password) - 1] = '\0';
2369 DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
2370 conf->private_key_password = password;
2377 memcpy(&password, &conf->private_key_password, sizeof(password));
2378 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2379 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2383 #ifdef PSK_MAX_IDENTITY_LEN
2386 * No dynamic query exists. There MUST be a
2387 * statically configured identity and password.
2389 if (conf->psk_query && !*conf->psk_query) {
2390 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
2395 * Set the callback only if we can check things.
2397 if (conf->psk_identity || conf->psk_query) {
2398 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2401 } else if (conf->psk_query) {
2402 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2407 * Now check that if PSK is being used, the config is valid.
2409 if ((conf->psk_identity && !conf->psk_password) ||
2410 (!conf->psk_identity && conf->psk_password) ||
2411 (conf->psk_identity && !*conf->psk_identity) ||
2412 (conf->psk_password && !*conf->psk_password)) {
2413 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
2417 if (conf->psk_identity) {
2418 size_t psk_len, hex_len;
2419 uint8_t buffer[PSK_MAX_PSK_LEN];
2421 if (conf->certificate_file ||
2422 conf->private_key_password || conf->private_key_file ||
2423 conf->ca_file || conf->ca_path) {
2424 ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
2429 SSL_CTX_set_psk_client_callback(ctx,
2430 psk_client_callback);
2433 psk_len = strlen(conf->psk_password);
2434 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2435 ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
2440 * Check the password now, so that we don't have
2441 * errors at run-time.
2443 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2444 if (psk_len != (2 * hex_len)) {
2445 ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
2452 (void) client; /* -Wunused */
2456 * Load our keys and certificates
2458 * If certificates are of type PEM then we can make use
2459 * of cert chain authentication using openssl api call
2460 * SSL_CTX_use_certificate_chain_file. Please see how
2461 * the cert chain needs to be given in PEM from
2464 if (!conf->certificate_file) goto load_ca;
2466 if (type == SSL_FILETYPE_PEM) {
2467 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2468 ERROR(LOG_PREFIX ": Error reading certificate file %s:%s", conf->certificate_file,
2469 ERR_error_string(ERR_get_error(), NULL));
2473 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2474 ERROR(LOG_PREFIX ": Error reading certificate file %s:%s",
2475 conf->certificate_file,
2476 ERR_error_string(ERR_get_error(), NULL));
2480 /* Load the CAs we trust */
2482 if (conf->ca_file || conf->ca_path) {
2483 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2484 ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2485 ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file );
2489 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2491 if (conf->private_key_file) {
2492 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2493 ERROR(LOG_PREFIX ": Failed reading private key file %s:%s",
2494 conf->private_key_file,
2495 ERR_error_string(ERR_get_error(), NULL));
2500 * Check if the loaded private key is the right one
2502 if (!SSL_CTX_check_private_key(ctx)) {
2503 ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
2508 #ifdef PSK_MAX_IDENTITY_LEN
2513 * We never want SSLv2 or SSLv3.
2515 ctx_options |= SSL_OP_NO_SSLv2;
2516 ctx_options |= SSL_OP_NO_SSLv3;
2519 * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2520 * Though they can be *globally* disabled if necessary.x
2522 #ifdef SSL_OP_NO_TLSv1
2523 if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
2525 ctx_tls_versions |= SSL_OP_NO_TLSv1;
2527 #ifdef SSL_OP_NO_TLSv1_1
2528 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2530 ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
2532 #ifdef SSL_OP_NO_TLSv1_2
2533 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2535 ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
2538 if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
2539 ERROR(LOG_PREFIX ": You have disabled all available TLS versions. EAP will not work");
2543 #ifdef SSL_OP_NO_TICKET
2544 ctx_options |= SSL_OP_NO_TICKET;
2548 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2549 * small subgroup attacks and forward secrecy. Always
2552 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2553 * time needed during negotiation, but it is not very
2556 ctx_options |= SSL_OP_SINGLE_DH_USE;
2559 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2560 * in Windows Vista client.
2561 * http://www.openssl.org/~bodo/tls-cbc.txt
2562 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2564 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2566 SSL_CTX_set_options(ctx, ctx_options);
2569 * TODO: Set the RSA & DH
2570 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2571 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2575 * set the message callback to identify the type of
2576 * message. For every new session, there can be a
2577 * different callback argument.
2579 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2583 * Set eliptical curve crypto configuration.
2585 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2586 #ifndef OPENSSL_NO_ECDH
2587 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2593 /* Set Info callback */
2594 SSL_CTX_set_info_callback(ctx, cbtls_info);
2597 * Callbacks, etc. for session resumption.
2599 if (conf->session_cache_enable) {
2601 * Cache sessions on disk if requested.
2603 if (conf->session_cache_path) {
2604 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2605 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2606 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2609 SSL_CTX_set_quiet_shutdown(ctx, 1);
2610 if (fr_tls_ex_index_vps < 0)
2611 fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2615 * Check the certificates for revocation.
2617 #ifdef X509_V_FLAG_CRL_CHECK
2618 if (conf->check_crl) {
2619 certstore = SSL_CTX_get_cert_store(ctx);
2620 if (certstore == NULL) {
2621 ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2622 ERROR(LOG_PREFIX ": Error reading Certificate Store");
2625 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2627 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2628 if (conf->check_all_crl)
2629 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
2636 * Always verify the peer certificate
2638 verify_mode |= SSL_VERIFY_PEER;
2639 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2640 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2641 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2643 if (conf->verify_depth) {
2644 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2647 /* Load randomness */
2648 if (conf->random_file) {
2649 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2650 ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2651 ERROR(LOG_PREFIX ": Error loading randomness");
2657 * Set the cipher list if we were told to
2659 if (conf->cipher_list) {
2660 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2661 ERROR(LOG_PREFIX ": Error setting cipher list");
2667 * Setup session caching
2669 if (conf->session_cache_enable) {
2671 * Create a unique context Id per EAP-TLS configuration.
2673 if (conf->session_id_name) {
2674 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2675 "FR eap %s", conf->session_id_name);
2677 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2682 * Cache it, and DON'T auto-clear it.
2684 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2686 SSL_CTX_set_session_id_context(ctx,
2687 (unsigned char *) conf->session_context_id,
2688 (unsigned int) strlen(conf->session_context_id));
2691 * Our timeout is in hours, this is in seconds.
2693 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2696 * Set the maximum number of entries in the
2699 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2702 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2710 * Free TLS client/server config
2711 * Should not be called outside this code, as a callback is
2712 * added to automatically free the data when the CONF_SECTION
2715 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2717 if (conf->ctx) SSL_CTX_free(conf->ctx);
2719 #ifdef HAVE_OPENSSL_OCSP_H
2720 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2721 conf->ocsp_store = NULL;
2725 memset(conf, 0, sizeof(*conf));
2730 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2732 fr_tls_server_conf_t *conf;
2734 conf = talloc_zero(ctx, fr_tls_server_conf_t);
2736 ERROR(LOG_PREFIX ": Out of memory");
2740 talloc_set_destructor(conf, _tls_server_conf_free);
2745 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2747 fr_tls_server_conf_t *conf;
2750 * If cs has already been parsed there should be a cached copy
2751 * of conf already stored, so just return that.
2753 conf = cf_data_find(cs, "tls-conf");
2755 DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
2759 conf = tls_server_conf_alloc(cs);
2761 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2768 * Save people from their own stupidity.
2770 if (conf->fragment_size < 100) conf->fragment_size = 100;
2772 if (!conf->private_key_file) {
2773 ERROR(LOG_PREFIX ": TLS Server requires a private key file");
2777 if (!conf->certificate_file) {
2778 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
2785 conf->ctx = tls_init_ctx(conf, 0);
2786 if (conf->ctx == NULL) {
2790 #ifdef HAVE_OPENSSL_OCSP_H
2792 * Initialize OCSP Revocation Store
2794 if (conf->ocsp_enable) {
2795 conf->ocsp_store = init_revocation_store(conf);
2796 if (conf->ocsp_store == NULL) goto error;
2798 #endif /*HAVE_OPENSSL_OCSP_H*/
2802 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2803 if (load_dh_params(conf->ctx, dh_file) < 0) {
2808 if (conf->verify_tmp_dir) {
2809 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2810 ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
2811 conf->verify_tmp_dir, fr_syserror(errno));
2816 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2817 ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
2822 * Cache conf in cs in case we're asked to parse this again.
2824 cf_data_add(cs, "tls-conf", conf, NULL);
2829 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2831 fr_tls_server_conf_t *conf;
2833 conf = cf_data_find(cs, "tls-conf");
2835 DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
2839 conf = tls_server_conf_alloc(cs);
2841 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2848 * Save people from their own stupidity.
2850 if (conf->fragment_size < 100) conf->fragment_size = 100;
2855 conf->ctx = tls_init_ctx(conf, 1);
2856 if (conf->ctx == NULL) {
2863 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2864 if (load_dh_params(conf->ctx, dh_file) < 0) {
2869 cf_data_add(cs, "tls-conf", conf, NULL);
2874 int tls_success(tls_session_t *ssn, REQUEST *request)
2876 VALUE_PAIR *vp, *vps = NULL;
2877 fr_tls_server_conf_t *conf;
2878 TALLOC_CTX *talloc_ctx;
2880 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2881 rad_assert(conf != NULL);
2883 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2886 * If there's no session resumption, delete the entry
2887 * from the cache. This means either it's disabled
2888 * globally for this SSL context, OR we were told to
2889 * disable it for this user.
2891 * This also means you can't turn it on just for one
2894 if ((!ssn->allow_session_resumption) ||
2895 (((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
2896 (vp->vp_integer == 0))) {
2897 SSL_CTX_remove_session(ssn->ctx,
2899 ssn->allow_session_resumption = false;
2902 * If we're in a resumed session and it's
2905 if (SSL_session_reused(ssn->ssl)) {
2906 RDEBUG("Forcibly stopping session resumption as it is not allowed");
2911 * Else resumption IS allowed, so we store the
2912 * user data in the cache.
2914 } else if (!SSL_session_reused(ssn->ssl)) {
2917 char buffer[2 * MAX_SESSION_SIZE + 1];
2919 size = ssn->ssl->session->session_id_length;
2920 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2922 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2924 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2925 if (vp) fr_pair_add(&vps, vp);
2927 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2928 if (vp) fr_pair_add(&vps, vp);
2930 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
2931 if (vp) fr_pair_add(&vps, vp);
2933 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2934 if (vp) fr_pair_add(&vps, vp);
2936 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2937 if (vp) fr_pair_add(&vps, vp);
2939 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
2942 * Hmm... the certs should probably be session data.
2946 * @todo: some go into reply, others into
2949 fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
2952 * Save the certs in the packet, so that we can see them.
2954 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
2958 SSL_SESSION_set_ex_data(ssn->ssl->session, fr_tls_ex_index_vps, vps);
2959 rdebug_pair_list(L_DBG_LVL_2, request, vps, " caching ");
2961 if (conf->session_cache_path) {
2962 /* write the VPs to the cache file */
2963 char filename[256], buf[1024];
2966 RDEBUG2("Saving session %s in the disk cache", buffer);
2968 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
2969 FR_DIR_SEP, buffer);
2970 vp_file = fopen(filename, "w");
2971 if (vp_file == NULL) {
2972 RWDEBUG("Could not write session VPs to persistent cache: %s",
2973 fr_syserror(errno));
2975 VALUE_PAIR *prev = NULL;
2977 /* generate a dummy user-style entry which is easy to read back */
2978 fprintf(vp_file, "# SSL cached session\n");
2979 fprintf(vp_file, "%s\n\t", buffer);
2981 for (vp = fr_cursor_init(&cursor, &vps);
2983 vp = fr_cursor_next(&cursor)) {
2985 * Terminate the previous line.
2987 if (prev) fprintf(vp_file, ",\n\t");
2992 vp_prints(buf, sizeof(buf), vp);
2993 fputs(buf, vp_file);
2998 * Terminate the final line.
3000 fprintf(vp_file, "\n");
3004 RDEBUG("Failed to find 'persist_dir' in TLS configuration. Session will not be cached on disk.");
3007 RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
3008 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
3012 * Else the session WAS allowed. Copy the cached reply.
3016 char buffer[2 * MAX_SESSION_SIZE + 1];
3018 size = ssn->ssl->session->session_id_length;
3019 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
3021 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
3024 * The "restore VPs from OpenSSL cache" code is
3025 * now in eaptls_process()
3028 if (conf->session_cache_path) {
3029 /* "touch" the cached session/vp file */
3032 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
3033 conf->session_cache_path, FR_DIR_SEP, buffer);
3034 utime(filename, NULL);
3035 snprintf(filename, sizeof(filename), "%s%c%s.vps",
3036 conf->session_cache_path, FR_DIR_SEP, buffer);
3037 utime(filename, NULL);
3041 * Mark the request as resumed.
3043 pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
3050 void tls_fail(tls_session_t *ssn)
3053 * Force the session to NOT be cached.
3055 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
3058 fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
3065 * Decrypt the complete record.
3067 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
3068 ssn->dirty_in.used);
3069 if (err != (int) ssn->dirty_in.used) {
3070 record_init(&ssn->dirty_in);
3071 RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
3076 * Clear the dirty buffer now that we are done with it
3077 * and init the clean_out buffer to store decrypted data
3079 record_init(&ssn->dirty_in);
3080 record_init(&ssn->clean_out);
3083 * Read (and decrypt) the tunneled data from the
3084 * SSL session, and put it into the decrypted
3087 err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
3091 RDEBUG("SSL_read Error");
3093 code = SSL_get_error(ssn->ssl, err);
3095 case SSL_ERROR_WANT_READ:
3096 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
3097 return FR_TLS_MORE_FRAGMENTS;
3099 case SSL_ERROR_WANT_WRITE:
3100 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
3104 DEBUG("Error in fragmentation logic: %s", ERR_error_string(code, NULL));
3107 * FIXME: Call int_ssl_check?
3114 if (err == 0) RWDEBUG("No data inside of the tunnel");
3117 * Passed all checks, successfully decrypted data
3119 ssn->clean_out.used = err;
3122 * Add the certificates to intermediate packets, so that
3123 * the inner tunnel policies can use them.
3125 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3127 if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3134 * Acknowledge received is for one of the following messages sent earlier
3135 * 1. Handshake completed Message, so now send, EAP-Success
3136 * 2. Alert Message, now send, EAP-Failure
3137 * 3. Fragment Message, now send, next Fragment
3139 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
3142 REDEBUG("Unexpected ACK received: No ongoing SSL session");
3143 return FR_TLS_INVALID;
3145 if (!ssn->info.initialized) {
3146 RDEBUG("No SSL info available. Waiting for more SSL data");
3147 return FR_TLS_REQUEST;
3150 if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3151 REDEBUG("Unexpected ACK received: We sent no previous messages");
3152 return FR_TLS_INVALID;
3155 switch (ssn->info.content_type) {
3157 RDEBUG2("Peer ACKed our alert");
3161 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3162 RDEBUG2("Peer ACKed our handshake fragment. handshake is finished");
3165 * From now on all the content is
3166 * application data set it here as nobody else
3169 ssn->info.content_type = application_data;
3170 return FR_TLS_SUCCESS;
3171 } /* else more data to send */
3173 RDEBUG2("Peer ACKed our handshake fragment");
3174 /* Fragmentation handler, send next fragment */
3175 return FR_TLS_REQUEST;
3177 case application_data:
3178 RDEBUG2("Peer ACKed our application data fragment");
3179 return FR_TLS_REQUEST;
3182 * For the rest of the conditions, switch over
3183 * to the default section below.
3186 REDEBUG("Invalid ACK received: %d", ssn->info.content_type);
3187 return FR_TLS_INVALID;
3190 #endif /* WITH_TLS */