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, 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, 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;
133 ssn = talloc_zero(conf, tls_session_t);
134 if (!ssn) return NULL;
136 ssn->ctx = conf->ctx;
138 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
140 ssn->ssl = SSL_new(ssn->ctx);
141 rad_assert(ssn->ssl != NULL);
144 * Add the message callback to identify what type of
145 * message/handshake is passed
147 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
148 SSL_set_msg_callback_arg(ssn->ssl, ssn);
149 SSL_set_info_callback(ssn->ssl, cbtls_info);
152 * Always verify the peer certificate.
154 DEBUG2("Requiring Server certificate");
155 verify_mode = SSL_VERIFY_PEER;
156 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
157 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
159 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
160 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
161 SSL_set_fd(ssn->ssl, fd);
162 if (SSL_connect(ssn->ssl) <= 0) {
164 while ((err = ERR_get_error())) {
165 DEBUG("OpenSSL Err says %s",
166 ERR_error_string(err, NULL));
173 ssn->offset = conf->fragment_size;
178 tls_session_t *tls_new_session(fr_tls_server_conf_t *conf, REQUEST *request,
181 tls_session_t *state = NULL;
186 rad_assert(request != NULL);
189 * Manually flush the sessions every so often. If HALF
190 * of the session lifetime has passed since we last
191 * flushed, then flush it again.
193 * FIXME: Also do it every N sessions?
195 if (conf->session_cache_enable &&
196 ((conf->session_last_flushed + (conf->session_timeout * 1800)) <= request->timestamp)){
197 RDEBUG2("Flushing SSL sessions (of #%ld)",
198 SSL_CTX_sess_number(conf->ctx));
200 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
201 conf->session_last_flushed = request->timestamp;
204 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
205 ERROR("SSL: Error creating new SSL: %s",
206 ERR_error_string(ERR_get_error(), NULL));
210 /* We use the SSL's "app_data" to indicate a call-back */
211 SSL_set_app_data(new_tls, NULL);
213 state = talloc_zero(conf, tls_session_t);
216 state->ctx = conf->ctx;
217 state->ssl = new_tls;
220 * Initialize callbacks
222 state->record_init = record_init;
223 state->record_close = record_close;
224 state->record_plus = record_plus;
225 state->record_minus = record_minus;
228 * Create & hook the BIOs to handle the dirty side of the
229 * SSL. This is *very important* as we want to handle
230 * the transmission part. Now the only IO interface
231 * that SSL is aware of, is our defined BIO buffers.
233 * This means that all SSL IO is done to/from memory,
234 * and we can update those BIOs from the packets we've
237 state->into_ssl = BIO_new(BIO_s_mem());
238 state->from_ssl = BIO_new(BIO_s_mem());
239 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
242 * Add the message callback to identify what type of
243 * message/handshake is passed
245 SSL_set_msg_callback(new_tls, cbtls_msg);
246 SSL_set_msg_callback_arg(new_tls, state);
247 SSL_set_info_callback(new_tls, cbtls_info);
250 * In Server mode we only accept.
252 SSL_set_accept_state(state->ssl);
255 * Verify the peer certificate, if asked.
258 RDEBUG2("Requiring client certificate");
259 verify_mode = SSL_VERIFY_PEER;
260 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
261 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
263 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
265 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
266 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
267 state->length_flag = conf->include_length;
270 * We use default fragment size, unless the Framed-MTU
271 * tells us it's too big. Note that we do NOT account
272 * for the EAP-TLS headers if conf->fragment_size is
273 * large, because that config item looks to be confusing.
275 * i.e. it should REALLY be called MTU, and the code here
276 * should figure out what that means for TLS fragment size.
277 * asking the administrator to know the internal details
278 * of EAP-TLS in order to calculate fragment sizes is
281 state->offset = conf->fragment_size;
282 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
283 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
284 state->offset = vp->vp_integer;
287 if (conf->session_cache_enable) {
288 state->allow_session_resumption = 1; /* otherwise it's zero */
297 * Print out some text describing the error.
299 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
304 if ((l = ERR_get_error()) != 0) {
305 char const *p = ERR_error_string(l, NULL);
307 if (request && p) REDEBUG("SSL says: %s", p);
309 e = SSL_get_error(s, ret);
313 * These seem to be harmless and already "dealt
314 * with" by our non-blocking environment. NB:
315 * "ZERO_RETURN" is the clean "error"
316 * indicating a successfully closed SSL
317 * tunnel. We let this happen because our IO
318 * loop should not appear to have broken on
319 * this condition - and outside the IO loop, the
320 * "shutdown" state is checked.
322 * Don't print anything if we ignore the error.
325 case SSL_ERROR_WANT_READ:
326 case SSL_ERROR_WANT_WRITE:
327 case SSL_ERROR_WANT_X509_LOOKUP:
328 case SSL_ERROR_ZERO_RETURN:
332 * These seem to be indications of a genuine
333 * error that should result in the SSL tunnel
334 * being regarded as "dead".
336 case SSL_ERROR_SYSCALL:
337 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
342 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
348 * For any other errors that (a) exist, and (b)
349 * crop up - we need to interpret what to do with
350 * them - so "politely inform" the caller that
351 * the code needs updating here.
353 ERROR("SSL: FATAL SSL error ..... %d\n", e);
361 * We are the server, we always get the dirty data
362 * (Handshake data is also considered as dirty data)
363 * During handshake, since SSL API handles itself,
364 * After clean-up, dirty_out will be filled with
365 * the data required for handshaking. So we check
366 * if dirty_out is empty then we simply send it back.
367 * As of now, if handshake is successful, then we keep going,
370 * Fill the Bio with the dirty data to clean it
371 * Get the cleaned data from SSL, if it is not Handshake data
373 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
377 if (ssn->invalid_hb_used) return 0;
379 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
380 if (err != (int) ssn->dirty_in.used) {
381 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
383 record_init(&ssn->dirty_in);
386 record_init(&ssn->dirty_in);
388 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
389 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
391 ssn->clean_out.used += err;
395 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
399 /* Some Extra STATE information for easy debugging */
400 if (SSL_is_init_finished(ssn->ssl)) {
401 DEBUG2("SSL Connection Established\n");
403 if (SSL_in_init(ssn->ssl)) {
404 DEBUG2("In SSL Handshake Phase\n");
406 if (SSL_in_before(ssn->ssl)) {
407 DEBUG2("Before SSL Handshake Phase\n");
409 if (SSL_in_accept_init(ssn->ssl)) {
410 DEBUG2("In SSL Accept mode \n");
412 if (SSL_in_connect_init(ssn->ssl)) {
413 DEBUG2("In SSL Connect mode \n");
416 err = BIO_ctrl_pending(ssn->from_ssl);
418 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
419 sizeof(ssn->dirty_out.data));
421 ssn->dirty_out.used = err;
423 } else if (BIO_should_retry(ssn->from_ssl)) {
424 record_init(&ssn->dirty_in);
425 DEBUG2(" tls: Asking for more data in tunnel");
429 int_ssl_check(request, ssn->ssl, err, "BIO_read");
430 record_init(&ssn->dirty_in);
434 DEBUG2("SSL Application Data");
435 /* Its clean application data, do whatever we want */
436 record_init(&ssn->clean_out);
439 /* We are done with dirty_in, reinitialize it */
440 record_init(&ssn->dirty_in);
445 * Take cleartext user data, and encrypt it into the output buffer,
446 * to send to the client at the other end of the SSL connection.
448 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
453 * If there's un-encrypted data in 'clean_in', then write
454 * that data to the SSL session, and then call the BIO function
455 * to get that encrypted data from the SSL session, into
456 * a buffer which we can then package into an EAP packet.
458 * Based on Server's logic this clean_in is expected to
459 * contain the data to send to the client.
461 if (ssn->clean_in.used > 0) {
464 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
465 record_minus(&ssn->clean_in, NULL, written);
467 /* Get the dirty data from Bio to send it */
468 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
469 sizeof(ssn->dirty_out.data));
471 ssn->dirty_out.used = err;
473 int_ssl_check(request, ssn->ssl, err, "handshake_send");
480 void session_init(tls_session_t *ssn)
483 ssn->into_ssl = ssn->from_ssl = NULL;
484 record_init(&ssn->clean_in);
485 record_init(&ssn->clean_out);
486 record_init(&ssn->dirty_in);
487 record_init(&ssn->dirty_out);
489 memset(&ssn->info, 0, sizeof(ssn->info));
493 ssn->tls_msg_len = 0;
494 ssn->length_flag = 0;
496 ssn->free_opaque = NULL;
499 void session_close(tls_session_t *ssn)
501 SSL_set_quiet_shutdown(ssn->ssl, 1);
502 SSL_shutdown(ssn->ssl);
509 record_close(&ssn->clean_in);
510 record_close(&ssn->clean_out);
511 record_close(&ssn->dirty_in);
512 record_close(&ssn->dirty_out);
516 void session_free(void *ssn)
518 tls_session_t *sess = (tls_session_t *)ssn;
523 * Free any opaque TTLS or PEAP data.
525 if ((sess->opaque) && (sess->free_opaque)) {
526 sess->free_opaque(sess->opaque);
535 static void record_init(record_t *rec)
540 static void record_close(record_t *rec)
547 * Copy data to the intermediate buffer, before we send
550 static unsigned int record_plus(record_t *rec, void const *ptr,
553 unsigned int added = MAX_RECORD_SIZE - rec->used;
559 memcpy(rec->data + rec->used, ptr, added);
565 * Take data from the buffer, and give it to the caller.
567 static unsigned int record_minus(record_t *rec, void *ptr,
570 unsigned int taken = rec->used;
577 memcpy(ptr, rec->data, taken);
581 * This is pretty bad...
584 memmove(rec->data, rec->data + taken, rec->used);
588 void tls_session_information(tls_session_t *tls_session)
590 char const *str_write_p, *str_version, *str_content_type = "";
591 char const *str_details1 = "", *str_details2= "";
595 * Don't print this out in the normal course of
598 if (debug_flag == 0) {
602 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
604 switch (tls_session->info.version) {
606 str_version = "SSL 2.0";
609 str_version = "SSL 3.0 ";
612 str_version = "TLS 1.0 ";
615 str_version = "Unknown TLS version";
619 if (tls_session->info.version == SSL3_VERSION ||
620 tls_session->info.version == TLS1_VERSION) {
621 switch (tls_session->info.content_type) {
622 case SSL3_RT_CHANGE_CIPHER_SPEC:
623 str_content_type = "ChangeCipherSpec";
626 str_content_type = "Alert";
628 case SSL3_RT_HANDSHAKE:
629 str_content_type = "Handshake";
631 case SSL3_RT_APPLICATION_DATA:
632 str_content_type = "ApplicationData";
635 str_content_type = "UnknownContentType";
639 if (tls_session->info.content_type == SSL3_RT_ALERT) {
640 str_details1 = ", ???";
642 if (tls_session->info.record_len == 2) {
644 switch (tls_session->info.alert_level) {
645 case SSL3_AL_WARNING:
646 str_details1 = ", warning";
649 str_details1 = ", fatal";
653 str_details2 = " ???";
654 switch (tls_session->info.alert_description) {
655 case SSL3_AD_CLOSE_NOTIFY:
656 str_details2 = " close_notify";
658 case SSL3_AD_UNEXPECTED_MESSAGE:
659 str_details2 = " unexpected_message";
661 case SSL3_AD_BAD_RECORD_MAC:
662 str_details2 = " bad_record_mac";
664 case TLS1_AD_DECRYPTION_FAILED:
665 str_details2 = " decryption_failed";
667 case TLS1_AD_RECORD_OVERFLOW:
668 str_details2 = " record_overflow";
670 case SSL3_AD_DECOMPRESSION_FAILURE:
671 str_details2 = " decompression_failure";
673 case SSL3_AD_HANDSHAKE_FAILURE:
674 str_details2 = " handshake_failure";
676 case SSL3_AD_BAD_CERTIFICATE:
677 str_details2 = " bad_certificate";
679 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
680 str_details2 = " unsupported_certificate";
682 case SSL3_AD_CERTIFICATE_REVOKED:
683 str_details2 = " certificate_revoked";
685 case SSL3_AD_CERTIFICATE_EXPIRED:
686 str_details2 = " certificate_expired";
688 case SSL3_AD_CERTIFICATE_UNKNOWN:
689 str_details2 = " certificate_unknown";
691 case SSL3_AD_ILLEGAL_PARAMETER:
692 str_details2 = " illegal_parameter";
694 case TLS1_AD_UNKNOWN_CA:
695 str_details2 = " unknown_ca";
697 case TLS1_AD_ACCESS_DENIED:
698 str_details2 = " access_denied";
700 case TLS1_AD_DECODE_ERROR:
701 str_details2 = " decode_error";
703 case TLS1_AD_DECRYPT_ERROR:
704 str_details2 = " decrypt_error";
706 case TLS1_AD_EXPORT_RESTRICTION:
707 str_details2 = " export_restriction";
709 case TLS1_AD_PROTOCOL_VERSION:
710 str_details2 = " protocol_version";
712 case TLS1_AD_INSUFFICIENT_SECURITY:
713 str_details2 = " insufficient_security";
715 case TLS1_AD_INTERNAL_ERROR:
716 str_details2 = " internal_error";
718 case TLS1_AD_USER_CANCELLED:
719 str_details2 = " user_canceled";
721 case TLS1_AD_NO_RENEGOTIATION:
722 str_details2 = " no_renegotiation";
728 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
729 str_details1 = "???";
731 if (tls_session->info.record_len > 0)
732 switch (tls_session->info.handshake_type) {
733 case SSL3_MT_HELLO_REQUEST:
734 str_details1 = ", HelloRequest";
736 case SSL3_MT_CLIENT_HELLO:
737 str_details1 = ", ClientHello";
739 case SSL3_MT_SERVER_HELLO:
740 str_details1 = ", ServerHello";
742 case SSL3_MT_CERTIFICATE:
743 str_details1 = ", Certificate";
745 case SSL3_MT_SERVER_KEY_EXCHANGE:
746 str_details1 = ", ServerKeyExchange";
748 case SSL3_MT_CERTIFICATE_REQUEST:
749 str_details1 = ", CertificateRequest";
751 case SSL3_MT_SERVER_DONE:
752 str_details1 = ", ServerHelloDone";
754 case SSL3_MT_CERTIFICATE_VERIFY:
755 str_details1 = ", CertificateVerify";
757 case SSL3_MT_CLIENT_KEY_EXCHANGE:
758 str_details1 = ", ClientKeyExchange";
760 case SSL3_MT_FINISHED:
761 str_details1 = ", Finished";
767 snprintf(tls_session->info.info_description,
768 sizeof(tls_session->info.info_description),
769 "%s %s%s [length %04lx]%s%s\n",
770 str_write_p, str_version, str_content_type,
771 (unsigned long)tls_session->info.record_len,
772 str_details1, str_details2);
774 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
776 RDEBUG2("%s\n", tls_session->info.info_description);
779 static CONF_PARSER cache_config[] = {
780 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
781 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
782 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
783 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
784 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
785 { NULL, -1, 0, NULL, NULL } /* end the list */
788 static CONF_PARSER verify_config[] = {
789 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
790 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
791 { NULL, -1, 0, NULL, NULL } /* end the list */
794 #ifdef HAVE_OPENSSL_OCSP_H
795 static CONF_PARSER ocsp_config[] = {
796 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
797 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
798 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
799 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
800 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
801 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "yes" },
802 { NULL, -1, 0, NULL, NULL } /* end the list */
806 static CONF_PARSER tls_server_config[] = {
807 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
808 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
809 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
810 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
811 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
812 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
813 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
814 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
815 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
816 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
817 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
818 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
819 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
820 #ifdef PSK_MAX_IDENTITY_LEN
821 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
822 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
824 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
825 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
826 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
827 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
828 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
829 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
830 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
831 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
832 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
833 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
835 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
836 #ifndef OPENSSL_NO_ECDH
837 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
841 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
843 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
845 #ifdef HAVE_OPENSSL_OCSP_H
846 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
849 { NULL, -1, 0, NULL, NULL } /* end the list */
853 static CONF_PARSER tls_client_config[] = {
854 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
855 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
856 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
857 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
858 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
859 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
860 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
861 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
862 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
863 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
864 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
865 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
866 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
867 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
868 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
869 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
870 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
871 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
872 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
874 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
875 #ifndef OPENSSL_NO_ECDH
876 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
880 { NULL, -1, 0, NULL, NULL } /* end the list */
885 * TODO: Check for the type of key exchange * like conf->dh_key
887 static int load_dh_params(SSL_CTX *ctx, char *file)
894 if ((bio = BIO_new_file(file, "r")) == NULL) {
895 ERROR("tls: Unable to open DH file - %s", file);
899 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
902 WARN("tls: Unable to set DH parameters. DH cipher suites may not work!");
903 WARN("Fix this by running the OpenSSL command listed in eap.conf");
907 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
908 ERROR("tls: Unable to set DH parameters");
919 * Generate ephemeral RSA keys.
921 static int generate_eph_rsa_key(SSL_CTX *ctx)
925 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
927 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
928 ERROR("tls: Couldn't set ephemeral RSA key");
936 /* index we use to store cached session VPs
937 * needs to be dynamic so we can supply a "free" function
939 static int FR_TLS_EX_INDEX_VPS = -1;
940 int FR_TLS_EX_INDEX_CERTS = -1;
943 * Print debugging messages, and free data.
945 * FIXME: Write sessions to some long-term storage, so that
946 * session resumption can still occur after the server
949 #define MAX_SESSION_SIZE (256)
951 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
954 char buffer[2 * MAX_SESSION_SIZE + 1];
955 fr_tls_server_conf_t *conf;
957 size = sess->session_id_length;
958 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
960 fr_bin2hex(buffer, sess->session_id, size);
962 DEBUG2(" SSL: Removing session %s from the cache", buffer);
963 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
964 if (conf && conf->session_cache_path) {
968 /* remove session and any cached VPs */
969 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
970 conf->session_cache_path, FR_DIR_SEP, buffer);
971 rv = unlink(filename);
973 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
975 /* VPs might be absent; might not have been written to disk yet */
976 snprintf(filename, sizeof(filename), "%s%c%s.vps",
977 conf->session_cache_path, FR_DIR_SEP, buffer);
984 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
987 char buffer[2 * MAX_SESSION_SIZE + 1];
988 fr_tls_server_conf_t *conf;
989 unsigned char *sess_blob = NULL;
991 size = sess->session_id_length;
992 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
994 fr_bin2hex(buffer, sess->session_id, size);
996 DEBUG2(" SSL: adding session %s to cache", buffer);
998 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
999 if (conf && conf->session_cache_path) {
1000 int fd, rv, todo, blob_len;
1004 /* find out what length data we need */
1005 blob_len = i2d_SSL_SESSION(sess, NULL);
1007 /* something went wrong */
1008 DEBUG2(" SSL: could not find buffer length to persist session");
1012 /* alloc and convert to ASN.1 */
1013 sess_blob = talloc_array(conf, unsigned char, blob_len);
1015 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1018 /* openssl mutates &p */
1020 rv = i2d_SSL_SESSION(sess, &p);
1021 if (rv != blob_len) {
1022 DEBUG2(" SSL: could not persist session");
1026 /* open output file */
1027 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1028 conf->session_cache_path, FR_DIR_SEP, buffer);
1029 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1031 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1038 rv = write(fd, p, todo);
1040 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1048 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1052 if (sess_blob) talloc_free(sess_blob);
1057 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1058 unsigned char *data, int len,
1062 char buffer[2 * MAX_SESSION_SIZE + 1];
1063 fr_tls_server_conf_t *conf;
1064 TALLOC_CTX *talloc_ctx;
1066 SSL_SESSION *sess = NULL;
1067 unsigned char *sess_data = NULL;
1068 PAIR_LIST *pairlist = NULL;
1071 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1073 fr_bin2hex(buffer, data, size);
1075 DEBUG2(" SSL: Client requested cached session %s", buffer);
1077 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1078 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1079 if (conf && conf->session_cache_path) {
1086 /* read in the cached VPs from the .vps file */
1087 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1088 conf->session_cache_path, FR_DIR_SEP, buffer);
1089 rv = pairlist_read(NULL, filename, &pairlist, 1);
1091 /* not safe to un-persist a session w/o VPs */
1092 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1096 /* load the actual SSL session */
1097 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1098 conf->session_cache_path, FR_DIR_SEP, buffer);
1099 fd = open(filename, O_RDONLY);
1101 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1105 rv = fstat(fd, &st);
1107 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1112 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1114 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1122 rv = read(fd, p, todo);
1124 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1133 /* openssl mutates &p */
1135 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1138 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1142 /* cache the VPs into the session */
1143 vp = paircopy(talloc_ctx, pairlist->reply);
1144 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1145 DEBUG2(" SSL: Successfully restored session %s", buffer);
1148 if (sess_data) talloc_free(sess_data);
1149 if (pairlist) pairlist_free(&pairlist);
1155 #ifdef HAVE_OPENSSL_OCSP_H
1157 * This function extracts the OCSP Responder URL
1158 * from an existing x509 certificate.
1160 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1161 char **ppath, int *pssl)
1165 AUTHORITY_INFO_ACCESS *aia;
1166 ACCESS_DESCRIPTION *ad;
1168 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1170 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1171 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1172 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1173 if (ad->location->type == GEN_URI) {
1174 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1175 phost, pport, ppath, pssl))
1184 * This function sends a OCSP request to a defined OCSP responder
1185 * and checks the OCSP response for correctness.
1188 /* Maximum leeway in validity period: default 5 minutes */
1189 #define MAX_VALIDITY_PERIOD (5 * 60)
1191 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1192 fr_tls_server_conf_t *conf)
1194 OCSP_CERTID *certid;
1196 OCSP_RESPONSE *resp = NULL;
1197 OCSP_BASICRESP *bresp = NULL;
1202 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1203 BIO *cbio, *bio_out;
1206 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1208 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1212 struct timeval when;
1216 * Create OCSP Request
1218 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1219 req = OCSP_REQUEST_new();
1220 OCSP_request_add0_id(req, certid);
1221 if(conf->ocsp_use_nonce) {
1222 OCSP_request_add1_nonce(req, NULL, 8);
1226 * Send OCSP Request and get OCSP Response
1229 /* Get OCSP responder URL */
1230 if (conf->ocsp_override_url) {
1233 memcpy(&url, &conf->ocsp_url, sizeof(url));
1234 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1235 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1238 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1241 if (!host || !port || !path) {
1242 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP");
1247 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1249 /* Setup BIO socket to OCSP responder */
1250 cbio = BIO_new_connect(host);
1252 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1254 BIO_set_conn_port(cbio, port);
1255 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1256 BIO_do_connect(cbio);
1258 /* Send OCSP request and wait for response */
1259 resp = OCSP_sendreq_bio(cbio, path, req);
1261 ERROR("Couldn't get OCSP response");
1266 if (conf->ocsp_timeout)
1267 BIO_set_nbio(cbio, 1);
1269 rc = BIO_do_connect(cbio);
1270 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1271 ERROR("Couldn't connect to OCSP responder");
1276 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1278 ERROR("Couldn't send OCSP request");
1283 gettimeofday(&when, NULL);
1284 when.tv_sec += conf->ocsp_timeout;
1287 rc = OCSP_sendreq_nbio(&resp, ctx);
1288 if (conf->ocsp_timeout) {
1289 gettimeofday(&now, NULL);
1290 if (!timercmp(&now, &when, <))
1293 } while ((rc == -1) && BIO_should_retry(cbio));
1295 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1296 ERROR("OCSP response timed out");
1301 OCSP_REQ_CTX_free(ctx);
1304 ERROR("Couldn't get OCSP response");
1310 /* Verify OCSP response status */
1311 status = OCSP_response_status(resp);
1312 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1313 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1314 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1317 bresp = OCSP_response_get1_basic(resp);
1318 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1319 ERROR("OCSP response has wrong nonce value");
1322 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1323 ERROR("Couldn't verify OCSP basic response");
1327 /* Verify OCSP cert status */
1328 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1329 &rev, &thisupd, &nextupd)) {
1330 ERROR("No Status found.\n");
1334 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1335 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1336 ERR_print_errors(bio_out);
1339 BIO_puts(bio_out, "\tThis Update: ");
1340 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1341 BIO_puts(bio_out, "\n");
1343 BIO_puts(bio_out, "\tNext Update: ");
1344 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1345 BIO_puts(bio_out, "\n");
1349 case V_OCSP_CERTSTATUS_GOOD:
1350 DEBUG2("[oscp] --> Cert status: good");
1355 /* REVOKED / UNKNOWN */
1356 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1358 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1359 BIO_puts(bio_out, "\tRevocation Time: ");
1360 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1361 BIO_puts(bio_out, "\n");
1366 /* Free OCSP Stuff */
1367 OCSP_REQUEST_free(req);
1368 OCSP_RESPONSE_free(resp);
1373 OCSP_BASICRESP_free(bresp);
1378 DEBUG2("[ocsp] --> Certificate is valid!");
1381 if (conf->ocsp_softfail) {
1382 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1383 DEBUG2("[ocsp] --> Warning! This may be insecure");
1386 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1391 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1397 #endif /* HAVE_OPENSSL_OCSP_H */
1400 * For creating certificate attributes.
1402 static char const *cert_attr_names[8][2] = {
1403 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1404 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1405 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1406 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1407 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1408 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1409 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1410 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1413 #define FR_TLS_SERIAL (0)
1414 #define FR_TLS_EXPIRATION (1)
1415 #define FR_TLS_SUBJECT (2)
1416 #define FR_TLS_ISSUER (3)
1417 #define FR_TLS_CN (4)
1418 #define FR_TLS_SAN_EMAIL (5)
1419 #define FR_TLS_SAN_DNS (6)
1420 #define FR_TLS_SAN_UPN (7)
1423 * Before trusting a certificate, you must make sure that the
1424 * certificate is 'valid'. There are several steps that your
1425 * application can take in determining if a certificate is
1426 * valid. Commonly used steps are:
1428 * 1.Verifying the certificate's signature, and verifying that
1429 * the certificate has been issued by a trusted Certificate
1432 * 2.Verifying that the certificate is valid for the present date
1433 * (i.e. it is being presented within its validity dates).
1435 * 3.Verifying that the certificate has not been revoked by its
1436 * issuing Certificate Authority, by checking with respect to a
1437 * Certificate Revocation List (CRL).
1439 * 4.Verifying that the credentials presented by the certificate
1440 * fulfill additional requirements specific to the application,
1441 * such as with respect to access control lists or with respect
1442 * to OCSP (Online Certificate Status Processing).
1444 * NOTE: This callback will be called multiple times based on the
1445 * depth of the root certificate chain
1447 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1449 char subject[1024]; /* Used for the subject name */
1450 char issuer[1024]; /* Used for the issuer name */
1451 char attribute[1024];
1453 char common_name[1024];
1457 X509_CINF *client_inf;
1458 STACK_OF(X509_EXTENSION) *ext_list;
1460 int err, depth, lookup, loc;
1461 fr_tls_server_conf_t *conf;
1464 ASN1_INTEGER *sn = NULL;
1465 ASN1_TIME *asn_time = NULL;
1468 #ifdef HAVE_OPENSSL_OCSP_H
1469 X509_STORE *ocsp_store = NULL;
1472 TALLOC_CTX *talloc_ctx;
1474 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1475 err = X509_STORE_CTX_get_error(ctx);
1476 depth = X509_STORE_CTX_get_error_depth(ctx);
1481 * Log client/issuing cert. If there's an error, log
1484 if ((lookup > 1) && !my_ok) lookup = 1;
1487 * Retrieve the pointer to the SSL of the connection currently treated
1488 * and the application specific data stored into the SSL object.
1490 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1491 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1492 if (!conf) return 1;
1494 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1496 if (!request) return 1; /* FIXME: outbound TLS */
1498 rad_assert(request != NULL);
1499 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1500 rad_assert(certs != NULL);
1501 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1502 #ifdef HAVE_OPENSSL_OCSP_H
1503 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1506 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1509 * Get the Serial Number
1512 sn = X509_get_serialNumber(client_cert);
1515 * For this next bit, we create the attributes *only* if
1516 * we're at the client or issuing certificate, AND we
1517 * have a user identity. i.e. we don't create the
1518 * attributes for RadSec connections.
1521 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1525 for (i = 0; i < sn->length; i++) {
1526 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1529 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1534 * Get the Expiration Date
1537 asn_time = X509_get_notAfter(client_cert);
1538 if (identity && (lookup <= 1) && asn_time &&
1539 (asn_time->length < (int) sizeof(buf))) {
1540 memcpy(buf, (char*) asn_time->data, asn_time->length);
1541 buf[asn_time->length] = '\0';
1542 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1546 * Get the Subject & Issuer
1548 subject[0] = issuer[0] = '\0';
1549 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1551 subject[sizeof(subject) - 1] = '\0';
1552 if (identity && (lookup <= 1) && subject[0]) {
1553 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1556 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1558 issuer[sizeof(issuer) - 1] = '\0';
1559 if (identity && (lookup <= 1) && issuer[0]) {
1560 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1564 * Get the Common Name, if there is a subject.
1566 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1567 NID_commonName, common_name, sizeof(common_name));
1568 common_name[sizeof(common_name) - 1] = '\0';
1569 if (identity && (lookup <= 1) && common_name[0] && subject[0]) {
1570 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1574 * Get the RFC822 Subject Alternative Name
1576 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1577 if (lookup <= 1 && loc >= 0) {
1578 X509_EXTENSION *ext = NULL;
1579 GENERAL_NAMES *names = NULL;
1582 if ((ext = X509_get_ext(client_cert, loc)) &&
1583 (names = X509V3_EXT_d2i(ext))) {
1584 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1585 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1587 switch (name->type) {
1590 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1591 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1593 #endif /* GEN_EMAIL */
1596 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1597 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1599 #endif /* GEN_DNS */
1600 #ifdef GEN_OTHERNAME
1602 /* look for a MS UPN */
1603 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1604 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1605 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1606 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1607 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1610 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)\n");
1615 #endif /* GEN_OTHERNAME */
1617 /* XXX TODO handle other SAN types */
1623 sk_GENERAL_NAME_free(names);
1627 * If the CRL has expired, that might still be OK.
1630 (conf->allow_expired_crl) &&
1631 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1633 X509_STORE_CTX_set_error( ctx, 0 );
1637 char const *p = X509_verify_cert_error_string(err);
1638 ERROR("--> verify error:num=%d:%s\n",err, p);
1639 REDEBUG("SSL says error %d : %s", err, p);
1644 client_inf = client_cert->cert_info;
1645 ext_list = client_inf->extensions;
1651 * Grab the X509 extensions, and create attributes out of them.
1652 * For laziness, we re-use the OpenSSL names
1654 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1659 out = BIO_new(BIO_s_mem());
1660 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1662 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1664 X509_EXTENSION *ext;
1667 ext = sk_X509_EXTENSION_value(ext_list, i);
1669 obj = X509_EXTENSION_get_object(ext);
1670 i2a_ASN1_OBJECT(out, obj);
1671 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1672 if (len <= 0) continue;
1674 attribute[16 + len] = '\0';
1676 X509V3_EXT_print(out, ext, 0, 0);
1677 len = BIO_read(out, value , sizeof(value) - 1);
1678 if (len <= 0) continue;
1683 * Mash the OpenSSL name to our name, and
1684 * create the attribute.
1686 for (p = value + 16; *p != '\0'; p++) {
1687 if (*p == ' ') *p = '-';
1690 vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1691 if (vp) debug_pair_list(vp);
1697 switch (ctx->error) {
1699 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1700 ERROR("issuer= %s\n", issuer);
1702 case X509_V_ERR_CERT_NOT_YET_VALID:
1703 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1704 ERROR("notBefore=");
1706 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1709 case X509_V_ERR_CERT_HAS_EXPIRED:
1710 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1713 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1719 * If we're at the actual client cert, apply additional
1724 * If the conf tells us to, check cert issuer
1725 * against the specified value and fail
1726 * verification if they don't match.
1728 if (conf->check_cert_issuer &&
1729 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1730 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1735 * If the conf tells us to, check the CN in the
1736 * cert against xlat'ed value, but only if the
1737 * previous checks passed.
1739 if (my_ok && conf->check_cert_cn) {
1740 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1741 /* if this fails, fail the verification */
1744 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1745 if (strcmp(cn_str, common_name) != 0) {
1746 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1750 } /* check_cert_cn */
1752 #ifdef HAVE_OPENSSL_OCSP_H
1753 if (my_ok && conf->ocsp_enable){
1754 RDEBUG2("--> Starting OCSP Request");
1755 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1756 ERROR("Couldn't get issuer_cert for %s", common_name);
1758 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1762 while (conf->verify_client_cert_cmd) {
1767 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1768 conf->verify_tmp_dir, progname);
1769 fd = mkstemp(filename);
1771 RDEBUG("Failed creating file in %s: %s",
1772 conf->verify_tmp_dir, fr_syserror(errno));
1776 fp = fdopen(fd, "w");
1779 RDEBUG("Failed opening file %s: %s",
1780 filename, fr_syserror(errno));
1784 if (!PEM_write_X509(fp, client_cert)) {
1786 RDEBUG("Failed writing certificate to file");
1791 if (!pairmake_packet("TLS-Client-Cert-Filename",
1792 filename, T_OP_SET)) {
1793 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1798 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1799 if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1800 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1801 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1804 RDEBUG("Client certificate CN %s passed external validation", common_name);
1815 if (debug_flag > 0) {
1816 RDEBUG2("chain-depth=%d, ", depth);
1817 RDEBUG2("error=%d", err);
1819 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1820 RDEBUG2("--> BUF-Name = %s", common_name);
1821 RDEBUG2("--> subject = %s", subject);
1822 RDEBUG2("--> issuer = %s", issuer);
1823 RDEBUG2("--> verify return:%d", my_ok);
1829 #ifdef HAVE_OPENSSL_OCSP_H
1831 * Create Global X509 revocation store and use it to verify
1834 * - Load the trusted CAs
1835 * - Load the trusted issuer certificates
1837 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1839 X509_STORE *store = NULL;
1841 store = X509_STORE_new();
1843 /* Load the CAs we trust */
1844 if (conf->ca_file || conf->ca_path)
1845 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1846 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1847 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1851 #ifdef X509_V_FLAG_CRL_CHECK
1852 if (conf->check_crl)
1853 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1857 #endif /* HAVE_OPENSSL_OCSP_H */
1859 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1860 #ifndef OPENSSL_NO_ECDH
1861 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1866 if (!ecdh_curve || !*ecdh_curve) return 0;
1868 nid = OBJ_sn2nid(ecdh_curve);
1870 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1874 ecdh = EC_KEY_new_by_curve_name(nid);
1876 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1880 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1882 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1892 * DIE OPENSSL DIE DIE DIE
1894 * What a palaver, just to free some data attached the
1895 * session. We need to do this because the "remove" callback
1896 * is called when refcount > 0 sometimes, if another thread
1897 * is using the session
1899 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1900 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1901 UNUSED long argl, UNUSED void *argp)
1903 VALUE_PAIR *vp = data_ptr;
1906 DEBUG2(" Freeing cached session VPs");;
1911 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
1912 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1913 UNUSED long argl, UNUSED void *argp)
1915 VALUE_PAIR **certs = data_ptr;
1918 DEBUG2(" Freeing cached session Certificates");
1923 /** Add all the default ciphers and message digests reate our context.
1925 * This should be called exactly once from main, before reading the main config
1926 * or initialising any modules.
1928 void tls_global_init(void)
1930 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
1931 SSL_library_init(); /* initialize library */
1932 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
1933 OPENSSL_config(NULL);
1936 /** Check for vulnerable versions of libssl
1938 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
1939 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
1941 int tls_global_version_check(char const *acknowledged)
1945 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
1949 /* Check for bad versions */
1950 v = (uint64_t) SSLeay();
1952 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
1953 libssl_defect_t *defect = &libssl_defects[i];
1955 if ((v >= defect->low) && (v <= defect->high)) {
1956 ERROR("Refusing to start with libssl version %s (in range %s)",
1957 ssl_version(), ssl_version_range(defect->low, defect->high));
1958 ERROR("Security advisory %s (%s)", defect->id, defect->name);
1959 ERROR("%s", defect->comment);
1966 INFO("Once you have verified libssl has been correctly patched, "
1967 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
1975 /** Free any memory alloced by libssl
1978 void tls_global_cleanup(void)
1980 ERR_remove_state(0);
1982 CONF_modules_unload(1);
1985 CRYPTO_cleanup_all_ex_data();
1989 * Create Global context SSL and use it in every new session
1991 * - Load the trusted CAs
1992 * - Load the Private key & the certificate
1993 * - Set the Context options & Verify options
1995 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
1998 X509_STORE *certstore;
1999 int verify_mode = SSL_VERIFY_NONE;
2000 int ctx_options = 0;
2004 * SHA256 is in all versions of OpenSSL, but isn't
2005 * initialized by default. It's needed for WiMAX
2008 #ifdef HAVE_OPENSSL_EVP_SHA256
2009 EVP_add_digest(EVP_sha256());
2012 ctx = SSL_CTX_new(TLSv1_method());
2015 while ((err = ERR_get_error())) {
2016 DEBUG("Failed creating SSL context: %s",
2017 ERR_error_string(err, NULL));
2023 * Save the config on the context so that callbacks which
2024 * only get SSL_CTX* e.g. session persistence, can get it
2026 SSL_CTX_set_app_data(ctx, conf);
2029 * Identify the type of certificates that needs to be loaded
2031 if (conf->file_type) {
2032 type = SSL_FILETYPE_PEM;
2034 type = SSL_FILETYPE_ASN1;
2038 * Set the password to load private key
2040 if (conf->private_key_password) {
2043 * We don't want to put the private key password in eap.conf, so check
2044 * for our special string which indicates we should get the password
2047 char const* special_string = "Apple:UseCertAdmin";
2048 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2051 long const max_password_len = 128;
2052 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2053 conf->private_key_file);
2055 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2057 FILE* cmd_pipe = popen(cmd, "r");
2059 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2060 ERROR("Error reading private_key_file %s", conf->private_key_file);
2064 rad_const_free(conf->private_key_password);
2065 password = talloc_array(conf, char, max_password_len);
2067 ERROR("TLS: Can't allocate space for private_key_password");
2068 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2073 fgets(password, max_password_len, cmd_pipe);
2076 /* Get rid of newline at end of password. */
2077 password[strlen(password) - 1] = '\0';
2079 DEBUG3("tls: Password from command = \"%s\"", password);
2080 conf->private_key_password = password;
2087 memcpy(&password, &conf->private_key_password, sizeof(password));
2088 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2089 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2093 #ifdef PSK_MAX_IDENTITY_LEN
2094 if ((conf->psk_identity && !conf->psk_password) ||
2095 (!conf->psk_identity && conf->psk_password) ||
2096 (conf->psk_identity && !*conf->psk_identity) ||
2097 (conf->psk_password && !*conf->psk_password)) {
2098 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2102 if (conf->psk_identity) {
2103 size_t psk_len, hex_len;
2104 char buffer[PSK_MAX_PSK_LEN];
2106 if (conf->certificate_file ||
2107 conf->private_key_password || conf->private_key_file ||
2108 conf->ca_file || conf->ca_path) {
2109 ERROR("When PSKs are used, No certificate configuration is permitted");
2114 SSL_CTX_set_psk_client_callback(ctx,
2115 psk_client_callback);
2117 SSL_CTX_set_psk_server_callback(ctx,
2118 psk_server_callback);
2121 psk_len = strlen(conf->psk_password);
2122 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2123 ERROR("psk_hexphrase is too long (max %d)",
2128 hex_len = fr_hex2bin((uint8_t *) buffer, conf->psk_password, psk_len);
2129 if (psk_len != (2 * hex_len)) {
2130 ERROR("psk_hexphrase is not all hex");
2137 (void) client; /* -Wunused */
2141 * Load our keys and certificates
2143 * If certificates are of type PEM then we can make use
2144 * of cert chain authentication using openssl api call
2145 * SSL_CTX_use_certificate_chain_file. Please see how
2146 * the cert chain needs to be given in PEM from
2149 if (!conf->certificate_file) goto load_ca;
2151 if (type == SSL_FILETYPE_PEM) {
2152 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2153 ERROR("Error reading certificate file %s:%s",
2154 conf->certificate_file,
2155 ERR_error_string(ERR_get_error(), NULL));
2159 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2160 ERROR("Error reading certificate file %s:%s",
2161 conf->certificate_file,
2162 ERR_error_string(ERR_get_error(), NULL));
2166 /* Load the CAs we trust */
2168 if (conf->ca_file || conf->ca_path) {
2169 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2170 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2171 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2175 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2177 if (conf->private_key_file) {
2178 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2179 ERROR("Failed reading private key file %s:%s",
2180 conf->private_key_file,
2181 ERR_error_string(ERR_get_error(), NULL));
2186 * Check if the loaded private key is the right one
2188 if (!SSL_CTX_check_private_key(ctx)) {
2189 ERROR("Private key does not match the certificate public key");
2194 #ifdef PSK_MAX_IDENTITY_LEN
2201 ctx_options |= SSL_OP_NO_SSLv2;
2202 ctx_options |= SSL_OP_NO_SSLv3;
2203 #ifdef SSL_OP_NO_TICKET
2204 ctx_options |= SSL_OP_NO_TICKET ;
2208 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2209 * small subgroup attacks and forward secrecy. Always
2212 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2213 * time needed during negotiation, but it is not very
2216 ctx_options |= SSL_OP_SINGLE_DH_USE;
2219 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2220 * in Windows Vista client.
2221 * http://www.openssl.org/~bodo/tls-cbc.txt
2222 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2224 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2226 SSL_CTX_set_options(ctx, ctx_options);
2229 * TODO: Set the RSA & DH
2230 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2231 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2235 * set the message callback to identify the type of
2236 * message. For every new session, there can be a
2237 * different callback argument.
2239 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2243 * Set eliptical curve crypto configuration.
2245 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2246 #ifndef OPENSSL_NO_ECDH
2247 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2253 /* Set Info callback */
2254 SSL_CTX_set_info_callback(ctx, cbtls_info);
2257 * Callbacks, etc. for session resumption.
2259 if (conf->session_cache_enable) {
2260 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2261 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2262 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2264 SSL_CTX_set_quiet_shutdown(ctx, 1);
2265 if (FR_TLS_EX_INDEX_VPS < 0)
2266 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2267 if (FR_TLS_EX_INDEX_CERTS < 0)
2268 FR_TLS_EX_INDEX_CERTS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2272 * Check the certificates for revocation.
2274 #ifdef X509_V_FLAG_CRL_CHECK
2275 if (conf->check_crl) {
2276 certstore = SSL_CTX_get_cert_store(ctx);
2277 if (certstore == NULL) {
2278 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2279 ERROR("tls: Error reading Certificate Store");
2282 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2288 * Always verify the peer certificate
2290 verify_mode |= SSL_VERIFY_PEER;
2291 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2292 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2293 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2295 if (conf->verify_depth) {
2296 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2299 /* Load randomness */
2300 if (conf->random_file) {
2301 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2302 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2303 ERROR("tls: Error loading randomness");
2309 * Set the cipher list if we were told to
2311 if (conf->cipher_list) {
2312 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2313 ERROR("tls: Error setting cipher list");
2319 * Setup session caching
2321 if (conf->session_cache_enable) {
2323 * Create a unique context Id per EAP-TLS configuration.
2325 if (conf->session_id_name) {
2326 snprintf(conf->session_context_id,
2327 sizeof(conf->session_context_id),
2329 conf->session_id_name);
2331 snprintf(conf->session_context_id,
2332 sizeof(conf->session_context_id),
2337 * Cache it, and DON'T auto-clear it.
2339 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2341 SSL_CTX_set_session_id_context(ctx,
2342 (unsigned char *) conf->session_context_id,
2343 (unsigned int) strlen(conf->session_context_id));
2346 * Our timeout is in hours, this is in seconds.
2348 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2351 * Set the maximum number of entries in the
2354 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2357 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2365 * Free TLS client/server config
2366 * Should not be called outside this code, as a callback is
2367 * added to automatically free the data when the CONF_SECTION
2370 static int tls_server_conf_free(fr_tls_server_conf_t *conf)
2372 if (conf->ctx) SSL_CTX_free(conf->ctx);
2374 #ifdef HAVE_OPENSSL_OCSP_H
2375 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2376 conf->ocsp_store = NULL;
2380 memset(conf, 0, sizeof(*conf));
2386 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2388 fr_tls_server_conf_t *conf;
2391 * If cs has already been parsed there should be a cached copy
2392 * of conf already stored, so just return that.
2394 conf = cf_data_find(cs, "tls-conf");
2396 DEBUG("Using cached TLS configuration from previous invocation");
2400 conf = talloc_zero(cs, fr_tls_server_conf_t);
2402 ERROR("Out of memory");
2406 talloc_set_destructor(conf, tls_server_conf_free);
2408 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2415 * Save people from their own stupidity.
2417 if (conf->fragment_size < 100) conf->fragment_size = 100;
2419 if (!conf->private_key_file) {
2420 ERROR("TLS Server requires a private key file");
2424 if (!conf->certificate_file) {
2425 ERROR("TLS Server requires a certificate file");
2432 conf->ctx = init_tls_ctx(conf, 0);
2433 if (conf->ctx == NULL) {
2437 #ifdef HAVE_OPENSSL_OCSP_H
2439 * Initialize OCSP Revocation Store
2441 if (conf->ocsp_enable) {
2442 conf->ocsp_store = init_revocation_store(conf);
2443 if (conf->ocsp_store == NULL) goto error;
2445 #endif /*HAVE_OPENSSL_OCSP_H*/
2449 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2450 if (load_dh_params(conf->ctx, dh_file) < 0) {
2455 if (generate_eph_rsa_key(conf->ctx) < 0) {
2459 if (conf->verify_tmp_dir) {
2460 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2461 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2466 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2467 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2472 * Cache conf in cs in case we're asked to parse this again.
2474 cf_data_add(cs, "tls-conf", conf, NULL);
2479 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2481 fr_tls_server_conf_t *conf;
2483 conf = cf_data_find(cs, "tls-conf");
2485 DEBUG("Using cached TLS configuration from previous invocation");
2489 conf = talloc_zero(cs, fr_tls_server_conf_t);
2491 ERROR("Out of memory");
2495 talloc_set_destructor(conf, tls_server_conf_free);
2497 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2504 * Save people from their own stupidity.
2506 if (conf->fragment_size < 100) conf->fragment_size = 100;
2511 conf->ctx = init_tls_ctx(conf, 1);
2512 if (conf->ctx == NULL) {
2519 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2520 if (load_dh_params(conf->ctx, dh_file) < 0) {
2525 if (generate_eph_rsa_key(conf->ctx) < 0) {
2529 cf_data_add(cs, "tls-conf", conf, NULL);
2534 int tls_success(tls_session_t *ssn, REQUEST *request)
2536 VALUE_PAIR *vp, *vps = NULL;
2537 fr_tls_server_conf_t *conf;
2538 TALLOC_CTX *talloc_ctx;
2540 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2541 rad_assert(conf != NULL);
2543 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2546 * If there's no session resumption, delete the entry
2547 * from the cache. This means either it's disabled
2548 * globally for this SSL context, OR we were told to
2549 * disable it for this user.
2551 * This also means you can't turn it on just for one
2554 if ((!ssn->allow_session_resumption) ||
2555 (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2556 (vp->vp_integer == 0))) {
2557 SSL_CTX_remove_session(ssn->ctx,
2559 ssn->allow_session_resumption = 0;
2562 * If we're in a resumed session and it's
2565 if (SSL_session_reused(ssn->ssl)) {
2566 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2571 * Else resumption IS allowed, so we store the
2572 * user data in the cache.
2574 } else if (!SSL_session_reused(ssn->ssl)) {
2577 char buffer[2 * MAX_SESSION_SIZE + 1];
2579 size = ssn->ssl->session->session_id_length;
2580 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2582 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2584 vp = paircopy2(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2585 if (vp) pairadd(&vps, vp);
2587 vp = paircopy2(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2588 if (vp) pairadd(&vps, vp);
2590 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2591 if (vp) pairadd(&vps, vp);
2593 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2594 if (vp) pairadd(&vps, vp);
2596 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2599 * Hmm... the certs should probably be session data.
2603 * @todo: some go into reply, others into
2606 pairadd(&vps, paircopy(talloc_ctx, *certs));
2610 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2611 SSL_SESSION_set_ex_data(ssn->ssl->session,
2612 FR_TLS_EX_INDEX_VPS, vps);
2613 if (conf->session_cache_path) {
2614 /* write the VPs to the cache file */
2615 char filename[256], buf[1024];
2618 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2619 conf->session_cache_path, FR_DIR_SEP, buffer
2621 vp_file = fopen(filename, "w");
2622 if (vp_file == NULL) {
2623 RDEBUG2("Could not write session VPs to persistent cache: %s", fr_syserror(errno));
2626 /* generate a dummy user-style entry which is easy to read back */
2627 fprintf(vp_file, "# SSL cached session\n");
2628 fprintf(vp_file, "%s\n", buffer);
2629 for (vp = fr_cursor_init(&cursor, &vps);
2631 vp = fr_cursor_next(&cursor)) {
2632 vp_prints(buf, sizeof(buf), vp);
2633 fprintf(vp_file, "\t%s,\n", buf);
2639 RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2640 SSL_CTX_remove_session(ssn->ctx,
2645 * Else the session WAS allowed. Copy the cached
2650 char buffer[2 * MAX_SESSION_SIZE + 1];
2652 size = ssn->ssl->session->session_id_length;
2653 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2655 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2657 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2658 FR_TLS_EX_INDEX_VPS);
2660 RWDEBUG("No information in cached session %s", buffer);
2666 RDEBUG("Adding cached attributes for session %s:", buffer);
2667 debug_pair_list(vps);
2669 for (vp = fr_cursor_init(&cursor, &vps);
2671 vp = fr_cursor_next(&cursor)) {
2673 * TLS-* attrs get added back to
2676 if ((vp->da->vendor == 0) &&
2677 (vp->da->attr >= 1910) &&
2678 (vp->da->attr < 1929)) {
2679 pairadd(&request->packet->vps,
2680 paircopyvp(request->packet, vp));
2682 pairadd(&request->reply->vps,
2683 paircopyvp(request->packet, vp));
2687 if (conf->session_cache_path) {
2688 /* "touch" the cached session/vp file */
2691 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2692 conf->session_cache_path, FR_DIR_SEP, buffer
2694 utime(filename, NULL);
2695 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2696 conf->session_cache_path, FR_DIR_SEP, buffer
2698 utime(filename, NULL);
2702 * Mark the request as resumed.
2704 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2712 void tls_fail(tls_session_t *ssn)
2715 * Force the session to NOT be cached.
2717 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2720 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2727 * Decrypt the complete record.
2729 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2730 ssn->dirty_in.used);
2731 if (err != (int) ssn->dirty_in.used) {
2732 record_init(&ssn->dirty_in);
2733 RDEBUG("Failed writing %d to SSL BIO: %d",
2734 ssn->dirty_in.used, err);
2739 * Clear the dirty buffer now that we are done with it
2740 * and init the clean_out buffer to store decrypted data
2742 record_init(&ssn->dirty_in);
2743 record_init(&ssn->clean_out);
2746 * Read (and decrypt) the tunneled data from the
2747 * SSL session, and put it into the decrypted
2750 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2751 sizeof(ssn->clean_out.data));
2756 RDEBUG("SSL_read Error");
2758 code = SSL_get_error(ssn->ssl, err);
2760 case SSL_ERROR_WANT_READ:
2761 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2762 return FR_TLS_MORE_FRAGMENTS;
2764 case SSL_ERROR_WANT_WRITE:
2765 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2769 DEBUG("Error in fragmentation logic: %s",
2770 ERR_error_string(code, NULL));
2773 * FIXME: Call int_ssl_check?
2781 RWDEBUG("No data inside of the tunnel");
2785 * Passed all checks, successfully decrypted data
2787 ssn->clean_out.used = err;
2794 * Acknowledge received is for one of the following messages sent earlier
2795 * 1. Handshake completed Message, so now send, EAP-Success
2796 * 2. Alert Message, now send, EAP-Failure
2797 * 3. Fragment Message, now send, next Fragment
2799 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2801 RDEBUG2("Received TLS ACK");
2804 RERROR("FAIL: Unexpected ACK received. Could not obtain session information");
2805 return FR_TLS_INVALID;
2807 if (ssn->info.initialized == 0) {
2808 RDEBUG("No SSL info available. Waiting for more SSL data");
2809 return FR_TLS_REQUEST;
2811 if ((ssn->info.content_type == handshake) &&
2812 (ssn->info.origin == 0)) {
2813 RERROR("FAIL: ACK without earlier message");
2814 return FR_TLS_INVALID;
2817 switch (ssn->info.content_type) {
2819 RDEBUG2("ACK alert");
2823 if ((ssn->info.handshake_type == finished) &&
2824 (ssn->dirty_out.used == 0)) {
2825 RDEBUG2("ACK handshake is finished");
2828 * From now on all the content is
2829 * application data set it here as nobody else
2832 ssn->info.content_type = application_data;
2833 return FR_TLS_SUCCESS;
2834 } /* else more data to send */
2836 RDEBUG2("ACK handshake fragment handler");
2837 /* Fragmentation handler, send next fragment */
2838 return FR_TLS_REQUEST;
2840 case application_data:
2841 RDEBUG2("ACK handshake fragment handler in application data");
2842 return FR_TLS_REQUEST;
2845 * For the rest of the conditions, switch over
2846 * to the default section below.
2849 RDEBUG2("ACK default");
2850 RERROR("Invalid ACK received: %d",
2851 ssn->info.content_type);
2852 return FR_TLS_INVALID;
2856 #endif /* WITH_TLS */