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 tls_session_t *tls_new_session(fr_tls_server_conf_t *conf, REQUEST *request,
188 tls_session_t *state = NULL;
193 rad_assert(request != NULL);
196 * Manually flush the sessions every so often. If HALF
197 * of the session lifetime has passed since we last
198 * flushed, then flush it again.
200 * FIXME: Also do it every N sessions?
202 if (conf->session_cache_enable &&
203 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
204 RDEBUG2("Flushing SSL sessions (of #%ld)",
205 SSL_CTX_sess_number(conf->ctx));
207 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
208 conf->session_last_flushed = request->timestamp;
211 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
212 ERROR("SSL: Error creating new SSL: %s",
213 ERR_error_string(ERR_get_error(), NULL));
217 /* We use the SSL's "app_data" to indicate a call-back */
218 SSL_set_app_data(new_tls, NULL);
220 state = talloc_zero(conf, tls_session_t);
223 state->ctx = conf->ctx;
224 state->ssl = new_tls;
227 * Initialize callbacks
229 state->record_init = record_init;
230 state->record_close = record_close;
231 state->record_plus = record_plus;
232 state->record_minus = record_minus;
235 * Create & hook the BIOs to handle the dirty side of the
236 * SSL. This is *very important* as we want to handle
237 * the transmission part. Now the only IO interface
238 * that SSL is aware of, is our defined BIO buffers.
240 * This means that all SSL IO is done to/from memory,
241 * and we can update those BIOs from the packets we've
244 state->into_ssl = BIO_new(BIO_s_mem());
245 state->from_ssl = BIO_new(BIO_s_mem());
246 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
249 * Add the message callback to identify what type of
250 * message/handshake is passed
252 SSL_set_msg_callback(new_tls, cbtls_msg);
253 SSL_set_msg_callback_arg(new_tls, state);
254 SSL_set_info_callback(new_tls, cbtls_info);
257 * In Server mode we only accept.
259 SSL_set_accept_state(state->ssl);
262 * Verify the peer certificate, if asked.
265 RDEBUG2("Requiring client certificate");
266 verify_mode = SSL_VERIFY_PEER;
267 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
268 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
270 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
272 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
273 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
274 state->length_flag = conf->include_length;
277 * We use default fragment size, unless the Framed-MTU
278 * tells us it's too big. Note that we do NOT account
279 * for the EAP-TLS headers if conf->fragment_size is
280 * large, because that config item looks to be confusing.
282 * i.e. it should REALLY be called MTU, and the code here
283 * should figure out what that means for TLS fragment size.
284 * asking the administrator to know the internal details
285 * of EAP-TLS in order to calculate fragment sizes is
288 state->offset = conf->fragment_size;
289 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
290 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
291 state->offset = vp->vp_integer;
294 if (conf->session_cache_enable) {
295 state->allow_session_resumption = 1; /* otherwise it's zero */
304 * Print out some text describing the error.
306 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
311 if ((l = ERR_get_error()) != 0) {
312 char const *p = ERR_error_string(l, NULL);
314 if (request && p) REDEBUG("SSL says: %s", p);
316 e = SSL_get_error(s, ret);
320 * These seem to be harmless and already "dealt
321 * with" by our non-blocking environment. NB:
322 * "ZERO_RETURN" is the clean "error"
323 * indicating a successfully closed SSL
324 * tunnel. We let this happen because our IO
325 * loop should not appear to have broken on
326 * this condition - and outside the IO loop, the
327 * "shutdown" state is checked.
329 * Don't print anything if we ignore the error.
332 case SSL_ERROR_WANT_READ:
333 case SSL_ERROR_WANT_WRITE:
334 case SSL_ERROR_WANT_X509_LOOKUP:
335 case SSL_ERROR_ZERO_RETURN:
339 * These seem to be indications of a genuine
340 * error that should result in the SSL tunnel
341 * being regarded as "dead".
343 case SSL_ERROR_SYSCALL:
344 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
349 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
355 * For any other errors that (a) exist, and (b)
356 * crop up - we need to interpret what to do with
357 * them - so "politely inform" the caller that
358 * the code needs updating here.
360 ERROR("SSL: FATAL SSL error ..... %d\n", e);
368 * We are the server, we always get the dirty data
369 * (Handshake data is also considered as dirty data)
370 * During handshake, since SSL API handles itself,
371 * After clean-up, dirty_out will be filled with
372 * the data required for handshaking. So we check
373 * if dirty_out is empty then we simply send it back.
374 * As of now, if handshake is successful, then we keep going,
377 * Fill the Bio with the dirty data to clean it
378 * Get the cleaned data from SSL, if it is not Handshake data
380 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
384 if (ssn->invalid_hb_used) return 0;
386 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
387 if (err != (int) ssn->dirty_in.used) {
388 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
390 record_init(&ssn->dirty_in);
393 record_init(&ssn->dirty_in);
395 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
396 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
398 ssn->clean_out.used += err;
402 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
406 /* Some Extra STATE information for easy debugging */
407 if (SSL_is_init_finished(ssn->ssl)) {
408 DEBUG2("SSL Connection Established\n");
410 if (SSL_in_init(ssn->ssl)) {
411 DEBUG2("In SSL Handshake Phase\n");
413 if (SSL_in_before(ssn->ssl)) {
414 DEBUG2("Before SSL Handshake Phase\n");
416 if (SSL_in_accept_init(ssn->ssl)) {
417 DEBUG2("In SSL Accept mode \n");
419 if (SSL_in_connect_init(ssn->ssl)) {
420 DEBUG2("In SSL Connect mode \n");
423 err = BIO_ctrl_pending(ssn->from_ssl);
425 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
426 sizeof(ssn->dirty_out.data));
428 ssn->dirty_out.used = err;
430 } else if (BIO_should_retry(ssn->from_ssl)) {
431 record_init(&ssn->dirty_in);
432 DEBUG2(" tls: Asking for more data in tunnel");
436 int_ssl_check(request, ssn->ssl, err, "BIO_read");
437 record_init(&ssn->dirty_in);
441 DEBUG2("SSL Application Data");
442 /* Its clean application data, do whatever we want */
443 record_init(&ssn->clean_out);
446 /* We are done with dirty_in, reinitialize it */
447 record_init(&ssn->dirty_in);
452 * Take cleartext user data, and encrypt it into the output buffer,
453 * to send to the client at the other end of the SSL connection.
455 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
460 * If there's un-encrypted data in 'clean_in', then write
461 * that data to the SSL session, and then call the BIO function
462 * to get that encrypted data from the SSL session, into
463 * a buffer which we can then package into an EAP packet.
465 * Based on Server's logic this clean_in is expected to
466 * contain the data to send to the client.
468 if (ssn->clean_in.used > 0) {
471 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
472 record_minus(&ssn->clean_in, NULL, written);
474 /* Get the dirty data from Bio to send it */
475 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
476 sizeof(ssn->dirty_out.data));
478 ssn->dirty_out.used = err;
480 int_ssl_check(request, ssn->ssl, err, "handshake_send");
487 void session_init(tls_session_t *ssn)
490 ssn->into_ssl = ssn->from_ssl = NULL;
491 record_init(&ssn->clean_in);
492 record_init(&ssn->clean_out);
493 record_init(&ssn->dirty_in);
494 record_init(&ssn->dirty_out);
496 memset(&ssn->info, 0, sizeof(ssn->info));
500 ssn->tls_msg_len = 0;
501 ssn->length_flag = 0;
503 ssn->free_opaque = NULL;
506 void session_close(tls_session_t *ssn)
508 SSL_set_quiet_shutdown(ssn->ssl, 1);
509 SSL_shutdown(ssn->ssl);
516 record_close(&ssn->clean_in);
517 record_close(&ssn->clean_out);
518 record_close(&ssn->dirty_in);
519 record_close(&ssn->dirty_out);
523 void session_free(void *ssn)
525 tls_session_t *sess = (tls_session_t *)ssn;
530 * Free any opaque TTLS or PEAP data.
532 if ((sess->opaque) && (sess->free_opaque)) {
533 sess->free_opaque(sess->opaque);
542 static void record_init(record_t *rec)
547 static void record_close(record_t *rec)
554 * Copy data to the intermediate buffer, before we send
557 static unsigned int record_plus(record_t *rec, void const *ptr,
560 unsigned int added = MAX_RECORD_SIZE - rec->used;
566 memcpy(rec->data + rec->used, ptr, added);
572 * Take data from the buffer, and give it to the caller.
574 static unsigned int record_minus(record_t *rec, void *ptr,
577 unsigned int taken = rec->used;
584 memcpy(ptr, rec->data, taken);
588 * This is pretty bad...
591 memmove(rec->data, rec->data + taken, rec->used);
595 void tls_session_information(tls_session_t *tls_session)
597 char const *str_write_p, *str_version, *str_content_type = "";
598 char const *str_details1 = "", *str_details2= "";
602 * Don't print this out in the normal course of
605 if (debug_flag == 0) {
609 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
611 switch (tls_session->info.version) {
613 str_version = "SSL 2.0";
616 str_version = "SSL 3.0 ";
619 str_version = "TLS 1.0 ";
622 str_version = "Unknown TLS version";
626 if (tls_session->info.version == SSL3_VERSION ||
627 tls_session->info.version == TLS1_VERSION) {
628 switch (tls_session->info.content_type) {
629 case SSL3_RT_CHANGE_CIPHER_SPEC:
630 str_content_type = "ChangeCipherSpec";
633 str_content_type = "Alert";
635 case SSL3_RT_HANDSHAKE:
636 str_content_type = "Handshake";
638 case SSL3_RT_APPLICATION_DATA:
639 str_content_type = "ApplicationData";
642 str_content_type = "UnknownContentType";
646 if (tls_session->info.content_type == SSL3_RT_ALERT) {
647 str_details1 = ", ???";
649 if (tls_session->info.record_len == 2) {
651 switch (tls_session->info.alert_level) {
652 case SSL3_AL_WARNING:
653 str_details1 = ", warning";
656 str_details1 = ", fatal";
660 str_details2 = " ???";
661 switch (tls_session->info.alert_description) {
662 case SSL3_AD_CLOSE_NOTIFY:
663 str_details2 = " close_notify";
665 case SSL3_AD_UNEXPECTED_MESSAGE:
666 str_details2 = " unexpected_message";
668 case SSL3_AD_BAD_RECORD_MAC:
669 str_details2 = " bad_record_mac";
671 case TLS1_AD_DECRYPTION_FAILED:
672 str_details2 = " decryption_failed";
674 case TLS1_AD_RECORD_OVERFLOW:
675 str_details2 = " record_overflow";
677 case SSL3_AD_DECOMPRESSION_FAILURE:
678 str_details2 = " decompression_failure";
680 case SSL3_AD_HANDSHAKE_FAILURE:
681 str_details2 = " handshake_failure";
683 case SSL3_AD_BAD_CERTIFICATE:
684 str_details2 = " bad_certificate";
686 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
687 str_details2 = " unsupported_certificate";
689 case SSL3_AD_CERTIFICATE_REVOKED:
690 str_details2 = " certificate_revoked";
692 case SSL3_AD_CERTIFICATE_EXPIRED:
693 str_details2 = " certificate_expired";
695 case SSL3_AD_CERTIFICATE_UNKNOWN:
696 str_details2 = " certificate_unknown";
698 case SSL3_AD_ILLEGAL_PARAMETER:
699 str_details2 = " illegal_parameter";
701 case TLS1_AD_UNKNOWN_CA:
702 str_details2 = " unknown_ca";
704 case TLS1_AD_ACCESS_DENIED:
705 str_details2 = " access_denied";
707 case TLS1_AD_DECODE_ERROR:
708 str_details2 = " decode_error";
710 case TLS1_AD_DECRYPT_ERROR:
711 str_details2 = " decrypt_error";
713 case TLS1_AD_EXPORT_RESTRICTION:
714 str_details2 = " export_restriction";
716 case TLS1_AD_PROTOCOL_VERSION:
717 str_details2 = " protocol_version";
719 case TLS1_AD_INSUFFICIENT_SECURITY:
720 str_details2 = " insufficient_security";
722 case TLS1_AD_INTERNAL_ERROR:
723 str_details2 = " internal_error";
725 case TLS1_AD_USER_CANCELLED:
726 str_details2 = " user_canceled";
728 case TLS1_AD_NO_RENEGOTIATION:
729 str_details2 = " no_renegotiation";
735 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
736 str_details1 = "???";
738 if (tls_session->info.record_len > 0)
739 switch (tls_session->info.handshake_type) {
740 case SSL3_MT_HELLO_REQUEST:
741 str_details1 = ", HelloRequest";
743 case SSL3_MT_CLIENT_HELLO:
744 str_details1 = ", ClientHello";
746 case SSL3_MT_SERVER_HELLO:
747 str_details1 = ", ServerHello";
749 case SSL3_MT_CERTIFICATE:
750 str_details1 = ", Certificate";
752 case SSL3_MT_SERVER_KEY_EXCHANGE:
753 str_details1 = ", ServerKeyExchange";
755 case SSL3_MT_CERTIFICATE_REQUEST:
756 str_details1 = ", CertificateRequest";
758 case SSL3_MT_SERVER_DONE:
759 str_details1 = ", ServerHelloDone";
761 case SSL3_MT_CERTIFICATE_VERIFY:
762 str_details1 = ", CertificateVerify";
764 case SSL3_MT_CLIENT_KEY_EXCHANGE:
765 str_details1 = ", ClientKeyExchange";
767 case SSL3_MT_FINISHED:
768 str_details1 = ", Finished";
774 snprintf(tls_session->info.info_description,
775 sizeof(tls_session->info.info_description),
776 "%s %s%s [length %04lx]%s%s\n",
777 str_write_p, str_version, str_content_type,
778 (unsigned long)tls_session->info.record_len,
779 str_details1, str_details2);
781 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
783 RDEBUG2("%s", tls_session->info.info_description);
785 DEBUG2("%s", tls_session->info.info_description);
789 static CONF_PARSER cache_config[] = {
790 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
791 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
792 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
793 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
794 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
795 { NULL, -1, 0, NULL, NULL } /* end the list */
798 static CONF_PARSER verify_config[] = {
799 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
800 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
801 { NULL, -1, 0, NULL, NULL } /* end the list */
804 #ifdef HAVE_OPENSSL_OCSP_H
805 static CONF_PARSER ocsp_config[] = {
806 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
807 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
808 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
809 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
810 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
811 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "yes" },
812 { NULL, -1, 0, NULL, NULL } /* end the list */
816 static CONF_PARSER tls_server_config[] = {
817 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
818 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
819 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
820 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
821 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
822 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
823 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
824 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
825 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
826 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
827 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
828 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
829 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
830 #ifdef PSK_MAX_IDENTITY_LEN
831 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
832 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
834 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
835 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
836 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
837 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
838 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
839 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
840 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
841 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
842 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
843 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
845 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
846 #ifndef OPENSSL_NO_ECDH
847 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
851 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
853 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
855 #ifdef HAVE_OPENSSL_OCSP_H
856 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
859 { NULL, -1, 0, NULL, NULL } /* end the list */
863 static CONF_PARSER tls_client_config[] = {
864 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
865 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
866 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
867 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
868 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
869 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
870 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
871 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
872 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
873 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
874 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
875 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
876 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
877 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
878 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
879 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
880 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
881 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
882 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
884 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
885 #ifndef OPENSSL_NO_ECDH
886 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
890 { NULL, -1, 0, NULL, NULL } /* end the list */
895 * TODO: Check for the type of key exchange * like conf->dh_key
897 static int load_dh_params(SSL_CTX *ctx, char *file)
904 if ((bio = BIO_new_file(file, "r")) == NULL) {
905 ERROR("tls: Unable to open DH file - %s", file);
909 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
912 WARN("tls: Unable to set DH parameters. DH cipher suites may not work!");
913 WARN("Fix this by running the OpenSSL command listed in eap.conf");
917 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
918 ERROR("tls: Unable to set DH parameters");
929 * Generate ephemeral RSA keys.
931 static int generate_eph_rsa_key(SSL_CTX *ctx)
935 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
937 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
938 ERROR("tls: Couldn't set ephemeral RSA key");
946 /* index we use to store cached session VPs
947 * needs to be dynamic so we can supply a "free" function
949 static int FR_TLS_EX_INDEX_VPS = -1;
950 int FR_TLS_EX_INDEX_CERTS = -1;
953 * Print debugging messages, and free data.
955 * FIXME: Write sessions to some long-term storage, so that
956 * session resumption can still occur after the server
959 #define MAX_SESSION_SIZE (256)
961 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
964 char buffer[2 * MAX_SESSION_SIZE + 1];
965 fr_tls_server_conf_t *conf;
967 size = sess->session_id_length;
968 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
970 fr_bin2hex(buffer, sess->session_id, size);
972 DEBUG2(" SSL: Removing session %s from the cache", buffer);
973 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
974 if (conf && conf->session_cache_path) {
978 /* remove session and any cached VPs */
979 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
980 conf->session_cache_path, FR_DIR_SEP, buffer);
981 rv = unlink(filename);
983 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
985 /* VPs might be absent; might not have been written to disk yet */
986 snprintf(filename, sizeof(filename), "%s%c%s.vps",
987 conf->session_cache_path, FR_DIR_SEP, buffer);
994 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
997 char buffer[2 * MAX_SESSION_SIZE + 1];
998 fr_tls_server_conf_t *conf;
999 unsigned char *sess_blob = NULL;
1001 size = sess->session_id_length;
1002 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1004 fr_bin2hex(buffer, sess->session_id, size);
1006 DEBUG2(" SSL: adding session %s to cache", buffer);
1008 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1009 if (conf && conf->session_cache_path) {
1010 int fd, rv, todo, blob_len;
1014 /* find out what length data we need */
1015 blob_len = i2d_SSL_SESSION(sess, NULL);
1017 /* something went wrong */
1018 DEBUG2(" SSL: could not find buffer length to persist session");
1022 /* alloc and convert to ASN.1 */
1023 sess_blob = talloc_array(conf, unsigned char, blob_len);
1025 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1028 /* openssl mutates &p */
1030 rv = i2d_SSL_SESSION(sess, &p);
1031 if (rv != blob_len) {
1032 DEBUG2(" SSL: could not persist session");
1036 /* open output file */
1037 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1038 conf->session_cache_path, FR_DIR_SEP, buffer);
1039 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1041 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1048 rv = write(fd, p, todo);
1050 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1058 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1062 if (sess_blob) talloc_free(sess_blob);
1067 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1068 unsigned char *data, int len,
1072 char buffer[2 * MAX_SESSION_SIZE + 1];
1073 fr_tls_server_conf_t *conf;
1074 TALLOC_CTX *talloc_ctx;
1076 SSL_SESSION *sess = NULL;
1077 unsigned char *sess_data = NULL;
1078 PAIR_LIST *pairlist = NULL;
1081 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1083 fr_bin2hex(buffer, data, size);
1085 DEBUG2(" SSL: Client requested cached session %s", buffer);
1087 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1088 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1089 if (conf && conf->session_cache_path) {
1096 /* read in the cached VPs from the .vps file */
1097 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1098 conf->session_cache_path, FR_DIR_SEP, buffer);
1099 rv = pairlist_read(NULL, filename, &pairlist, 1);
1101 /* not safe to un-persist a session w/o VPs */
1102 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1106 /* load the actual SSL session */
1107 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1108 conf->session_cache_path, FR_DIR_SEP, buffer);
1109 fd = open(filename, O_RDONLY);
1111 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1115 rv = fstat(fd, &st);
1117 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1122 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1124 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1132 rv = read(fd, p, todo);
1134 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1143 /* openssl mutates &p */
1145 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1148 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1152 /* cache the VPs into the session */
1153 vp = paircopy(talloc_ctx, pairlist->reply);
1154 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1155 DEBUG2(" SSL: Successfully restored session %s", buffer);
1158 if (sess_data) talloc_free(sess_data);
1159 if (pairlist) pairlist_free(&pairlist);
1165 #ifdef HAVE_OPENSSL_OCSP_H
1167 * This function extracts the OCSP Responder URL
1168 * from an existing x509 certificate.
1170 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1171 char **ppath, int *pssl)
1175 AUTHORITY_INFO_ACCESS *aia;
1176 ACCESS_DESCRIPTION *ad;
1178 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1180 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1181 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1182 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1183 if (ad->location->type == GEN_URI) {
1184 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1185 phost, pport, ppath, pssl))
1194 * This function sends a OCSP request to a defined OCSP responder
1195 * and checks the OCSP response for correctness.
1198 /* Maximum leeway in validity period: default 5 minutes */
1199 #define MAX_VALIDITY_PERIOD (5 * 60)
1201 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1202 fr_tls_server_conf_t *conf)
1204 OCSP_CERTID *certid;
1206 OCSP_RESPONSE *resp = NULL;
1207 OCSP_BASICRESP *bresp = NULL;
1212 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1213 BIO *cbio, *bio_out;
1216 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1218 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1222 struct timeval when;
1226 * Create OCSP Request
1228 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1229 req = OCSP_REQUEST_new();
1230 OCSP_request_add0_id(req, certid);
1231 if(conf->ocsp_use_nonce) {
1232 OCSP_request_add1_nonce(req, NULL, 8);
1236 * Send OCSP Request and get OCSP Response
1239 /* Get OCSP responder URL */
1240 if (conf->ocsp_override_url) {
1243 memcpy(&url, &conf->ocsp_url, sizeof(url));
1244 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1245 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1248 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1251 if (!host || !port || !path) {
1252 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP");
1257 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1259 /* Setup BIO socket to OCSP responder */
1260 cbio = BIO_new_connect(host);
1262 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1264 BIO_set_conn_port(cbio, port);
1265 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1266 BIO_do_connect(cbio);
1268 /* Send OCSP request and wait for response */
1269 resp = OCSP_sendreq_bio(cbio, path, req);
1271 ERROR("Couldn't get OCSP response");
1276 if (conf->ocsp_timeout)
1277 BIO_set_nbio(cbio, 1);
1279 rc = BIO_do_connect(cbio);
1280 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1281 ERROR("Couldn't connect to OCSP responder");
1286 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1288 ERROR("Couldn't send OCSP request");
1293 gettimeofday(&when, NULL);
1294 when.tv_sec += conf->ocsp_timeout;
1297 rc = OCSP_sendreq_nbio(&resp, ctx);
1298 if (conf->ocsp_timeout) {
1299 gettimeofday(&now, NULL);
1300 if (!timercmp(&now, &when, <))
1303 } while ((rc == -1) && BIO_should_retry(cbio));
1305 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1306 ERROR("OCSP response timed out");
1311 OCSP_REQ_CTX_free(ctx);
1314 ERROR("Couldn't get OCSP response");
1320 /* Verify OCSP response status */
1321 status = OCSP_response_status(resp);
1322 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1323 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1324 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1327 bresp = OCSP_response_get1_basic(resp);
1328 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1329 ERROR("OCSP response has wrong nonce value");
1332 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1333 ERROR("Couldn't verify OCSP basic response");
1337 /* Verify OCSP cert status */
1338 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1339 &rev, &thisupd, &nextupd)) {
1340 ERROR("No Status found.\n");
1344 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1345 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1346 ERR_print_errors(bio_out);
1349 BIO_puts(bio_out, "\tThis Update: ");
1350 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1351 BIO_puts(bio_out, "\n");
1353 BIO_puts(bio_out, "\tNext Update: ");
1354 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1355 BIO_puts(bio_out, "\n");
1359 case V_OCSP_CERTSTATUS_GOOD:
1360 DEBUG2("[oscp] --> Cert status: good");
1365 /* REVOKED / UNKNOWN */
1366 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1368 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1369 BIO_puts(bio_out, "\tRevocation Time: ");
1370 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1371 BIO_puts(bio_out, "\n");
1376 /* Free OCSP Stuff */
1377 OCSP_REQUEST_free(req);
1378 OCSP_RESPONSE_free(resp);
1383 OCSP_BASICRESP_free(bresp);
1388 DEBUG2("[ocsp] --> Certificate is valid!");
1391 if (conf->ocsp_softfail) {
1392 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1393 DEBUG2("[ocsp] --> Warning! This may be insecure");
1396 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1401 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1407 #endif /* HAVE_OPENSSL_OCSP_H */
1410 * For creating certificate attributes.
1412 static char const *cert_attr_names[8][2] = {
1413 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1414 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1415 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1416 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1417 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1418 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1419 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1420 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1423 #define FR_TLS_SERIAL (0)
1424 #define FR_TLS_EXPIRATION (1)
1425 #define FR_TLS_SUBJECT (2)
1426 #define FR_TLS_ISSUER (3)
1427 #define FR_TLS_CN (4)
1428 #define FR_TLS_SAN_EMAIL (5)
1429 #define FR_TLS_SAN_DNS (6)
1430 #define FR_TLS_SAN_UPN (7)
1433 * Before trusting a certificate, you must make sure that the
1434 * certificate is 'valid'. There are several steps that your
1435 * application can take in determining if a certificate is
1436 * valid. Commonly used steps are:
1438 * 1.Verifying the certificate's signature, and verifying that
1439 * the certificate has been issued by a trusted Certificate
1442 * 2.Verifying that the certificate is valid for the present date
1443 * (i.e. it is being presented within its validity dates).
1445 * 3.Verifying that the certificate has not been revoked by its
1446 * issuing Certificate Authority, by checking with respect to a
1447 * Certificate Revocation List (CRL).
1449 * 4.Verifying that the credentials presented by the certificate
1450 * fulfill additional requirements specific to the application,
1451 * such as with respect to access control lists or with respect
1452 * to OCSP (Online Certificate Status Processing).
1454 * NOTE: This callback will be called multiple times based on the
1455 * depth of the root certificate chain
1457 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1459 char subject[1024]; /* Used for the subject name */
1460 char issuer[1024]; /* Used for the issuer name */
1461 char attribute[1024];
1463 char common_name[1024];
1467 X509_CINF *client_inf;
1468 STACK_OF(X509_EXTENSION) *ext_list;
1470 int err, depth, lookup, loc;
1471 fr_tls_server_conf_t *conf;
1474 ASN1_INTEGER *sn = NULL;
1475 ASN1_TIME *asn_time = NULL;
1478 #ifdef HAVE_OPENSSL_OCSP_H
1479 X509_STORE *ocsp_store = NULL;
1482 TALLOC_CTX *talloc_ctx;
1484 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1485 err = X509_STORE_CTX_get_error(ctx);
1486 depth = X509_STORE_CTX_get_error_depth(ctx);
1491 * Log client/issuing cert. If there's an error, log
1494 if ((lookup > 1) && !my_ok) lookup = 1;
1497 * Retrieve the pointer to the SSL of the connection currently treated
1498 * and the application specific data stored into the SSL object.
1500 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1501 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1502 if (!conf) return 1;
1504 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1505 rad_assert(request != NULL);
1506 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1508 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1509 #ifdef HAVE_OPENSSL_OCSP_H
1510 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1513 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1516 * Get the Serial Number
1519 sn = X509_get_serialNumber(client_cert);
1522 * For this next bit, we create the attributes *only* if
1523 * we're at the client or issuing certificate, AND we
1524 * have a user identity. i.e. we don't create the
1525 * attributes for RadSec connections.
1527 if (certs && identity &&
1528 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1532 for (i = 0; i < sn->length; i++) {
1533 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1536 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1541 * Get the Expiration Date
1544 asn_time = X509_get_notAfter(client_cert);
1545 if (certs && identity && (lookup <= 1) && asn_time &&
1546 (asn_time->length < (int) sizeof(buf))) {
1547 memcpy(buf, (char*) asn_time->data, asn_time->length);
1548 buf[asn_time->length] = '\0';
1549 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1553 * Get the Subject & Issuer
1555 subject[0] = issuer[0] = '\0';
1556 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1558 subject[sizeof(subject) - 1] = '\0';
1559 if (certs && identity && (lookup <= 1) && subject[0]) {
1560 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1563 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1565 issuer[sizeof(issuer) - 1] = '\0';
1566 if (certs && identity && (lookup <= 1) && issuer[0]) {
1567 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1571 * Get the Common Name, if there is a subject.
1573 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1574 NID_commonName, common_name, sizeof(common_name));
1575 common_name[sizeof(common_name) - 1] = '\0';
1576 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1577 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1581 * Get the RFC822 Subject Alternative Name
1583 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1584 if (certs && (lookup <= 1) && (loc >= 0)) {
1585 X509_EXTENSION *ext = NULL;
1586 GENERAL_NAMES *names = NULL;
1589 if ((ext = X509_get_ext(client_cert, loc)) &&
1590 (names = X509V3_EXT_d2i(ext))) {
1591 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1592 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1594 switch (name->type) {
1597 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1598 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1600 #endif /* GEN_EMAIL */
1603 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1604 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1606 #endif /* GEN_DNS */
1607 #ifdef GEN_OTHERNAME
1609 /* look for a MS UPN */
1610 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1611 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1612 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1613 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1614 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1617 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)\n");
1622 #endif /* GEN_OTHERNAME */
1624 /* XXX TODO handle other SAN types */
1630 sk_GENERAL_NAME_free(names);
1634 * If the CRL has expired, that might still be OK.
1637 (conf->allow_expired_crl) &&
1638 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1640 X509_STORE_CTX_set_error( ctx, 0 );
1644 char const *p = X509_verify_cert_error_string(err);
1645 ERROR("--> verify error:num=%d:%s\n",err, p);
1646 REDEBUG("SSL says error %d : %s", err, p);
1651 client_inf = client_cert->cert_info;
1652 ext_list = client_inf->extensions;
1658 * Grab the X509 extensions, and create attributes out of them.
1659 * For laziness, we re-use the OpenSSL names
1661 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1666 out = BIO_new(BIO_s_mem());
1667 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1669 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1671 X509_EXTENSION *ext;
1674 ext = sk_X509_EXTENSION_value(ext_list, i);
1676 obj = X509_EXTENSION_get_object(ext);
1677 i2a_ASN1_OBJECT(out, obj);
1678 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1679 if (len <= 0) continue;
1681 attribute[16 + len] = '\0';
1683 X509V3_EXT_print(out, ext, 0, 0);
1684 len = BIO_read(out, value , sizeof(value) - 1);
1685 if (len <= 0) continue;
1690 * Mash the OpenSSL name to our name, and
1691 * create the attribute.
1693 for (p = value + 16; *p != '\0'; p++) {
1694 if (*p == ' ') *p = '-';
1697 vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1698 if (vp) debug_pair_list(vp);
1704 switch (ctx->error) {
1706 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1707 ERROR("issuer= %s\n", issuer);
1709 case X509_V_ERR_CERT_NOT_YET_VALID:
1710 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1711 ERROR("notBefore=");
1713 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1716 case X509_V_ERR_CERT_HAS_EXPIRED:
1717 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1720 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1726 * If we're at the actual client cert, apply additional
1731 * If the conf tells us to, check cert issuer
1732 * against the specified value and fail
1733 * verification if they don't match.
1735 if (conf->check_cert_issuer &&
1736 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1737 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1742 * If the conf tells us to, check the CN in the
1743 * cert against xlat'ed value, but only if the
1744 * previous checks passed.
1746 if (my_ok && conf->check_cert_cn) {
1747 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1748 /* if this fails, fail the verification */
1751 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1752 if (strcmp(cn_str, common_name) != 0) {
1753 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1757 } /* check_cert_cn */
1759 #ifdef HAVE_OPENSSL_OCSP_H
1760 if (my_ok && conf->ocsp_enable){
1761 RDEBUG2("--> Starting OCSP Request");
1762 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1763 ERROR("Couldn't get issuer_cert for %s", common_name);
1765 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1769 while (conf->verify_client_cert_cmd) {
1774 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1775 conf->verify_tmp_dir, progname);
1776 fd = mkstemp(filename);
1778 RDEBUG("Failed creating file in %s: %s",
1779 conf->verify_tmp_dir, fr_syserror(errno));
1783 fp = fdopen(fd, "w");
1786 RDEBUG("Failed opening file %s: %s",
1787 filename, fr_syserror(errno));
1791 if (!PEM_write_X509(fp, client_cert)) {
1793 RDEBUG("Failed writing certificate to file");
1798 if (!pairmake_packet("TLS-Client-Cert-Filename",
1799 filename, T_OP_SET)) {
1800 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1805 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1806 if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1807 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1808 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1811 RDEBUG("Client certificate CN %s passed external validation", common_name);
1822 if (debug_flag > 0) {
1823 RDEBUG2("chain-depth=%d, ", depth);
1824 RDEBUG2("error=%d", err);
1826 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1827 RDEBUG2("--> BUF-Name = %s", common_name);
1828 RDEBUG2("--> subject = %s", subject);
1829 RDEBUG2("--> issuer = %s", issuer);
1830 RDEBUG2("--> verify return:%d", my_ok);
1836 #ifdef HAVE_OPENSSL_OCSP_H
1838 * Create Global X509 revocation store and use it to verify
1841 * - Load the trusted CAs
1842 * - Load the trusted issuer certificates
1844 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1846 X509_STORE *store = NULL;
1848 store = X509_STORE_new();
1850 /* Load the CAs we trust */
1851 if (conf->ca_file || conf->ca_path)
1852 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1853 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1854 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1858 #ifdef X509_V_FLAG_CRL_CHECK
1859 if (conf->check_crl)
1860 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1864 #endif /* HAVE_OPENSSL_OCSP_H */
1866 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1867 #ifndef OPENSSL_NO_ECDH
1868 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1873 if (!ecdh_curve || !*ecdh_curve) return 0;
1875 nid = OBJ_sn2nid(ecdh_curve);
1877 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1881 ecdh = EC_KEY_new_by_curve_name(nid);
1883 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1887 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1889 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1899 * DIE OPENSSL DIE DIE DIE
1901 * What a palaver, just to free some data attached the
1902 * session. We need to do this because the "remove" callback
1903 * is called when refcount > 0 sometimes, if another thread
1904 * is using the session
1906 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1907 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1908 UNUSED long argl, UNUSED void *argp)
1910 VALUE_PAIR *vp = data_ptr;
1913 DEBUG2(" Freeing cached session VPs");;
1918 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
1919 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1920 UNUSED long argl, UNUSED void *argp)
1922 VALUE_PAIR **certs = data_ptr;
1925 DEBUG2(" Freeing cached session Certificates");
1930 /** Add all the default ciphers and message digests reate our context.
1932 * This should be called exactly once from main, before reading the main config
1933 * or initialising any modules.
1935 void tls_global_init(void)
1937 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
1938 SSL_library_init(); /* initialize library */
1939 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
1940 OPENSSL_config(NULL);
1943 /** Check for vulnerable versions of libssl
1945 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
1946 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
1948 int tls_global_version_check(char const *acknowledged)
1952 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
1956 /* Check for bad versions */
1957 v = (uint64_t) SSLeay();
1959 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
1960 libssl_defect_t *defect = &libssl_defects[i];
1962 if ((v >= defect->low) && (v <= defect->high)) {
1963 ERROR("Refusing to start with libssl version %s (in range %s)",
1964 ssl_version(), ssl_version_range(defect->low, defect->high));
1965 ERROR("Security advisory %s (%s)", defect->id, defect->name);
1966 ERROR("%s", defect->comment);
1973 INFO("Once you have verified libssl has been correctly patched, "
1974 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
1982 /** Free any memory alloced by libssl
1985 void tls_global_cleanup(void)
1987 ERR_remove_state(0);
1989 CONF_modules_unload(1);
1992 CRYPTO_cleanup_all_ex_data();
1996 * Create Global context SSL and use it in every new session
1998 * - Load the trusted CAs
1999 * - Load the Private key & the certificate
2000 * - Set the Context options & Verify options
2002 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
2005 X509_STORE *certstore;
2006 int verify_mode = SSL_VERIFY_NONE;
2007 int ctx_options = 0;
2011 * SHA256 is in all versions of OpenSSL, but isn't
2012 * initialized by default. It's needed for WiMAX
2015 #ifdef HAVE_OPENSSL_EVP_SHA256
2016 EVP_add_digest(EVP_sha256());
2019 ctx = SSL_CTX_new(TLSv1_method());
2022 while ((err = ERR_get_error())) {
2023 DEBUG("Failed creating SSL context: %s",
2024 ERR_error_string(err, NULL));
2030 * Save the config on the context so that callbacks which
2031 * only get SSL_CTX* e.g. session persistence, can get it
2033 SSL_CTX_set_app_data(ctx, conf);
2036 * Identify the type of certificates that needs to be loaded
2038 if (conf->file_type) {
2039 type = SSL_FILETYPE_PEM;
2041 type = SSL_FILETYPE_ASN1;
2045 * Set the password to load private key
2047 if (conf->private_key_password) {
2050 * We don't want to put the private key password in eap.conf, so check
2051 * for our special string which indicates we should get the password
2054 char const* special_string = "Apple:UseCertAdmin";
2055 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2058 long const max_password_len = 128;
2059 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2060 conf->private_key_file);
2062 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2064 FILE* cmd_pipe = popen(cmd, "r");
2066 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2067 ERROR("Error reading private_key_file %s", conf->private_key_file);
2071 rad_const_free(conf->private_key_password);
2072 password = talloc_array(conf, char, max_password_len);
2074 ERROR("TLS: Can't allocate space for private_key_password");
2075 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2080 fgets(password, max_password_len, cmd_pipe);
2083 /* Get rid of newline at end of password. */
2084 password[strlen(password) - 1] = '\0';
2086 DEBUG3("tls: Password from command = \"%s\"", password);
2087 conf->private_key_password = password;
2094 memcpy(&password, &conf->private_key_password, sizeof(password));
2095 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2096 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2100 #ifdef PSK_MAX_IDENTITY_LEN
2101 if ((conf->psk_identity && !conf->psk_password) ||
2102 (!conf->psk_identity && conf->psk_password) ||
2103 (conf->psk_identity && !*conf->psk_identity) ||
2104 (conf->psk_password && !*conf->psk_password)) {
2105 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2109 if (conf->psk_identity) {
2110 size_t psk_len, hex_len;
2111 char buffer[PSK_MAX_PSK_LEN];
2113 if (conf->certificate_file ||
2114 conf->private_key_password || conf->private_key_file ||
2115 conf->ca_file || conf->ca_path) {
2116 ERROR("When PSKs are used, No certificate configuration is permitted");
2121 SSL_CTX_set_psk_client_callback(ctx,
2122 psk_client_callback);
2124 SSL_CTX_set_psk_server_callback(ctx,
2125 psk_server_callback);
2128 psk_len = strlen(conf->psk_password);
2129 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2130 ERROR("psk_hexphrase is too long (max %d)",
2135 hex_len = fr_hex2bin((uint8_t *) buffer, sizeof(buffer), conf->psk_password, psk_len);
2136 if (psk_len != (2 * hex_len)) {
2137 ERROR("psk_hexphrase is not all hex");
2144 (void) client; /* -Wunused */
2148 * Load our keys and certificates
2150 * If certificates are of type PEM then we can make use
2151 * of cert chain authentication using openssl api call
2152 * SSL_CTX_use_certificate_chain_file. Please see how
2153 * the cert chain needs to be given in PEM from
2156 if (!conf->certificate_file) goto load_ca;
2158 if (type == SSL_FILETYPE_PEM) {
2159 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2160 ERROR("Error reading certificate file %s:%s",
2161 conf->certificate_file,
2162 ERR_error_string(ERR_get_error(), NULL));
2166 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2167 ERROR("Error reading certificate file %s:%s",
2168 conf->certificate_file,
2169 ERR_error_string(ERR_get_error(), NULL));
2173 /* Load the CAs we trust */
2175 if (conf->ca_file || conf->ca_path) {
2176 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2177 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2178 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2182 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2184 if (conf->private_key_file) {
2185 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2186 ERROR("Failed reading private key file %s:%s",
2187 conf->private_key_file,
2188 ERR_error_string(ERR_get_error(), NULL));
2193 * Check if the loaded private key is the right one
2195 if (!SSL_CTX_check_private_key(ctx)) {
2196 ERROR("Private key does not match the certificate public key");
2201 #ifdef PSK_MAX_IDENTITY_LEN
2208 ctx_options |= SSL_OP_NO_SSLv2;
2209 ctx_options |= SSL_OP_NO_SSLv3;
2210 #ifdef SSL_OP_NO_TICKET
2211 ctx_options |= SSL_OP_NO_TICKET ;
2215 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2216 * small subgroup attacks and forward secrecy. Always
2219 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2220 * time needed during negotiation, but it is not very
2223 ctx_options |= SSL_OP_SINGLE_DH_USE;
2226 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2227 * in Windows Vista client.
2228 * http://www.openssl.org/~bodo/tls-cbc.txt
2229 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2231 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2233 SSL_CTX_set_options(ctx, ctx_options);
2236 * TODO: Set the RSA & DH
2237 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2238 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2242 * set the message callback to identify the type of
2243 * message. For every new session, there can be a
2244 * different callback argument.
2246 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2250 * Set eliptical curve crypto configuration.
2252 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2253 #ifndef OPENSSL_NO_ECDH
2254 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2260 /* Set Info callback */
2261 SSL_CTX_set_info_callback(ctx, cbtls_info);
2264 * Callbacks, etc. for session resumption.
2266 if (conf->session_cache_enable) {
2267 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2268 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2269 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2271 SSL_CTX_set_quiet_shutdown(ctx, 1);
2272 if (FR_TLS_EX_INDEX_VPS < 0)
2273 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2274 if (FR_TLS_EX_INDEX_CERTS < 0)
2275 FR_TLS_EX_INDEX_CERTS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2279 * Check the certificates for revocation.
2281 #ifdef X509_V_FLAG_CRL_CHECK
2282 if (conf->check_crl) {
2283 certstore = SSL_CTX_get_cert_store(ctx);
2284 if (certstore == NULL) {
2285 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2286 ERROR("tls: Error reading Certificate Store");
2289 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2295 * Always verify the peer certificate
2297 verify_mode |= SSL_VERIFY_PEER;
2298 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2299 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2300 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2302 if (conf->verify_depth) {
2303 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2306 /* Load randomness */
2307 if (conf->random_file) {
2308 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2309 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2310 ERROR("tls: Error loading randomness");
2316 * Set the cipher list if we were told to
2318 if (conf->cipher_list) {
2319 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2320 ERROR("tls: Error setting cipher list");
2326 * Setup session caching
2328 if (conf->session_cache_enable) {
2330 * Create a unique context Id per EAP-TLS configuration.
2332 if (conf->session_id_name) {
2333 snprintf(conf->session_context_id,
2334 sizeof(conf->session_context_id),
2336 conf->session_id_name);
2338 snprintf(conf->session_context_id,
2339 sizeof(conf->session_context_id),
2344 * Cache it, and DON'T auto-clear it.
2346 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2348 SSL_CTX_set_session_id_context(ctx,
2349 (unsigned char *) conf->session_context_id,
2350 (unsigned int) strlen(conf->session_context_id));
2353 * Our timeout is in hours, this is in seconds.
2355 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2358 * Set the maximum number of entries in the
2361 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2364 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2372 * Free TLS client/server config
2373 * Should not be called outside this code, as a callback is
2374 * added to automatically free the data when the CONF_SECTION
2377 static int tls_server_conf_free(fr_tls_server_conf_t *conf)
2379 if (conf->ctx) SSL_CTX_free(conf->ctx);
2381 #ifdef HAVE_OPENSSL_OCSP_H
2382 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2383 conf->ocsp_store = NULL;
2387 memset(conf, 0, sizeof(*conf));
2393 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2395 fr_tls_server_conf_t *conf;
2398 * If cs has already been parsed there should be a cached copy
2399 * of conf already stored, so just return that.
2401 conf = cf_data_find(cs, "tls-conf");
2403 DEBUG("Using cached TLS configuration from previous invocation");
2407 conf = talloc_zero(cs, fr_tls_server_conf_t);
2409 ERROR("Out of memory");
2413 talloc_set_destructor(conf, tls_server_conf_free);
2415 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2422 * Save people from their own stupidity.
2424 if (conf->fragment_size < 100) conf->fragment_size = 100;
2426 if (!conf->private_key_file) {
2427 ERROR("TLS Server requires a private key file");
2431 if (!conf->certificate_file) {
2432 ERROR("TLS Server requires a certificate file");
2439 conf->ctx = init_tls_ctx(conf, 0);
2440 if (conf->ctx == NULL) {
2444 #ifdef HAVE_OPENSSL_OCSP_H
2446 * Initialize OCSP Revocation Store
2448 if (conf->ocsp_enable) {
2449 conf->ocsp_store = init_revocation_store(conf);
2450 if (conf->ocsp_store == NULL) goto error;
2452 #endif /*HAVE_OPENSSL_OCSP_H*/
2456 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2457 if (load_dh_params(conf->ctx, dh_file) < 0) {
2462 if (generate_eph_rsa_key(conf->ctx) < 0) {
2466 if (conf->verify_tmp_dir) {
2467 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2468 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2473 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2474 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2479 * Cache conf in cs in case we're asked to parse this again.
2481 cf_data_add(cs, "tls-conf", conf, NULL);
2486 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2488 fr_tls_server_conf_t *conf;
2490 conf = cf_data_find(cs, "tls-conf");
2492 DEBUG("Using cached TLS configuration from previous invocation");
2496 conf = talloc_zero(cs, fr_tls_server_conf_t);
2498 ERROR("Out of memory");
2502 talloc_set_destructor(conf, tls_server_conf_free);
2504 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2511 * Save people from their own stupidity.
2513 if (conf->fragment_size < 100) conf->fragment_size = 100;
2518 conf->ctx = init_tls_ctx(conf, 1);
2519 if (conf->ctx == NULL) {
2526 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2527 if (load_dh_params(conf->ctx, dh_file) < 0) {
2532 if (generate_eph_rsa_key(conf->ctx) < 0) {
2536 cf_data_add(cs, "tls-conf", conf, NULL);
2541 int tls_success(tls_session_t *ssn, REQUEST *request)
2543 VALUE_PAIR *vp, *vps = NULL;
2544 fr_tls_server_conf_t *conf;
2545 TALLOC_CTX *talloc_ctx;
2547 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2548 rad_assert(conf != NULL);
2550 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2553 * If there's no session resumption, delete the entry
2554 * from the cache. This means either it's disabled
2555 * globally for this SSL context, OR we were told to
2556 * disable it for this user.
2558 * This also means you can't turn it on just for one
2561 if ((!ssn->allow_session_resumption) ||
2562 (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2563 (vp->vp_integer == 0))) {
2564 SSL_CTX_remove_session(ssn->ctx,
2566 ssn->allow_session_resumption = 0;
2569 * If we're in a resumed session and it's
2572 if (SSL_session_reused(ssn->ssl)) {
2573 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2578 * Else resumption IS allowed, so we store the
2579 * user data in the cache.
2581 } else if (!SSL_session_reused(ssn->ssl)) {
2584 char buffer[2 * MAX_SESSION_SIZE + 1];
2586 size = ssn->ssl->session->session_id_length;
2587 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2589 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2591 vp = paircopy2(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2592 if (vp) pairadd(&vps, vp);
2594 vp = paircopy2(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2595 if (vp) pairadd(&vps, vp);
2597 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2598 if (vp) pairadd(&vps, vp);
2600 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2601 if (vp) pairadd(&vps, vp);
2603 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2606 * Hmm... the certs should probably be session data.
2610 * @todo: some go into reply, others into
2613 pairadd(&vps, paircopy(talloc_ctx, *certs));
2617 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2618 SSL_SESSION_set_ex_data(ssn->ssl->session,
2619 FR_TLS_EX_INDEX_VPS, vps);
2620 if (conf->session_cache_path) {
2621 /* write the VPs to the cache file */
2622 char filename[256], buf[1024];
2625 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2626 conf->session_cache_path, FR_DIR_SEP, buffer
2628 vp_file = fopen(filename, "w");
2629 if (vp_file == NULL) {
2630 RDEBUG2("Could not write session VPs to persistent cache: %s", fr_syserror(errno));
2633 /* generate a dummy user-style entry which is easy to read back */
2634 fprintf(vp_file, "# SSL cached session\n");
2635 fprintf(vp_file, "%s\n", buffer);
2636 for (vp = fr_cursor_init(&cursor, &vps);
2638 vp = fr_cursor_next(&cursor)) {
2639 vp_prints(buf, sizeof(buf), vp);
2640 fprintf(vp_file, "\t%s,\n", buf);
2646 RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2647 SSL_CTX_remove_session(ssn->ctx,
2652 * Else the session WAS allowed. Copy the cached
2657 char buffer[2 * MAX_SESSION_SIZE + 1];
2659 size = ssn->ssl->session->session_id_length;
2660 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2662 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2664 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2665 FR_TLS_EX_INDEX_VPS);
2667 RWDEBUG("No information in cached session %s", buffer);
2673 RDEBUG("Adding cached attributes for session %s:", buffer);
2674 debug_pair_list(vps);
2676 for (vp = fr_cursor_init(&cursor, &vps);
2678 vp = fr_cursor_next(&cursor)) {
2680 * TLS-* attrs get added back to
2683 if ((vp->da->vendor == 0) &&
2684 (vp->da->attr >= 1910) &&
2685 (vp->da->attr < 1929)) {
2686 pairadd(&request->packet->vps,
2687 paircopyvp(request->reply, vp));
2689 pairadd(&request->reply->vps,
2690 paircopyvp(request->reply, vp));
2694 if (conf->session_cache_path) {
2695 /* "touch" the cached session/vp file */
2698 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2699 conf->session_cache_path, FR_DIR_SEP, buffer
2701 utime(filename, NULL);
2702 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2703 conf->session_cache_path, FR_DIR_SEP, buffer
2705 utime(filename, NULL);
2709 * Mark the request as resumed.
2711 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2719 void tls_fail(tls_session_t *ssn)
2722 * Force the session to NOT be cached.
2724 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2727 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2734 * Decrypt the complete record.
2736 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2737 ssn->dirty_in.used);
2738 if (err != (int) ssn->dirty_in.used) {
2739 record_init(&ssn->dirty_in);
2740 RDEBUG("Failed writing %d to SSL BIO: %d",
2741 ssn->dirty_in.used, err);
2746 * Clear the dirty buffer now that we are done with it
2747 * and init the clean_out buffer to store decrypted data
2749 record_init(&ssn->dirty_in);
2750 record_init(&ssn->clean_out);
2753 * Read (and decrypt) the tunneled data from the
2754 * SSL session, and put it into the decrypted
2757 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2758 sizeof(ssn->clean_out.data));
2763 RDEBUG("SSL_read Error");
2765 code = SSL_get_error(ssn->ssl, err);
2767 case SSL_ERROR_WANT_READ:
2768 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2769 return FR_TLS_MORE_FRAGMENTS;
2771 case SSL_ERROR_WANT_WRITE:
2772 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2776 DEBUG("Error in fragmentation logic: %s",
2777 ERR_error_string(code, NULL));
2780 * FIXME: Call int_ssl_check?
2788 RWDEBUG("No data inside of the tunnel");
2792 * Passed all checks, successfully decrypted data
2794 ssn->clean_out.used = err;
2801 * Acknowledge received is for one of the following messages sent earlier
2802 * 1. Handshake completed Message, so now send, EAP-Success
2803 * 2. Alert Message, now send, EAP-Failure
2804 * 3. Fragment Message, now send, next Fragment
2806 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2808 RDEBUG2("Received TLS ACK");
2811 RERROR("FAIL: Unexpected ACK received. Could not obtain session information");
2812 return FR_TLS_INVALID;
2814 if (ssn->info.initialized == 0) {
2815 RDEBUG("No SSL info available. Waiting for more SSL data");
2816 return FR_TLS_REQUEST;
2818 if ((ssn->info.content_type == handshake) &&
2819 (ssn->info.origin == 0)) {
2820 RERROR("FAIL: ACK without earlier message");
2821 return FR_TLS_INVALID;
2824 switch (ssn->info.content_type) {
2826 RDEBUG2("ACK alert");
2830 if ((ssn->info.handshake_type == finished) &&
2831 (ssn->dirty_out.used == 0)) {
2832 RDEBUG2("ACK handshake is finished");
2835 * From now on all the content is
2836 * application data set it here as nobody else
2839 ssn->info.content_type = application_data;
2840 return FR_TLS_SUCCESS;
2841 } /* else more data to send */
2843 RDEBUG2("ACK handshake fragment handler");
2844 /* Fragmentation handler, send next fragment */
2845 return FR_TLS_REQUEST;
2847 case application_data:
2848 RDEBUG2("ACK handshake fragment handler in application data");
2849 return FR_TLS_REQUEST;
2852 * For the rest of the conditions, switch over
2853 * to the default section below.
2856 RDEBUG2("ACK default");
2857 RERROR("Invalid ACK received: %d",
2858 ssn->info.content_type);
2859 return FR_TLS_INVALID;
2863 #endif /* WITH_TLS */