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
45 #ifdef HAVE_OPENSSL_RAND_H
46 #include <openssl/rand.h>
49 #ifdef HAVE_OPENSSL_OCSP_H
50 #include <openssl/ocsp.h>
53 typedef struct libssl_defect {
62 /* Record critical defects in libssl here (newest first)*/
63 static libssl_defect_t libssl_defects[] =
66 .low = 0x010001000, /* 1.0.1 */
67 .high = 0x01000106f, /* 1.0.1f */
68 .id = "CVE-2014-0160",
70 .comment = "For more information see http://heartbleed.com"
75 static void record_init(record_t *buf);
76 static void record_close(record_t *buf);
77 static unsigned int record_plus(record_t *buf, void const *ptr,
79 static unsigned int record_minus(record_t *buf, void *ptr,
82 #ifdef PSK_MAX_IDENTITY_LEN
83 static unsigned int psk_server_callback(SSL *ssl, char const *identity,
85 unsigned int max_psk_len)
88 fr_tls_server_conf_t *conf;
90 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
91 FR_TLS_EX_INDEX_CONF);
95 * FIXME: Look up the PSK password based on the identity!
97 if (strcmp(identity, conf->psk_identity) != 0) {
101 psk_len = strlen(conf->psk_password);
102 if (psk_len > (2 * max_psk_len)) return 0;
104 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
107 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
108 char *identity, unsigned int max_identity_len,
109 unsigned char *psk, unsigned int max_psk_len)
111 unsigned int psk_len;
112 fr_tls_server_conf_t *conf;
114 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
115 FR_TLS_EX_INDEX_CONF);
118 psk_len = strlen(conf->psk_password);
119 if (psk_len > (2 * max_psk_len)) return 0;
121 strlcpy(identity, conf->psk_identity, max_identity_len);
123 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
128 tls_session_t *tls_new_client_session(fr_tls_server_conf_t *conf, int fd)
131 tls_session_t *ssn = NULL;
134 ssn = talloc_zero(conf, tls_session_t);
135 if (!ssn) return NULL;
137 ssn->ctx = conf->ctx;
139 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
141 ssn->ssl = SSL_new(ssn->ctx);
147 request = request_alloc(ssn);
148 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
151 * Add the message callback to identify what type of
152 * message/handshake is passed
154 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
155 SSL_set_msg_callback_arg(ssn->ssl, ssn);
156 SSL_set_info_callback(ssn->ssl, cbtls_info);
159 * Always verify the peer certificate.
161 DEBUG2("Requiring Server certificate");
162 verify_mode = SSL_VERIFY_PEER;
163 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
164 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
166 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
167 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
168 SSL_set_fd(ssn->ssl, fd);
169 if (SSL_connect(ssn->ssl) <= 0) {
171 while ((err = ERR_get_error())) {
172 ERROR("tls: %s", ERR_error_string(err, NULL));
180 ssn->offset = conf->fragment_size;
185 static int _tls_session_free(tls_session_t *ssn)
188 * Free any opaque TTLS or PEAP data.
190 if ((ssn->opaque) && (ssn->free_opaque)) {
191 ssn->free_opaque(ssn->opaque);
200 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
202 tls_session_t *state = NULL;
207 rad_assert(request != NULL);
210 * Manually flush the sessions every so often. If HALF
211 * of the session lifetime has passed since we last
212 * flushed, then flush it again.
214 * FIXME: Also do it every N sessions?
216 if (conf->session_cache_enable &&
217 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
218 RDEBUG2("Flushing SSL sessions (of #%ld)",
219 SSL_CTX_sess_number(conf->ctx));
221 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
222 conf->session_last_flushed = request->timestamp;
225 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
226 ERROR("SSL: Error creating new SSL: %s",
227 ERR_error_string(ERR_get_error(), NULL));
231 /* We use the SSL's "app_data" to indicate a call-back */
232 SSL_set_app_data(new_tls, NULL);
234 state = talloc_zero(ctx, tls_session_t);
236 talloc_set_destructor(state, _tls_session_free);
238 state->ctx = conf->ctx;
239 state->ssl = new_tls;
242 * Initialize callbacks
244 state->record_init = record_init;
245 state->record_close = record_close;
246 state->record_plus = record_plus;
247 state->record_minus = record_minus;
250 * Create & hook the BIOs to handle the dirty side of the
251 * SSL. This is *very important* as we want to handle
252 * the transmission part. Now the only IO interface
253 * that SSL is aware of, is our defined BIO buffers.
255 * This means that all SSL IO is done to/from memory,
256 * and we can update those BIOs from the packets we've
259 state->into_ssl = BIO_new(BIO_s_mem());
260 state->from_ssl = BIO_new(BIO_s_mem());
261 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
264 * Add the message callback to identify what type of
265 * message/handshake is passed
267 SSL_set_msg_callback(new_tls, cbtls_msg);
268 SSL_set_msg_callback_arg(new_tls, state);
269 SSL_set_info_callback(new_tls, cbtls_info);
272 * In Server mode we only accept.
274 SSL_set_accept_state(state->ssl);
277 * Verify the peer certificate, if asked.
280 RDEBUG2("Requiring client certificate");
281 verify_mode = SSL_VERIFY_PEER;
282 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
283 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
285 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
287 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
288 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
289 state->length_flag = conf->include_length;
292 * We use default fragment size, unless the Framed-MTU
293 * tells us it's too big. Note that we do NOT account
294 * for the EAP-TLS headers if conf->fragment_size is
295 * large, because that config item looks to be confusing.
297 * i.e. it should REALLY be called MTU, and the code here
298 * should figure out what that means for TLS fragment size.
299 * asking the administrator to know the internal details
300 * of EAP-TLS in order to calculate fragment sizes is
303 state->offset = conf->fragment_size;
304 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
305 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
306 state->offset = vp->vp_integer;
309 if (conf->session_cache_enable) {
310 state->allow_session_resumption = 1; /* otherwise it's zero */
319 * Print out some text describing the error.
321 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
326 if ((l = ERR_get_error()) != 0) {
327 char const *p = ERR_error_string(l, NULL);
329 if (request && p) REDEBUG("SSL says: %s", p);
331 e = SSL_get_error(s, ret);
335 * These seem to be harmless and already "dealt
336 * with" by our non-blocking environment. NB:
337 * "ZERO_RETURN" is the clean "error"
338 * indicating a successfully closed SSL
339 * tunnel. We let this happen because our IO
340 * loop should not appear to have broken on
341 * this condition - and outside the IO loop, the
342 * "shutdown" state is checked.
344 * Don't print anything if we ignore the error.
347 case SSL_ERROR_WANT_READ:
348 case SSL_ERROR_WANT_WRITE:
349 case SSL_ERROR_WANT_X509_LOOKUP:
350 case SSL_ERROR_ZERO_RETURN:
354 * These seem to be indications of a genuine
355 * error that should result in the SSL tunnel
356 * being regarded as "dead".
358 case SSL_ERROR_SYSCALL:
359 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
364 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
370 * For any other errors that (a) exist, and (b)
371 * crop up - we need to interpret what to do with
372 * them - so "politely inform" the caller that
373 * the code needs updating here.
375 ERROR("SSL: FATAL SSL error ..... %d\n", e);
383 * We are the server, we always get the dirty data
384 * (Handshake data is also considered as dirty data)
385 * During handshake, since SSL API handles itself,
386 * After clean-up, dirty_out will be filled with
387 * the data required for handshaking. So we check
388 * if dirty_out is empty then we simply send it back.
389 * As of now, if handshake is successful, then we keep going,
392 * Fill the Bio with the dirty data to clean it
393 * Get the cleaned data from SSL, if it is not Handshake data
395 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
399 if (ssn->invalid_hb_used) return 0;
401 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
402 if (err != (int) ssn->dirty_in.used) {
403 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
405 record_init(&ssn->dirty_in);
408 record_init(&ssn->dirty_in);
410 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
411 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
413 ssn->clean_out.used += err;
417 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
421 /* Some Extra STATE information for easy debugging */
422 if (SSL_is_init_finished(ssn->ssl)) {
423 DEBUG2("SSL Connection Established\n");
425 if (SSL_in_init(ssn->ssl)) {
426 DEBUG2("In SSL Handshake Phase\n");
428 if (SSL_in_before(ssn->ssl)) {
429 DEBUG2("Before SSL Handshake Phase\n");
431 if (SSL_in_accept_init(ssn->ssl)) {
432 DEBUG2("In SSL Accept mode \n");
434 if (SSL_in_connect_init(ssn->ssl)) {
435 DEBUG2("In SSL Connect mode \n");
438 err = BIO_ctrl_pending(ssn->from_ssl);
440 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
441 sizeof(ssn->dirty_out.data));
443 ssn->dirty_out.used = err;
445 } else if (BIO_should_retry(ssn->from_ssl)) {
446 record_init(&ssn->dirty_in);
447 DEBUG2(" tls: Asking for more data in tunnel");
451 int_ssl_check(request, ssn->ssl, err, "BIO_read");
452 record_init(&ssn->dirty_in);
456 DEBUG2("SSL Application Data");
457 /* Its clean application data, do whatever we want */
458 record_init(&ssn->clean_out);
461 /* We are done with dirty_in, reinitialize it */
462 record_init(&ssn->dirty_in);
467 * Take cleartext user data, and encrypt it into the output buffer,
468 * to send to the client at the other end of the SSL connection.
470 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
475 * If there's un-encrypted data in 'clean_in', then write
476 * that data to the SSL session, and then call the BIO function
477 * to get that encrypted data from the SSL session, into
478 * a buffer which we can then package into an EAP packet.
480 * Based on Server's logic this clean_in is expected to
481 * contain the data to send to the client.
483 if (ssn->clean_in.used > 0) {
486 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
487 record_minus(&ssn->clean_in, NULL, written);
489 /* Get the dirty data from Bio to send it */
490 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
491 sizeof(ssn->dirty_out.data));
493 ssn->dirty_out.used = err;
495 int_ssl_check(request, ssn->ssl, err, "handshake_send");
502 void session_init(tls_session_t *ssn)
505 ssn->into_ssl = ssn->from_ssl = NULL;
506 record_init(&ssn->clean_in);
507 record_init(&ssn->clean_out);
508 record_init(&ssn->dirty_in);
509 record_init(&ssn->dirty_out);
511 memset(&ssn->info, 0, sizeof(ssn->info));
515 ssn->tls_msg_len = 0;
516 ssn->length_flag = 0;
518 ssn->free_opaque = NULL;
521 void session_close(tls_session_t *ssn)
523 SSL_set_quiet_shutdown(ssn->ssl, 1);
524 SSL_shutdown(ssn->ssl);
531 record_close(&ssn->clean_in);
532 record_close(&ssn->clean_out);
533 record_close(&ssn->dirty_in);
534 record_close(&ssn->dirty_out);
538 static void record_init(record_t *rec)
543 static void record_close(record_t *rec)
550 * Copy data to the intermediate buffer, before we send
553 static unsigned int record_plus(record_t *rec, void const *ptr,
556 unsigned int added = MAX_RECORD_SIZE - rec->used;
562 memcpy(rec->data + rec->used, ptr, added);
568 * Take data from the buffer, and give it to the caller.
570 static unsigned int record_minus(record_t *rec, void *ptr,
573 unsigned int taken = rec->used;
580 memcpy(ptr, rec->data, taken);
584 * This is pretty bad...
587 memmove(rec->data, rec->data + taken, rec->used);
591 void tls_session_information(tls_session_t *tls_session)
593 char const *str_write_p, *str_version, *str_content_type = "";
594 char const *str_details1 = "", *str_details2= "";
598 * Don't print this out in the normal course of
601 if (debug_flag == 0) {
605 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
607 switch (tls_session->info.version) {
609 str_version = "SSL 2.0";
612 str_version = "SSL 3.0 ";
615 str_version = "TLS 1.0 ";
618 str_version = "Unknown TLS version";
622 if (tls_session->info.version == SSL3_VERSION ||
623 tls_session->info.version == TLS1_VERSION) {
624 switch (tls_session->info.content_type) {
625 case SSL3_RT_CHANGE_CIPHER_SPEC:
626 str_content_type = "ChangeCipherSpec";
629 str_content_type = "Alert";
631 case SSL3_RT_HANDSHAKE:
632 str_content_type = "Handshake";
634 case SSL3_RT_APPLICATION_DATA:
635 str_content_type = "ApplicationData";
638 str_content_type = "UnknownContentType";
642 if (tls_session->info.content_type == SSL3_RT_ALERT) {
643 str_details1 = ", ???";
645 if (tls_session->info.record_len == 2) {
647 switch (tls_session->info.alert_level) {
648 case SSL3_AL_WARNING:
649 str_details1 = ", warning";
652 str_details1 = ", fatal";
656 str_details2 = " ???";
657 switch (tls_session->info.alert_description) {
658 case SSL3_AD_CLOSE_NOTIFY:
659 str_details2 = " close_notify";
661 case SSL3_AD_UNEXPECTED_MESSAGE:
662 str_details2 = " unexpected_message";
664 case SSL3_AD_BAD_RECORD_MAC:
665 str_details2 = " bad_record_mac";
667 case TLS1_AD_DECRYPTION_FAILED:
668 str_details2 = " decryption_failed";
670 case TLS1_AD_RECORD_OVERFLOW:
671 str_details2 = " record_overflow";
673 case SSL3_AD_DECOMPRESSION_FAILURE:
674 str_details2 = " decompression_failure";
676 case SSL3_AD_HANDSHAKE_FAILURE:
677 str_details2 = " handshake_failure";
679 case SSL3_AD_BAD_CERTIFICATE:
680 str_details2 = " bad_certificate";
682 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
683 str_details2 = " unsupported_certificate";
685 case SSL3_AD_CERTIFICATE_REVOKED:
686 str_details2 = " certificate_revoked";
688 case SSL3_AD_CERTIFICATE_EXPIRED:
689 str_details2 = " certificate_expired";
691 case SSL3_AD_CERTIFICATE_UNKNOWN:
692 str_details2 = " certificate_unknown";
694 case SSL3_AD_ILLEGAL_PARAMETER:
695 str_details2 = " illegal_parameter";
697 case TLS1_AD_UNKNOWN_CA:
698 str_details2 = " unknown_ca";
700 case TLS1_AD_ACCESS_DENIED:
701 str_details2 = " access_denied";
703 case TLS1_AD_DECODE_ERROR:
704 str_details2 = " decode_error";
706 case TLS1_AD_DECRYPT_ERROR:
707 str_details2 = " decrypt_error";
709 case TLS1_AD_EXPORT_RESTRICTION:
710 str_details2 = " export_restriction";
712 case TLS1_AD_PROTOCOL_VERSION:
713 str_details2 = " protocol_version";
715 case TLS1_AD_INSUFFICIENT_SECURITY:
716 str_details2 = " insufficient_security";
718 case TLS1_AD_INTERNAL_ERROR:
719 str_details2 = " internal_error";
721 case TLS1_AD_USER_CANCELLED:
722 str_details2 = " user_canceled";
724 case TLS1_AD_NO_RENEGOTIATION:
725 str_details2 = " no_renegotiation";
731 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
732 str_details1 = "???";
734 if (tls_session->info.record_len > 0)
735 switch (tls_session->info.handshake_type) {
736 case SSL3_MT_HELLO_REQUEST:
737 str_details1 = ", HelloRequest";
739 case SSL3_MT_CLIENT_HELLO:
740 str_details1 = ", ClientHello";
742 case SSL3_MT_SERVER_HELLO:
743 str_details1 = ", ServerHello";
745 case SSL3_MT_CERTIFICATE:
746 str_details1 = ", Certificate";
748 case SSL3_MT_SERVER_KEY_EXCHANGE:
749 str_details1 = ", ServerKeyExchange";
751 case SSL3_MT_CERTIFICATE_REQUEST:
752 str_details1 = ", CertificateRequest";
754 case SSL3_MT_SERVER_DONE:
755 str_details1 = ", ServerHelloDone";
757 case SSL3_MT_CERTIFICATE_VERIFY:
758 str_details1 = ", CertificateVerify";
760 case SSL3_MT_CLIENT_KEY_EXCHANGE:
761 str_details1 = ", ClientKeyExchange";
763 case SSL3_MT_FINISHED:
764 str_details1 = ", Finished";
770 snprintf(tls_session->info.info_description,
771 sizeof(tls_session->info.info_description),
772 "%s %s%s [length %04lx]%s%s\n",
773 str_write_p, str_version, str_content_type,
774 (unsigned long)tls_session->info.record_len,
775 str_details1, str_details2);
777 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
779 RDEBUG2("%s", tls_session->info.info_description);
781 DEBUG2("%s", tls_session->info.info_description);
785 static CONF_PARSER cache_config[] = {
786 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
787 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
788 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
789 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
790 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
791 { NULL, -1, 0, NULL, NULL } /* end the list */
794 static CONF_PARSER verify_config[] = {
795 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
796 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
797 { NULL, -1, 0, NULL, NULL } /* end the list */
800 #ifdef HAVE_OPENSSL_OCSP_H
801 static CONF_PARSER ocsp_config[] = {
802 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
803 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
804 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
805 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
806 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
807 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "yes" },
808 { NULL, -1, 0, NULL, NULL } /* end the list */
812 static CONF_PARSER tls_server_config[] = {
813 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
814 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
815 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
816 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
817 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
818 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
819 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
820 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
821 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
822 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
823 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
824 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
825 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
826 #ifdef PSK_MAX_IDENTITY_LEN
827 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
828 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
830 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
831 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
832 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
833 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
834 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
835 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
836 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
837 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
838 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
839 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
841 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
842 #ifndef OPENSSL_NO_ECDH
843 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
847 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
849 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
851 #ifdef HAVE_OPENSSL_OCSP_H
852 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
855 { NULL, -1, 0, NULL, NULL } /* end the list */
859 static CONF_PARSER tls_client_config[] = {
860 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
861 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
862 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
863 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
864 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
865 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
866 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
867 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
868 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
869 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
870 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
871 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
872 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
873 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
874 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
875 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
876 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
877 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
878 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
880 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
881 #ifndef OPENSSL_NO_ECDH
882 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
886 { NULL, -1, 0, NULL, NULL } /* end the list */
891 * TODO: Check for the type of key exchange * like conf->dh_key
893 static int load_dh_params(SSL_CTX *ctx, char *file)
900 if ((bio = BIO_new_file(file, "r")) == NULL) {
901 ERROR("tls: Unable to open DH file - %s", file);
905 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
908 WARN("tls: Unable to set DH parameters. DH cipher suites may not work!");
909 WARN("Fix this by running the OpenSSL command listed in eap.conf");
913 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
914 ERROR("tls: Unable to set DH parameters");
925 * Generate ephemeral RSA keys.
927 static int generate_eph_rsa_key(SSL_CTX *ctx)
931 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
933 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
934 ERROR("tls: Couldn't set ephemeral RSA key");
942 /* index we use to store cached session VPs
943 * needs to be dynamic so we can supply a "free" function
945 static int FR_TLS_EX_INDEX_VPS = -1;
946 int FR_TLS_EX_INDEX_CERTS = -1;
949 * Print debugging messages, and free data.
951 * FIXME: Write sessions to some long-term storage, so that
952 * session resumption can still occur after the server
955 #define MAX_SESSION_SIZE (256)
957 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
960 char buffer[2 * MAX_SESSION_SIZE + 1];
961 fr_tls_server_conf_t *conf;
963 size = sess->session_id_length;
964 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
966 fr_bin2hex(buffer, sess->session_id, size);
968 DEBUG2(" SSL: Removing session %s from the cache", buffer);
969 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
970 if (conf && conf->session_cache_path) {
974 /* remove session and any cached VPs */
975 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
976 conf->session_cache_path, FR_DIR_SEP, buffer);
977 rv = unlink(filename);
979 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
981 /* VPs might be absent; might not have been written to disk yet */
982 snprintf(filename, sizeof(filename), "%s%c%s.vps",
983 conf->session_cache_path, FR_DIR_SEP, buffer);
990 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
993 char buffer[2 * MAX_SESSION_SIZE + 1];
994 fr_tls_server_conf_t *conf;
995 unsigned char *sess_blob = NULL;
997 size = sess->session_id_length;
998 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1000 fr_bin2hex(buffer, sess->session_id, size);
1002 DEBUG2(" SSL: adding session %s to cache", buffer);
1004 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1005 if (conf && conf->session_cache_path) {
1006 int fd, rv, todo, blob_len;
1010 /* find out what length data we need */
1011 blob_len = i2d_SSL_SESSION(sess, NULL);
1013 /* something went wrong */
1014 DEBUG2(" SSL: could not find buffer length to persist session");
1018 /* alloc and convert to ASN.1 */
1019 sess_blob = talloc_array(conf, unsigned char, blob_len);
1021 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1024 /* openssl mutates &p */
1026 rv = i2d_SSL_SESSION(sess, &p);
1027 if (rv != blob_len) {
1028 DEBUG2(" SSL: could not persist session");
1032 /* open output file */
1033 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1034 conf->session_cache_path, FR_DIR_SEP, buffer);
1035 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1037 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1044 rv = write(fd, p, todo);
1046 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1054 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1058 if (sess_blob) talloc_free(sess_blob);
1063 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1064 unsigned char *data, int len,
1068 char buffer[2 * MAX_SESSION_SIZE + 1];
1069 fr_tls_server_conf_t *conf;
1070 TALLOC_CTX *talloc_ctx;
1072 SSL_SESSION *sess = NULL;
1073 unsigned char *sess_data = NULL;
1074 PAIR_LIST *pairlist = NULL;
1077 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1079 fr_bin2hex(buffer, data, size);
1081 DEBUG2(" SSL: Client requested cached session %s", buffer);
1083 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1084 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1085 if (conf && conf->session_cache_path) {
1092 /* read in the cached VPs from the .vps file */
1093 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1094 conf->session_cache_path, FR_DIR_SEP, buffer);
1095 rv = pairlist_read(NULL, filename, &pairlist, 1);
1097 /* not safe to un-persist a session w/o VPs */
1098 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1102 /* load the actual SSL session */
1103 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1104 conf->session_cache_path, FR_DIR_SEP, buffer);
1105 fd = open(filename, O_RDONLY);
1107 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1111 rv = fstat(fd, &st);
1113 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1118 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1120 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1128 rv = read(fd, p, todo);
1130 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1139 /* openssl mutates &p */
1141 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1144 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1148 /* cache the VPs into the session */
1149 vp = paircopy(talloc_ctx, pairlist->reply);
1150 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1151 DEBUG2(" SSL: Successfully restored session %s", buffer);
1154 if (sess_data) talloc_free(sess_data);
1155 if (pairlist) pairlist_free(&pairlist);
1161 #ifdef HAVE_OPENSSL_OCSP_H
1163 * This function extracts the OCSP Responder URL
1164 * from an existing x509 certificate.
1166 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1167 char **ppath, int *pssl)
1171 AUTHORITY_INFO_ACCESS *aia;
1172 ACCESS_DESCRIPTION *ad;
1174 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1176 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1177 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1178 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1179 if (ad->location->type == GEN_URI) {
1180 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1181 phost, pport, ppath, pssl))
1190 * This function sends a OCSP request to a defined OCSP responder
1191 * and checks the OCSP response for correctness.
1194 /* Maximum leeway in validity period: default 5 minutes */
1195 #define MAX_VALIDITY_PERIOD (5 * 60)
1197 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1198 fr_tls_server_conf_t *conf)
1200 OCSP_CERTID *certid;
1202 OCSP_RESPONSE *resp = NULL;
1203 OCSP_BASICRESP *bresp = NULL;
1208 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1209 BIO *cbio, *bio_out;
1212 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1214 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1218 struct timeval when;
1222 * Create OCSP Request
1224 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1225 req = OCSP_REQUEST_new();
1226 OCSP_request_add0_id(req, certid);
1227 if(conf->ocsp_use_nonce) {
1228 OCSP_request_add1_nonce(req, NULL, 8);
1232 * Send OCSP Request and get OCSP Response
1235 /* Get OCSP responder URL */
1236 if (conf->ocsp_override_url) {
1239 memcpy(&url, &conf->ocsp_url, sizeof(url));
1240 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1241 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1244 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1247 if (!host || !port || !path) {
1248 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP");
1253 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1255 /* Setup BIO socket to OCSP responder */
1256 cbio = BIO_new_connect(host);
1258 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1260 BIO_set_conn_port(cbio, port);
1261 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1262 BIO_do_connect(cbio);
1264 /* Send OCSP request and wait for response */
1265 resp = OCSP_sendreq_bio(cbio, path, req);
1267 ERROR("Couldn't get OCSP response");
1272 if (conf->ocsp_timeout)
1273 BIO_set_nbio(cbio, 1);
1275 rc = BIO_do_connect(cbio);
1276 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1277 ERROR("Couldn't connect to OCSP responder");
1282 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1284 ERROR("Couldn't send OCSP request");
1289 gettimeofday(&when, NULL);
1290 when.tv_sec += conf->ocsp_timeout;
1293 rc = OCSP_sendreq_nbio(&resp, ctx);
1294 if (conf->ocsp_timeout) {
1295 gettimeofday(&now, NULL);
1296 if (!timercmp(&now, &when, <))
1299 } while ((rc == -1) && BIO_should_retry(cbio));
1301 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1302 ERROR("OCSP response timed out");
1307 OCSP_REQ_CTX_free(ctx);
1310 ERROR("Couldn't get OCSP response");
1316 /* Verify OCSP response status */
1317 status = OCSP_response_status(resp);
1318 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1319 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1320 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1323 bresp = OCSP_response_get1_basic(resp);
1324 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1325 ERROR("OCSP response has wrong nonce value");
1328 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1329 ERROR("Couldn't verify OCSP basic response");
1333 /* Verify OCSP cert status */
1334 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1335 &rev, &thisupd, &nextupd)) {
1336 ERROR("No Status found.\n");
1340 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1341 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1342 ERR_print_errors(bio_out);
1345 BIO_puts(bio_out, "\tThis Update: ");
1346 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1347 BIO_puts(bio_out, "\n");
1349 BIO_puts(bio_out, "\tNext Update: ");
1350 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1351 BIO_puts(bio_out, "\n");
1355 case V_OCSP_CERTSTATUS_GOOD:
1356 DEBUG2("[oscp] --> Cert status: good");
1361 /* REVOKED / UNKNOWN */
1362 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1364 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1365 BIO_puts(bio_out, "\tRevocation Time: ");
1366 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1367 BIO_puts(bio_out, "\n");
1372 /* Free OCSP Stuff */
1373 OCSP_REQUEST_free(req);
1374 OCSP_RESPONSE_free(resp);
1379 OCSP_BASICRESP_free(bresp);
1384 DEBUG2("[ocsp] --> Certificate is valid!");
1387 if (conf->ocsp_softfail) {
1388 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1389 DEBUG2("[ocsp] --> Warning! This may be insecure");
1392 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1397 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1403 #endif /* HAVE_OPENSSL_OCSP_H */
1406 * For creating certificate attributes.
1408 static char const *cert_attr_names[8][2] = {
1409 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1410 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1411 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1412 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1413 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1414 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1415 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1416 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1419 #define FR_TLS_SERIAL (0)
1420 #define FR_TLS_EXPIRATION (1)
1421 #define FR_TLS_SUBJECT (2)
1422 #define FR_TLS_ISSUER (3)
1423 #define FR_TLS_CN (4)
1424 #define FR_TLS_SAN_EMAIL (5)
1425 #define FR_TLS_SAN_DNS (6)
1426 #define FR_TLS_SAN_UPN (7)
1429 * Before trusting a certificate, you must make sure that the
1430 * certificate is 'valid'. There are several steps that your
1431 * application can take in determining if a certificate is
1432 * valid. Commonly used steps are:
1434 * 1.Verifying the certificate's signature, and verifying that
1435 * the certificate has been issued by a trusted Certificate
1438 * 2.Verifying that the certificate is valid for the present date
1439 * (i.e. it is being presented within its validity dates).
1441 * 3.Verifying that the certificate has not been revoked by its
1442 * issuing Certificate Authority, by checking with respect to a
1443 * Certificate Revocation List (CRL).
1445 * 4.Verifying that the credentials presented by the certificate
1446 * fulfill additional requirements specific to the application,
1447 * such as with respect to access control lists or with respect
1448 * to OCSP (Online Certificate Status Processing).
1450 * NOTE: This callback will be called multiple times based on the
1451 * depth of the root certificate chain
1453 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1455 char subject[1024]; /* Used for the subject name */
1456 char issuer[1024]; /* Used for the issuer name */
1457 char attribute[1024];
1459 char common_name[1024];
1463 X509_CINF *client_inf;
1464 STACK_OF(X509_EXTENSION) *ext_list;
1466 int err, depth, lookup, loc;
1467 fr_tls_server_conf_t *conf;
1470 ASN1_INTEGER *sn = NULL;
1471 ASN1_TIME *asn_time = NULL;
1474 #ifdef HAVE_OPENSSL_OCSP_H
1475 X509_STORE *ocsp_store = NULL;
1478 TALLOC_CTX *talloc_ctx;
1480 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1481 err = X509_STORE_CTX_get_error(ctx);
1482 depth = X509_STORE_CTX_get_error_depth(ctx);
1487 * Log client/issuing cert. If there's an error, log
1490 if ((lookup > 1) && !my_ok) lookup = 1;
1493 * Retrieve the pointer to the SSL of the connection currently treated
1494 * and the application specific data stored into the SSL object.
1496 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1497 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1498 if (!conf) return 1;
1500 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1501 rad_assert(request != NULL);
1502 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1504 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1505 #ifdef HAVE_OPENSSL_OCSP_H
1506 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1509 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1512 * Get the Serial Number
1515 sn = X509_get_serialNumber(client_cert);
1518 * For this next bit, we create the attributes *only* if
1519 * we're at the client or issuing certificate, AND we
1520 * have a user identity. i.e. we don't create the
1521 * attributes for RadSec connections.
1523 if (certs && identity &&
1524 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1528 for (i = 0; i < sn->length; i++) {
1529 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1532 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1537 * Get the Expiration Date
1540 asn_time = X509_get_notAfter(client_cert);
1541 if (certs && identity && (lookup <= 1) && asn_time &&
1542 (asn_time->length < (int) sizeof(buf))) {
1543 memcpy(buf, (char*) asn_time->data, asn_time->length);
1544 buf[asn_time->length] = '\0';
1545 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1549 * Get the Subject & Issuer
1551 subject[0] = issuer[0] = '\0';
1552 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1554 subject[sizeof(subject) - 1] = '\0';
1555 if (certs && identity && (lookup <= 1) && subject[0]) {
1556 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1559 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1561 issuer[sizeof(issuer) - 1] = '\0';
1562 if (certs && identity && (lookup <= 1) && issuer[0]) {
1563 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1567 * Get the Common Name, if there is a subject.
1569 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1570 NID_commonName, common_name, sizeof(common_name));
1571 common_name[sizeof(common_name) - 1] = '\0';
1572 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1573 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1577 * Get the RFC822 Subject Alternative Name
1579 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1580 if (certs && (lookup <= 1) && (loc >= 0)) {
1581 X509_EXTENSION *ext = NULL;
1582 GENERAL_NAMES *names = NULL;
1585 if ((ext = X509_get_ext(client_cert, loc)) &&
1586 (names = X509V3_EXT_d2i(ext))) {
1587 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1588 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1590 switch (name->type) {
1593 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1594 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1596 #endif /* GEN_EMAIL */
1599 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1600 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1602 #endif /* GEN_DNS */
1603 #ifdef GEN_OTHERNAME
1605 /* look for a MS UPN */
1606 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1607 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1608 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1609 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1610 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1613 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)\n");
1618 #endif /* GEN_OTHERNAME */
1620 /* XXX TODO handle other SAN types */
1626 sk_GENERAL_NAME_free(names);
1630 * If the CRL has expired, that might still be OK.
1633 (conf->allow_expired_crl) &&
1634 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1636 X509_STORE_CTX_set_error( ctx, 0 );
1640 char const *p = X509_verify_cert_error_string(err);
1641 ERROR("--> verify error:num=%d:%s\n",err, p);
1642 REDEBUG("SSL says error %d : %s", err, p);
1647 client_inf = client_cert->cert_info;
1648 ext_list = client_inf->extensions;
1654 * Grab the X509 extensions, and create attributes out of them.
1655 * For laziness, we re-use the OpenSSL names
1657 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1662 out = BIO_new(BIO_s_mem());
1663 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1665 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1667 X509_EXTENSION *ext;
1670 ext = sk_X509_EXTENSION_value(ext_list, i);
1672 obj = X509_EXTENSION_get_object(ext);
1673 i2a_ASN1_OBJECT(out, obj);
1674 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1675 if (len <= 0) continue;
1677 attribute[16 + len] = '\0';
1679 X509V3_EXT_print(out, ext, 0, 0);
1680 len = BIO_read(out, value , sizeof(value) - 1);
1681 if (len <= 0) continue;
1686 * Mash the OpenSSL name to our name, and
1687 * create the attribute.
1689 for (p = value + 16; *p != '\0'; p++) {
1690 if (*p == ' ') *p = '-';
1693 vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1694 if (vp) debug_pair_list(vp);
1700 switch (ctx->error) {
1702 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1703 ERROR("issuer= %s\n", issuer);
1705 case X509_V_ERR_CERT_NOT_YET_VALID:
1706 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1707 ERROR("notBefore=");
1709 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1712 case X509_V_ERR_CERT_HAS_EXPIRED:
1713 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1716 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1722 * If we're at the actual client cert, apply additional
1727 * If the conf tells us to, check cert issuer
1728 * against the specified value and fail
1729 * verification if they don't match.
1731 if (conf->check_cert_issuer &&
1732 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1733 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1738 * If the conf tells us to, check the CN in the
1739 * cert against xlat'ed value, but only if the
1740 * previous checks passed.
1742 if (my_ok && conf->check_cert_cn) {
1743 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1744 /* if this fails, fail the verification */
1747 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1748 if (strcmp(cn_str, common_name) != 0) {
1749 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1753 } /* check_cert_cn */
1755 #ifdef HAVE_OPENSSL_OCSP_H
1756 if (my_ok && conf->ocsp_enable){
1757 RDEBUG2("--> Starting OCSP Request");
1758 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1759 ERROR("Couldn't get issuer_cert for %s", common_name);
1761 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1765 while (conf->verify_client_cert_cmd) {
1770 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1771 conf->verify_tmp_dir, progname);
1772 fd = mkstemp(filename);
1774 RDEBUG("Failed creating file in %s: %s",
1775 conf->verify_tmp_dir, fr_syserror(errno));
1779 fp = fdopen(fd, "w");
1782 RDEBUG("Failed opening file %s: %s",
1783 filename, fr_syserror(errno));
1787 if (!PEM_write_X509(fp, client_cert)) {
1789 RDEBUG("Failed writing certificate to file");
1794 if (!pairmake_packet("TLS-Client-Cert-Filename",
1795 filename, T_OP_SET)) {
1796 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1801 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1802 if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1803 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1804 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1807 RDEBUG("Client certificate CN %s passed external validation", common_name);
1818 if (debug_flag > 0) {
1819 RDEBUG2("chain-depth=%d, ", depth);
1820 RDEBUG2("error=%d", err);
1822 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1823 RDEBUG2("--> BUF-Name = %s", common_name);
1824 RDEBUG2("--> subject = %s", subject);
1825 RDEBUG2("--> issuer = %s", issuer);
1826 RDEBUG2("--> verify return:%d", my_ok);
1832 #ifdef HAVE_OPENSSL_OCSP_H
1834 * Create Global X509 revocation store and use it to verify
1837 * - Load the trusted CAs
1838 * - Load the trusted issuer certificates
1840 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1842 X509_STORE *store = NULL;
1844 store = X509_STORE_new();
1846 /* Load the CAs we trust */
1847 if (conf->ca_file || conf->ca_path)
1848 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1849 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1850 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1854 #ifdef X509_V_FLAG_CRL_CHECK
1855 if (conf->check_crl)
1856 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1860 #endif /* HAVE_OPENSSL_OCSP_H */
1862 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1863 #ifndef OPENSSL_NO_ECDH
1864 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1869 if (!ecdh_curve || !*ecdh_curve) return 0;
1871 nid = OBJ_sn2nid(ecdh_curve);
1873 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1877 ecdh = EC_KEY_new_by_curve_name(nid);
1879 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1883 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1885 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1895 * DIE OPENSSL DIE DIE DIE
1897 * What a palaver, just to free some data attached the
1898 * session. We need to do this because the "remove" callback
1899 * is called when refcount > 0 sometimes, if another thread
1900 * is using the session
1902 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1903 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1904 UNUSED long argl, UNUSED void *argp)
1906 VALUE_PAIR *vp = data_ptr;
1909 DEBUG2(" Freeing cached session VPs");;
1914 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
1915 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1916 UNUSED long argl, UNUSED void *argp)
1918 VALUE_PAIR **certs = data_ptr;
1921 DEBUG2(" Freeing cached session Certificates");
1926 /** Add all the default ciphers and message digests reate our context.
1928 * This should be called exactly once from main, before reading the main config
1929 * or initialising any modules.
1931 void tls_global_init(void)
1933 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
1934 SSL_library_init(); /* initialize library */
1935 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
1936 OPENSSL_config(NULL);
1939 /** Check for vulnerable versions of libssl
1941 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
1942 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
1944 int tls_global_version_check(char const *acknowledged)
1948 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
1952 /* Check for bad versions */
1953 v = (uint64_t) SSLeay();
1955 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
1956 libssl_defect_t *defect = &libssl_defects[i];
1958 if ((v >= defect->low) && (v <= defect->high)) {
1959 ERROR("Refusing to start with libssl version %s (in range %s)",
1960 ssl_version(), ssl_version_range(defect->low, defect->high));
1961 ERROR("Security advisory %s (%s)", defect->id, defect->name);
1962 ERROR("%s", defect->comment);
1969 INFO("Once you have verified libssl has been correctly patched, "
1970 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
1978 /** Free any memory alloced by libssl
1981 void tls_global_cleanup(void)
1983 ERR_remove_state(0);
1985 CONF_modules_unload(1);
1988 CRYPTO_cleanup_all_ex_data();
1992 * Create Global context SSL and use it in every new session
1994 * - Load the trusted CAs
1995 * - Load the Private key & the certificate
1996 * - Set the Context options & Verify options
1998 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
2001 X509_STORE *certstore;
2002 int verify_mode = SSL_VERIFY_NONE;
2003 int ctx_options = 0;
2007 * SHA256 is in all versions of OpenSSL, but isn't
2008 * initialized by default. It's needed for WiMAX
2011 #ifdef HAVE_OPENSSL_EVP_SHA256
2012 EVP_add_digest(EVP_sha256());
2015 ctx = SSL_CTX_new(TLSv1_method());
2018 while ((err = ERR_get_error())) {
2019 DEBUG("Failed creating SSL context: %s",
2020 ERR_error_string(err, NULL));
2026 * Save the config on the context so that callbacks which
2027 * only get SSL_CTX* e.g. session persistence, can get it
2029 SSL_CTX_set_app_data(ctx, conf);
2032 * Identify the type of certificates that needs to be loaded
2034 if (conf->file_type) {
2035 type = SSL_FILETYPE_PEM;
2037 type = SSL_FILETYPE_ASN1;
2041 * Set the password to load private key
2043 if (conf->private_key_password) {
2046 * We don't want to put the private key password in eap.conf, so check
2047 * for our special string which indicates we should get the password
2050 char const* special_string = "Apple:UseCertAdmin";
2051 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2054 long const max_password_len = 128;
2055 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2056 conf->private_key_file);
2058 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2060 FILE* cmd_pipe = popen(cmd, "r");
2062 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2063 ERROR("Error reading private_key_file %s", conf->private_key_file);
2067 rad_const_free(conf->private_key_password);
2068 password = talloc_array(conf, char, max_password_len);
2070 ERROR("TLS: Can't allocate space for private_key_password");
2071 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2076 fgets(password, max_password_len, cmd_pipe);
2079 /* Get rid of newline at end of password. */
2080 password[strlen(password) - 1] = '\0';
2082 DEBUG3("tls: Password from command = \"%s\"", password);
2083 conf->private_key_password = password;
2090 memcpy(&password, &conf->private_key_password, sizeof(password));
2091 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2092 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2096 #ifdef PSK_MAX_IDENTITY_LEN
2097 if ((conf->psk_identity && !conf->psk_password) ||
2098 (!conf->psk_identity && conf->psk_password) ||
2099 (conf->psk_identity && !*conf->psk_identity) ||
2100 (conf->psk_password && !*conf->psk_password)) {
2101 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2105 if (conf->psk_identity) {
2106 size_t psk_len, hex_len;
2107 char buffer[PSK_MAX_PSK_LEN];
2109 if (conf->certificate_file ||
2110 conf->private_key_password || conf->private_key_file ||
2111 conf->ca_file || conf->ca_path) {
2112 ERROR("When PSKs are used, No certificate configuration is permitted");
2117 SSL_CTX_set_psk_client_callback(ctx,
2118 psk_client_callback);
2120 SSL_CTX_set_psk_server_callback(ctx,
2121 psk_server_callback);
2124 psk_len = strlen(conf->psk_password);
2125 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2126 ERROR("psk_hexphrase is too long (max %d)",
2131 hex_len = fr_hex2bin((uint8_t *) buffer, sizeof(buffer), conf->psk_password, psk_len);
2132 if (psk_len != (2 * hex_len)) {
2133 ERROR("psk_hexphrase is not all hex");
2140 (void) client; /* -Wunused */
2144 * Load our keys and certificates
2146 * If certificates are of type PEM then we can make use
2147 * of cert chain authentication using openssl api call
2148 * SSL_CTX_use_certificate_chain_file. Please see how
2149 * the cert chain needs to be given in PEM from
2152 if (!conf->certificate_file) goto load_ca;
2154 if (type == SSL_FILETYPE_PEM) {
2155 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2156 ERROR("Error reading certificate file %s:%s",
2157 conf->certificate_file,
2158 ERR_error_string(ERR_get_error(), NULL));
2162 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2163 ERROR("Error reading certificate file %s:%s",
2164 conf->certificate_file,
2165 ERR_error_string(ERR_get_error(), NULL));
2169 /* Load the CAs we trust */
2171 if (conf->ca_file || conf->ca_path) {
2172 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2173 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2174 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2178 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2180 if (conf->private_key_file) {
2181 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2182 ERROR("Failed reading private key file %s:%s",
2183 conf->private_key_file,
2184 ERR_error_string(ERR_get_error(), NULL));
2189 * Check if the loaded private key is the right one
2191 if (!SSL_CTX_check_private_key(ctx)) {
2192 ERROR("Private key does not match the certificate public key");
2197 #ifdef PSK_MAX_IDENTITY_LEN
2204 ctx_options |= SSL_OP_NO_SSLv2;
2205 ctx_options |= SSL_OP_NO_SSLv3;
2206 #ifdef SSL_OP_NO_TICKET
2207 ctx_options |= SSL_OP_NO_TICKET ;
2211 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2212 * small subgroup attacks and forward secrecy. Always
2215 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2216 * time needed during negotiation, but it is not very
2219 ctx_options |= SSL_OP_SINGLE_DH_USE;
2222 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2223 * in Windows Vista client.
2224 * http://www.openssl.org/~bodo/tls-cbc.txt
2225 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2227 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2229 SSL_CTX_set_options(ctx, ctx_options);
2232 * TODO: Set the RSA & DH
2233 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2234 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2238 * set the message callback to identify the type of
2239 * message. For every new session, there can be a
2240 * different callback argument.
2242 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2246 * Set eliptical curve crypto configuration.
2248 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2249 #ifndef OPENSSL_NO_ECDH
2250 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2256 /* Set Info callback */
2257 SSL_CTX_set_info_callback(ctx, cbtls_info);
2260 * Callbacks, etc. for session resumption.
2262 if (conf->session_cache_enable) {
2263 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2264 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2265 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2267 SSL_CTX_set_quiet_shutdown(ctx, 1);
2268 if (FR_TLS_EX_INDEX_VPS < 0)
2269 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2270 if (FR_TLS_EX_INDEX_CERTS < 0)
2271 FR_TLS_EX_INDEX_CERTS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2275 * Check the certificates for revocation.
2277 #ifdef X509_V_FLAG_CRL_CHECK
2278 if (conf->check_crl) {
2279 certstore = SSL_CTX_get_cert_store(ctx);
2280 if (certstore == NULL) {
2281 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2282 ERROR("tls: Error reading Certificate Store");
2285 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2291 * Always verify the peer certificate
2293 verify_mode |= SSL_VERIFY_PEER;
2294 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2295 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2296 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2298 if (conf->verify_depth) {
2299 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2302 /* Load randomness */
2303 if (conf->random_file) {
2304 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2305 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2306 ERROR("tls: Error loading randomness");
2312 * Set the cipher list if we were told to
2314 if (conf->cipher_list) {
2315 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2316 ERROR("tls: Error setting cipher list");
2322 * Setup session caching
2324 if (conf->session_cache_enable) {
2326 * Create a unique context Id per EAP-TLS configuration.
2328 if (conf->session_id_name) {
2329 snprintf(conf->session_context_id,
2330 sizeof(conf->session_context_id),
2332 conf->session_id_name);
2334 snprintf(conf->session_context_id,
2335 sizeof(conf->session_context_id),
2340 * Cache it, and DON'T auto-clear it.
2342 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2344 SSL_CTX_set_session_id_context(ctx,
2345 (unsigned char *) conf->session_context_id,
2346 (unsigned int) strlen(conf->session_context_id));
2349 * Our timeout is in hours, this is in seconds.
2351 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2354 * Set the maximum number of entries in the
2357 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2360 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2368 * Free TLS client/server config
2369 * Should not be called outside this code, as a callback is
2370 * added to automatically free the data when the CONF_SECTION
2373 static int tls_server_conf_free(fr_tls_server_conf_t *conf)
2375 if (conf->ctx) SSL_CTX_free(conf->ctx);
2377 #ifdef HAVE_OPENSSL_OCSP_H
2378 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2379 conf->ocsp_store = NULL;
2383 memset(conf, 0, sizeof(*conf));
2389 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2391 fr_tls_server_conf_t *conf;
2394 * If cs has already been parsed there should be a cached copy
2395 * of conf already stored, so just return that.
2397 conf = cf_data_find(cs, "tls-conf");
2399 DEBUG("Using cached TLS configuration from previous invocation");
2403 conf = talloc_zero(cs, fr_tls_server_conf_t);
2405 ERROR("Out of memory");
2409 talloc_set_destructor(conf, tls_server_conf_free);
2411 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2418 * Save people from their own stupidity.
2420 if (conf->fragment_size < 100) conf->fragment_size = 100;
2422 if (!conf->private_key_file) {
2423 ERROR("TLS Server requires a private key file");
2427 if (!conf->certificate_file) {
2428 ERROR("TLS Server requires a certificate file");
2435 conf->ctx = init_tls_ctx(conf, 0);
2436 if (conf->ctx == NULL) {
2440 #ifdef HAVE_OPENSSL_OCSP_H
2442 * Initialize OCSP Revocation Store
2444 if (conf->ocsp_enable) {
2445 conf->ocsp_store = init_revocation_store(conf);
2446 if (conf->ocsp_store == NULL) goto error;
2448 #endif /*HAVE_OPENSSL_OCSP_H*/
2452 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2453 if (load_dh_params(conf->ctx, dh_file) < 0) {
2458 if (generate_eph_rsa_key(conf->ctx) < 0) {
2462 if (conf->verify_tmp_dir) {
2463 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2464 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2469 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2470 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2475 * Cache conf in cs in case we're asked to parse this again.
2477 cf_data_add(cs, "tls-conf", conf, NULL);
2482 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2484 fr_tls_server_conf_t *conf;
2486 conf = cf_data_find(cs, "tls-conf");
2488 DEBUG("Using cached TLS configuration from previous invocation");
2492 conf = talloc_zero(cs, fr_tls_server_conf_t);
2494 ERROR("Out of memory");
2498 talloc_set_destructor(conf, tls_server_conf_free);
2500 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2507 * Save people from their own stupidity.
2509 if (conf->fragment_size < 100) conf->fragment_size = 100;
2514 conf->ctx = init_tls_ctx(conf, 1);
2515 if (conf->ctx == NULL) {
2522 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2523 if (load_dh_params(conf->ctx, dh_file) < 0) {
2528 if (generate_eph_rsa_key(conf->ctx) < 0) {
2532 cf_data_add(cs, "tls-conf", conf, NULL);
2537 int tls_success(tls_session_t *ssn, REQUEST *request)
2539 VALUE_PAIR *vp, *vps = NULL;
2540 fr_tls_server_conf_t *conf;
2541 TALLOC_CTX *talloc_ctx;
2543 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2544 rad_assert(conf != NULL);
2546 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2549 * If there's no session resumption, delete the entry
2550 * from the cache. This means either it's disabled
2551 * globally for this SSL context, OR we were told to
2552 * disable it for this user.
2554 * This also means you can't turn it on just for one
2557 if ((!ssn->allow_session_resumption) ||
2558 (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2559 (vp->vp_integer == 0))) {
2560 SSL_CTX_remove_session(ssn->ctx,
2562 ssn->allow_session_resumption = 0;
2565 * If we're in a resumed session and it's
2568 if (SSL_session_reused(ssn->ssl)) {
2569 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2574 * Else resumption IS allowed, so we store the
2575 * user data in the cache.
2577 } else if (!SSL_session_reused(ssn->ssl)) {
2580 char buffer[2 * MAX_SESSION_SIZE + 1];
2582 size = ssn->ssl->session->session_id_length;
2583 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2585 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2587 vp = paircopy2(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2588 if (vp) pairadd(&vps, vp);
2590 vp = paircopy2(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2591 if (vp) pairadd(&vps, vp);
2593 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2594 if (vp) pairadd(&vps, vp);
2596 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2597 if (vp) pairadd(&vps, vp);
2599 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2602 * Hmm... the certs should probably be session data.
2606 * @todo: some go into reply, others into
2609 pairadd(&vps, paircopy(talloc_ctx, *certs));
2613 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2614 SSL_SESSION_set_ex_data(ssn->ssl->session,
2615 FR_TLS_EX_INDEX_VPS, vps);
2616 if (conf->session_cache_path) {
2617 /* write the VPs to the cache file */
2618 char filename[256], buf[1024];
2621 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2622 conf->session_cache_path, FR_DIR_SEP, buffer
2624 vp_file = fopen(filename, "w");
2625 if (vp_file == NULL) {
2626 RDEBUG2("Could not write session VPs to persistent cache: %s", fr_syserror(errno));
2629 /* generate a dummy user-style entry which is easy to read back */
2630 fprintf(vp_file, "# SSL cached session\n");
2631 fprintf(vp_file, "%s\n", buffer);
2632 for (vp = fr_cursor_init(&cursor, &vps);
2634 vp = fr_cursor_next(&cursor)) {
2635 vp_prints(buf, sizeof(buf), vp);
2636 fprintf(vp_file, "\t%s,\n", buf);
2642 RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2643 SSL_CTX_remove_session(ssn->ctx,
2648 * Else the session WAS allowed. Copy the cached
2653 char buffer[2 * MAX_SESSION_SIZE + 1];
2655 size = ssn->ssl->session->session_id_length;
2656 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2658 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2660 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2661 FR_TLS_EX_INDEX_VPS);
2663 RWDEBUG("No information in cached session %s", buffer);
2669 RDEBUG("Adding cached attributes for session %s:", buffer);
2670 debug_pair_list(vps);
2672 for (vp = fr_cursor_init(&cursor, &vps);
2674 vp = fr_cursor_next(&cursor)) {
2676 * TLS-* attrs get added back to
2679 if ((vp->da->vendor == 0) &&
2680 (vp->da->attr >= 1910) &&
2681 (vp->da->attr < 1929)) {
2682 pairadd(&request->packet->vps,
2683 paircopyvp(request->packet, vp));
2685 pairadd(&request->reply->vps,
2686 paircopyvp(request->reply, vp));
2690 if (conf->session_cache_path) {
2691 /* "touch" the cached session/vp file */
2694 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2695 conf->session_cache_path, FR_DIR_SEP, buffer
2697 utime(filename, NULL);
2698 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2699 conf->session_cache_path, FR_DIR_SEP, buffer
2701 utime(filename, NULL);
2705 * Mark the request as resumed.
2707 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2715 void tls_fail(tls_session_t *ssn)
2718 * Force the session to NOT be cached.
2720 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2723 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2730 * Decrypt the complete record.
2732 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2733 ssn->dirty_in.used);
2734 if (err != (int) ssn->dirty_in.used) {
2735 record_init(&ssn->dirty_in);
2736 RDEBUG("Failed writing %d to SSL BIO: %d",
2737 ssn->dirty_in.used, err);
2742 * Clear the dirty buffer now that we are done with it
2743 * and init the clean_out buffer to store decrypted data
2745 record_init(&ssn->dirty_in);
2746 record_init(&ssn->clean_out);
2749 * Read (and decrypt) the tunneled data from the
2750 * SSL session, and put it into the decrypted
2753 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2754 sizeof(ssn->clean_out.data));
2759 RDEBUG("SSL_read Error");
2761 code = SSL_get_error(ssn->ssl, err);
2763 case SSL_ERROR_WANT_READ:
2764 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2765 return FR_TLS_MORE_FRAGMENTS;
2767 case SSL_ERROR_WANT_WRITE:
2768 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2772 DEBUG("Error in fragmentation logic: %s",
2773 ERR_error_string(code, NULL));
2776 * FIXME: Call int_ssl_check?
2784 RWDEBUG("No data inside of the tunnel");
2788 * Passed all checks, successfully decrypted data
2790 ssn->clean_out.used = err;
2797 * Acknowledge received is for one of the following messages sent earlier
2798 * 1. Handshake completed Message, so now send, EAP-Success
2799 * 2. Alert Message, now send, EAP-Failure
2800 * 3. Fragment Message, now send, next Fragment
2802 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2804 RDEBUG2("Received TLS ACK");
2807 RERROR("FAIL: Unexpected ACK received. Could not obtain session information");
2808 return FR_TLS_INVALID;
2810 if (ssn->info.initialized == 0) {
2811 RDEBUG("No SSL info available. Waiting for more SSL data");
2812 return FR_TLS_REQUEST;
2814 if ((ssn->info.content_type == handshake) &&
2815 (ssn->info.origin == 0)) {
2816 RERROR("FAIL: ACK without earlier message");
2817 return FR_TLS_INVALID;
2820 switch (ssn->info.content_type) {
2822 RDEBUG2("ACK alert");
2826 if ((ssn->info.handshake_type == finished) &&
2827 (ssn->dirty_out.used == 0)) {
2828 RDEBUG2("ACK handshake is finished");
2831 * From now on all the content is
2832 * application data set it here as nobody else
2835 ssn->info.content_type = application_data;
2836 return FR_TLS_SUCCESS;
2837 } /* else more data to send */
2839 RDEBUG2("ACK handshake fragment handler");
2840 /* Fragmentation handler, send next fragment */
2841 return FR_TLS_REQUEST;
2843 case application_data:
2844 RDEBUG2("ACK handshake fragment handler in application data");
2845 return FR_TLS_REQUEST;
2848 * For the rest of the conditions, switch over
2849 * to the default section below.
2852 RDEBUG2("ACK default");
2853 RERROR("Invalid ACK received: %d",
2854 ssn->info.content_type);
2855 return FR_TLS_INVALID;
2859 #endif /* WITH_TLS */