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", PW_TYPE_BOOLEAN,
781 offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
782 { "lifetime", PW_TYPE_INTEGER,
783 offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
784 { "max_entries", PW_TYPE_INTEGER,
785 offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
786 { "name", PW_TYPE_STRING_PTR,
787 offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
788 { "persist_dir", PW_TYPE_STRING_PTR,
789 offsetof(fr_tls_server_conf_t, session_cache_path), NULL, NULL},
790 { NULL, -1, 0, NULL, NULL } /* end the list */
793 static CONF_PARSER verify_config[] = {
794 { "tmpdir", PW_TYPE_STRING_PTR,
795 offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
796 { "client", PW_TYPE_STRING_PTR,
797 offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
798 { NULL, -1, 0, NULL, NULL } /* end the list */
801 #ifdef HAVE_OPENSSL_OCSP_H
802 static CONF_PARSER ocsp_config[] = {
803 { "enable", PW_TYPE_BOOLEAN,
804 offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
805 { "override_cert_url", PW_TYPE_BOOLEAN,
806 offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
807 { "url", PW_TYPE_STRING_PTR,
808 offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
809 { "use_nonce", PW_TYPE_BOOLEAN,
810 offsetof(fr_tls_server_conf_t, ocsp_use_nonce), NULL, "yes"},
811 { "timeout", PW_TYPE_INTEGER,
812 offsetof(fr_tls_server_conf_t, ocsp_timeout), NULL, "yes"},
813 { "softfail", PW_TYPE_BOOLEAN,
814 offsetof(fr_tls_server_conf_t, ocsp_softfail), NULL, "yes"},
815 { NULL, -1, 0, NULL, NULL } /* end the list */
819 static CONF_PARSER tls_server_config[] = {
820 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
821 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
822 { "dh_key_exchange", PW_TYPE_BOOLEAN,
823 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
824 { "rsa_key_length", PW_TYPE_INTEGER,
825 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
826 { "dh_key_length", PW_TYPE_INTEGER,
827 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
828 { "verify_depth", PW_TYPE_INTEGER,
829 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
830 { "CA_path", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED,
831 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
832 { "ca_path", PW_TYPE_FILE_INPUT,
833 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
834 { "pem_file_type", PW_TYPE_BOOLEAN,
835 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
836 { "private_key_file", PW_TYPE_FILE_INPUT,
837 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
838 { "certificate_file", PW_TYPE_FILE_INPUT,
839 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
840 { "CA_file", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED,
841 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
842 { "ca_file", PW_TYPE_FILE_INPUT,
843 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
844 { "private_key_password", PW_TYPE_STRING_PTR | PW_TYPE_SECRET,
845 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
846 #ifdef PSK_MAX_IDENTITY_LEN
847 { "psk_identity", PW_TYPE_STRING_PTR,
848 offsetof(fr_tls_server_conf_t, psk_identity), NULL, NULL },
849 { "psk_hexphrase", PW_TYPE_STRING_PTR | PW_TYPE_SECRET,
850 offsetof(fr_tls_server_conf_t, psk_password), NULL, NULL },
852 { "dh_file", PW_TYPE_STRING_PTR,
853 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
854 { "random_file", PW_TYPE_STRING_PTR,
855 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
856 { "fragment_size", PW_TYPE_INTEGER,
857 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
858 { "include_length", PW_TYPE_BOOLEAN,
859 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
860 { "check_crl", PW_TYPE_BOOLEAN,
861 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
862 { "allow_expired_crl", PW_TYPE_BOOLEAN,
863 offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
864 { "check_cert_cn", PW_TYPE_STRING_PTR,
865 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
866 { "cipher_list", PW_TYPE_STRING_PTR,
867 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
868 { "check_cert_issuer", PW_TYPE_STRING_PTR,
869 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
870 { "require_client_cert", PW_TYPE_BOOLEAN,
871 offsetof(fr_tls_server_conf_t, require_client_cert), NULL, NULL },
873 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
874 #ifndef OPENSSL_NO_ECDH
875 { "ecdh_curve", PW_TYPE_STRING_PTR,
876 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
880 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (void const *) cache_config },
882 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (void const *) verify_config },
884 #ifdef HAVE_OPENSSL_OCSP_H
885 { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (void const *) ocsp_config },
888 { NULL, -1, 0, NULL, NULL } /* end the list */
892 static CONF_PARSER tls_client_config[] = {
893 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
894 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
895 { "dh_key_exchange", PW_TYPE_BOOLEAN,
896 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
897 { "rsa_key_length", PW_TYPE_INTEGER,
898 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
899 { "dh_key_length", PW_TYPE_INTEGER,
900 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
901 { "verify_depth", PW_TYPE_INTEGER,
902 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
903 { "ca_path", PW_TYPE_FILE_INPUT,
904 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
905 { "pem_file_type", PW_TYPE_BOOLEAN,
906 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
907 { "private_key_file", PW_TYPE_FILE_INPUT,
908 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
909 { "certificate_file", PW_TYPE_FILE_INPUT,
910 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
911 { "ca_file", PW_TYPE_FILE_INPUT,
912 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
913 { "private_key_password", PW_TYPE_STRING_PTR | PW_TYPE_SECRET,
914 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
915 { "dh_file", PW_TYPE_STRING_PTR,
916 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
917 { "random_file", PW_TYPE_STRING_PTR,
918 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
919 { "fragment_size", PW_TYPE_INTEGER,
920 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
921 { "include_length", PW_TYPE_BOOLEAN,
922 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
923 { "check_crl", PW_TYPE_BOOLEAN,
924 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
925 { "check_cert_cn", PW_TYPE_STRING_PTR,
926 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
927 { "cipher_list", PW_TYPE_STRING_PTR,
928 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
929 { "check_cert_issuer", PW_TYPE_STRING_PTR,
930 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
932 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
933 #ifndef OPENSSL_NO_ECDH
934 { "ecdh_curve", PW_TYPE_STRING_PTR,
935 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
939 { NULL, -1, 0, NULL, NULL } /* end the list */
944 * TODO: Check for the type of key exchange * like conf->dh_key
946 static int load_dh_params(SSL_CTX *ctx, char *file)
953 if ((bio = BIO_new_file(file, "r")) == NULL) {
954 ERROR("tls: Unable to open DH file - %s", file);
958 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
961 WDEBUG2("tls: Unable to set DH parameters. DH cipher suites may not work!");
962 WDEBUG2("Fix this by running the OpenSSL command listed in eap.conf");
966 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
967 ERROR("tls: Unable to set DH parameters");
978 * Generate ephemeral RSA keys.
980 static int generate_eph_rsa_key(SSL_CTX *ctx)
984 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
986 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
987 ERROR("tls: Couldn't set ephemeral RSA key");
995 /* index we use to store cached session VPs
996 * needs to be dynamic so we can supply a "free" function
998 static int FR_TLS_EX_INDEX_VPS = -1;
1001 * Print debugging messages, and free data.
1003 * FIXME: Write sessions to some long-term storage, so that
1004 * session resumption can still occur after the server
1007 #define MAX_SESSION_SIZE (256)
1009 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1012 char buffer[2 * MAX_SESSION_SIZE + 1];
1013 fr_tls_server_conf_t *conf;
1015 size = sess->session_id_length;
1016 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1018 fr_bin2hex(buffer, sess->session_id, size);
1020 DEBUG2(" SSL: Removing session %s from the cache", buffer);
1021 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1022 if (conf && conf->session_cache_path) {
1026 /* remove session and any cached VPs */
1027 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1028 conf->session_cache_path, FR_DIR_SEP, buffer);
1029 rv = unlink(filename);
1031 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
1033 /* VPs might be absent; might not have been written to disk yet */
1034 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1035 conf->session_cache_path, FR_DIR_SEP, buffer);
1042 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1045 char buffer[2 * MAX_SESSION_SIZE + 1];
1046 fr_tls_server_conf_t *conf;
1047 unsigned char *sess_blob = NULL;
1049 size = sess->session_id_length;
1050 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1052 fr_bin2hex(buffer, sess->session_id, size);
1054 DEBUG2(" SSL: adding session %s to cache", buffer);
1056 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1057 if (conf && conf->session_cache_path) {
1058 int fd, rv, todo, blob_len;
1062 /* find out what length data we need */
1063 blob_len = i2d_SSL_SESSION(sess, NULL);
1065 /* something went wrong */
1066 DEBUG2(" SSL: could not find buffer length to persist session");
1070 /* alloc and convert to ASN.1 */
1071 sess_blob = talloc_array(conf, unsigned char, blob_len);
1073 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1076 /* openssl mutates &p */
1078 rv = i2d_SSL_SESSION(sess, &p);
1079 if (rv != blob_len) {
1080 DEBUG2(" SSL: could not persist session");
1084 /* open output file */
1085 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1086 conf->session_cache_path, FR_DIR_SEP, buffer);
1087 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1089 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1096 rv = write(fd, p, todo);
1098 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1106 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1110 if (sess_blob) talloc_free(sess_blob);
1115 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1116 unsigned char *data, int len,
1120 char buffer[2 * MAX_SESSION_SIZE + 1];
1121 fr_tls_server_conf_t *conf;
1123 SSL_SESSION *sess = NULL;
1124 unsigned char *sess_data = NULL;
1125 PAIR_LIST *pairlist = NULL;
1128 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1130 fr_bin2hex(buffer, data, size);
1132 DEBUG2(" SSL: Client requested cached session %s", buffer);
1134 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1135 if (conf && conf->session_cache_path) {
1142 /* read in the cached VPs from the .vps file */
1143 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1144 conf->session_cache_path, FR_DIR_SEP, buffer);
1145 rv = pairlist_read(NULL, filename, &pairlist, 1);
1147 /* not safe to un-persist a session w/o VPs */
1148 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1152 /* load the actual SSL session */
1153 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1154 conf->session_cache_path, FR_DIR_SEP, buffer);
1155 fd = open(filename, O_RDONLY);
1157 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1161 rv = fstat(fd, &st);
1163 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1168 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1170 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1178 rv = read(fd, p, todo);
1180 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1189 /* openssl mutates &p */
1191 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1194 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1198 /* cache the VPs into the session */
1199 vp = paircopy(NULL, pairlist->reply);
1200 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1201 DEBUG2(" SSL: Successfully restored session %s", buffer);
1204 if (sess_data) talloc_free(sess_data);
1205 if (pairlist) pairlist_free(&pairlist);
1211 #ifdef HAVE_OPENSSL_OCSP_H
1213 * This function extracts the OCSP Responder URL
1214 * from an existing x509 certificate.
1216 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1217 char **ppath, int *pssl)
1221 AUTHORITY_INFO_ACCESS *aia;
1222 ACCESS_DESCRIPTION *ad;
1224 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1226 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1227 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1228 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1229 if (ad->location->type == GEN_URI) {
1230 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1231 phost, pport, ppath, pssl))
1240 * This function sends a OCSP request to a defined OCSP responder
1241 * and checks the OCSP response for correctness.
1244 /* Maximum leeway in validity period: default 5 minutes */
1245 #define MAX_VALIDITY_PERIOD (5 * 60)
1247 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1248 fr_tls_server_conf_t *conf)
1250 OCSP_CERTID *certid;
1252 OCSP_RESPONSE *resp = NULL;
1253 OCSP_BASICRESP *bresp = NULL;
1258 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1259 BIO *cbio, *bio_out;
1262 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1264 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1268 struct timeval when;
1272 * Create OCSP Request
1274 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1275 req = OCSP_REQUEST_new();
1276 OCSP_request_add0_id(req, certid);
1277 if(conf->ocsp_use_nonce) {
1278 OCSP_request_add1_nonce(req, NULL, 8);
1282 * Send OCSP Request and get OCSP Response
1285 /* Get OCSP responder URL */
1286 if(conf->ocsp_override_url) {
1287 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
1290 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1293 if (!host || !port || !path) {
1294 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP.");
1299 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1301 /* Setup BIO socket to OCSP responder */
1302 cbio = BIO_new_connect(host);
1304 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1306 BIO_set_conn_port(cbio, port);
1307 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1308 BIO_do_connect(cbio);
1310 /* Send OCSP request and wait for response */
1311 resp = OCSP_sendreq_bio(cbio, path, req);
1313 ERROR("Couldn't get OCSP response");
1318 if (conf->ocsp_timeout)
1319 BIO_set_nbio(cbio, 1);
1321 rc = BIO_do_connect(cbio);
1322 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1323 ERROR("Couldn't connect to OCSP responder");
1328 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1330 ERROR("Couldn't send OCSP request");
1335 gettimeofday(&when, NULL);
1336 when.tv_sec += conf->ocsp_timeout;
1339 rc = OCSP_sendreq_nbio(&resp, ctx);
1340 if (conf->ocsp_timeout) {
1341 gettimeofday(&now, NULL);
1342 if (!timercmp(&now, &when, <))
1345 } while ((rc == -1) && BIO_should_retry(cbio));
1347 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1348 ERROR("OCSP response timed out");
1353 OCSP_REQ_CTX_free(ctx);
1356 ERROR("Couldn't get OCSP response");
1362 /* Verify OCSP response status */
1363 status = OCSP_response_status(resp);
1364 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1365 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1366 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1369 bresp = OCSP_response_get1_basic(resp);
1370 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1371 ERROR("OCSP response has wrong nonce value");
1374 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1375 ERROR("Couldn't verify OCSP basic response");
1379 /* Verify OCSP cert status */
1380 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1381 &rev, &thisupd, &nextupd)) {
1382 ERROR("No Status found.\n");
1386 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1387 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1388 ERR_print_errors(bio_out);
1391 BIO_puts(bio_out, "\tThis Update: ");
1392 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1393 BIO_puts(bio_out, "\n");
1395 BIO_puts(bio_out, "\tNext Update: ");
1396 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1397 BIO_puts(bio_out, "\n");
1401 case V_OCSP_CERTSTATUS_GOOD:
1402 DEBUG2("[oscp] --> Cert status: good");
1407 /* REVOKED / UNKNOWN */
1408 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1410 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1411 BIO_puts(bio_out, "\tRevocation Time: ");
1412 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1413 BIO_puts(bio_out, "\n");
1418 /* Free OCSP Stuff */
1419 OCSP_REQUEST_free(req);
1420 OCSP_RESPONSE_free(resp);
1425 OCSP_BASICRESP_free(bresp);
1430 DEBUG2("[ocsp] --> Certificate is valid!");
1433 if (conf->ocsp_softfail) {
1434 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid.");
1435 DEBUG2("[ocsp] --> Warning! This may be insecure.");
1438 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1443 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1449 #endif /* HAVE_OPENSSL_OCSP_H */
1452 * For creating certificate attributes.
1454 static char const *cert_attr_names[6][2] = {
1455 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1456 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1457 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1458 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1459 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1460 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" }
1463 #define FR_TLS_SERIAL (0)
1464 #define FR_TLS_EXPIRATION (1)
1465 #define FR_TLS_SUBJECT (2)
1466 #define FR_TLS_ISSUER (3)
1467 #define FR_TLS_CN (4)
1468 #define FR_TLS_SAN_EMAIL (5)
1471 * Before trusting a certificate, you must make sure that the
1472 * certificate is 'valid'. There are several steps that your
1473 * application can take in determining if a certificate is
1474 * valid. Commonly used steps are:
1476 * 1.Verifying the certificate's signature, and verifying that
1477 * the certificate has been issued by a trusted Certificate
1480 * 2.Verifying that the certificate is valid for the present date
1481 * (i.e. it is being presented within its validity dates).
1483 * 3.Verifying that the certificate has not been revoked by its
1484 * issuing Certificate Authority, by checking with respect to a
1485 * Certificate Revocation List (CRL).
1487 * 4.Verifying that the credentials presented by the certificate
1488 * fulfill additional requirements specific to the application,
1489 * such as with respect to access control lists or with respect
1490 * to OCSP (Online Certificate Status Processing).
1492 * NOTE: This callback will be called multiple times based on the
1493 * depth of the root certificate chain
1495 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1497 char subject[1024]; /* Used for the subject name */
1498 char issuer[1024]; /* Used for the issuer name */
1499 char attribute[1024];
1501 char common_name[1024];
1505 X509_CINF *client_inf;
1506 STACK_OF(X509_EXTENSION) *ext_list;
1508 int err, depth, lookup, loc;
1509 fr_tls_server_conf_t *conf;
1512 ASN1_INTEGER *sn = NULL;
1513 ASN1_TIME *asn_time = NULL;
1516 #ifdef HAVE_OPENSSL_OCSP_H
1517 X509_STORE *ocsp_store = NULL;
1521 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1522 err = X509_STORE_CTX_get_error(ctx);
1523 depth = X509_STORE_CTX_get_error_depth(ctx);
1528 * Log client/issuing cert. If there's an error, log
1531 if ((lookup > 1) && !my_ok) lookup = 1;
1534 * Retrieve the pointer to the SSL of the connection currently treated
1535 * and the application specific data stored into the SSL object.
1537 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1538 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1539 if (!conf) return 1;
1541 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1543 if (!request) return 1; /* FIXME: outbound TLS */
1545 rad_assert(request != NULL);
1546 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1547 rad_assert(certs != NULL);
1548 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1549 #ifdef HAVE_OPENSSL_OCSP_H
1550 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1554 * Get the Serial Number
1557 sn = X509_get_serialNumber(client_cert);
1560 * For this next bit, we create the attributes *only* if
1561 * we're at the client or issuing certificate, AND we
1562 * have a user identity. i.e. we don't create the
1563 * attributes for RadSec connections.
1566 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1570 for (i = 0; i < sn->length; i++) {
1571 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1574 pairmake(NULL, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1579 * Get the Expiration Date
1582 asn_time = X509_get_notAfter(client_cert);
1583 if (identity && (lookup <= 1) && asn_time &&
1584 (asn_time->length < (int) sizeof(buf))) {
1585 memcpy(buf, (char*) asn_time->data, asn_time->length);
1586 buf[asn_time->length] = '\0';
1587 pairmake(NULL, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1591 * Get the Subject & Issuer
1593 subject[0] = issuer[0] = '\0';
1594 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1596 subject[sizeof(subject) - 1] = '\0';
1597 if (identity && (lookup <= 1) && subject[0]) {
1598 pairmake(NULL, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1601 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1603 issuer[sizeof(issuer) - 1] = '\0';
1604 if (identity && (lookup <= 1) && issuer[0]) {
1605 pairmake(NULL, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1609 * Get the Common Name, if there is a subject.
1611 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1612 NID_commonName, common_name, sizeof(common_name));
1613 common_name[sizeof(common_name) - 1] = '\0';
1614 if (identity && (lookup <= 1) && common_name[0] && subject[0]) {
1615 pairmake(NULL, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1620 * Get the RFC822 Subject Alternative Name
1622 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1623 if (lookup <= 1 && loc >= 0) {
1624 X509_EXTENSION *ext = NULL;
1625 GENERAL_NAMES *names = NULL;
1628 if ((ext = X509_get_ext(client_cert, loc)) &&
1629 (names = X509V3_EXT_d2i(ext))) {
1630 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1631 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1633 switch (name->type) {
1635 pairmake(NULL, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1636 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1639 /* XXX TODO handle other SAN types */
1645 sk_GENERAL_NAME_free(names);
1647 #endif /* GEN_EMAIL */
1650 * If the CRL has expired, that might still be OK.
1653 (conf->allow_expired_crl) &&
1654 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1656 X509_STORE_CTX_set_error( ctx, 0 );
1660 char const *p = X509_verify_cert_error_string(err);
1661 ERROR("--> verify error:num=%d:%s\n",err, p);
1662 REDEBUG("SSL says error %d : %s", err, p);
1667 client_inf = client_cert->cert_info;
1668 ext_list = client_inf->extensions;
1674 * Grab the X509 extensions, and create attributes out of them.
1675 * For laziness, we re-use the OpenSSL names
1677 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1682 out = BIO_new(BIO_s_mem());
1683 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1685 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1687 X509_EXTENSION *ext;
1690 ext = sk_X509_EXTENSION_value(ext_list, i);
1692 obj = X509_EXTENSION_get_object(ext);
1693 i2a_ASN1_OBJECT(out, obj);
1694 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1695 if (len <= 0) continue;
1697 attribute[16 + len] = '\0';
1699 X509V3_EXT_print(out, ext, 0, 0);
1700 len = BIO_read(out, value , sizeof(value) - 1);
1701 if (len <= 0) continue;
1706 * Mash the OpenSSL name to our name, and
1707 * create the attribute.
1709 for (p = value + 16; *p != '\0'; p++) {
1710 if (*p == ' ') *p = '-';
1713 vp = pairmake(NULL, certs, attribute, value, T_OP_ADD);
1714 if (vp) debug_pair_list(vp);
1720 switch (ctx->error) {
1722 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1723 ERROR("issuer= %s\n", issuer);
1725 case X509_V_ERR_CERT_NOT_YET_VALID:
1726 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1727 ERROR("notBefore=");
1729 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1732 case X509_V_ERR_CERT_HAS_EXPIRED:
1733 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1736 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1742 * If we're at the actual client cert, apply additional
1747 * If the conf tells us to, check cert issuer
1748 * against the specified value and fail
1749 * verification if they don't match.
1751 if (conf->check_cert_issuer &&
1752 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1753 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1758 * If the conf tells us to, check the CN in the
1759 * cert against xlat'ed value, but only if the
1760 * previous checks passed.
1762 if (my_ok && conf->check_cert_cn) {
1763 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1764 /* if this fails, fail the verification */
1767 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1768 if (strcmp(cn_str, common_name) != 0) {
1769 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1773 } /* check_cert_cn */
1775 #ifdef HAVE_OPENSSL_OCSP_H
1776 if (my_ok && conf->ocsp_enable){
1777 RDEBUG2("--> Starting OCSP Request");
1778 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1779 ERROR("Couldn't get issuer_cert for %s", common_name);
1781 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1785 while (conf->verify_client_cert_cmd) {
1790 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1791 conf->verify_tmp_dir, progname);
1792 fd = mkstemp(filename);
1794 RDEBUG("Failed creating file in %s: %s",
1795 conf->verify_tmp_dir, fr_syserror(errno));
1799 fp = fdopen(fd, "w");
1802 RDEBUG("Failed opening file %s: %s",
1803 filename, fr_syserror(errno));
1807 if (!PEM_write_X509(fp, client_cert)) {
1809 RDEBUG("Failed writing certificate to file");
1814 if (!pairmake_packet("TLS-Client-Cert-Filename",
1815 filename, T_OP_SET)) {
1816 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1821 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1822 if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1823 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1824 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1827 RDEBUG("Client certificate CN %s passed external validation", common_name);
1838 if (debug_flag > 0) {
1839 RDEBUG2("chain-depth=%d, ", depth);
1840 RDEBUG2("error=%d", err);
1842 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1843 RDEBUG2("--> BUF-Name = %s", common_name);
1844 RDEBUG2("--> subject = %s", subject);
1845 RDEBUG2("--> issuer = %s", issuer);
1846 RDEBUG2("--> verify return:%d", my_ok);
1852 #ifdef HAVE_OPENSSL_OCSP_H
1854 * Create Global X509 revocation store and use it to verify
1857 * - Load the trusted CAs
1858 * - Load the trusted issuer certificates
1860 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1862 X509_STORE *store = NULL;
1864 store = X509_STORE_new();
1866 /* Load the CAs we trust */
1867 if (conf->ca_file || conf->ca_path)
1868 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1869 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1870 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1874 #ifdef X509_V_FLAG_CRL_CHECK
1875 if (conf->check_crl)
1876 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1880 #endif /* HAVE_OPENSSL_OCSP_H */
1882 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1883 #ifndef OPENSSL_NO_ECDH
1884 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1889 if (!ecdh_curve || !*ecdh_curve) return 0;
1891 nid = OBJ_sn2nid(ecdh_curve);
1893 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1897 ecdh = EC_KEY_new_by_curve_name(nid);
1899 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1903 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1905 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1915 * DIE OPENSSL DIE DIE DIE
1917 * What a palaver, just to free some data attached the
1918 * session. We need to do this because the "remove" callback
1919 * is called when refcount > 0 sometimes, if another thread
1920 * is using the session
1922 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1923 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1924 UNUSED long argl, UNUSED void *argp)
1926 VALUE_PAIR *vp = data_ptr;
1929 DEBUG2(" Freeing cached session VPs %p", vp);
1935 * Add all the default ciphers and message digests
1936 * Create our context.
1938 * This should be called exactly once from main.
1940 int tls_global_init(char const *acknowledged)
1944 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
1945 SSL_library_init(); /* initialize library */
1946 #ifdef HAVE_OPENSSL_EVP_H
1947 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
1950 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
1954 /* Check for bad versions */
1955 v = (uint64_t) SSLeay();
1957 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
1958 libssl_defect_t *defect = &libssl_defects[i];
1960 if ((v >= defect->low) && (v <= defect->high)) {
1961 ERROR("Refusing to start with libssl version %s (in range %s)",
1962 ssl_version(), ssl_version_range(defect->low, defect->high));
1963 ERROR("Security advisory %s (%s)", defect->id, defect->name);
1964 ERROR("%s", defect->comment);
1971 INFO("Once you have verified libssl has been correctly patched, "
1972 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
1981 * Create Global context SSL and use it in every new session
1983 * - Load the trusted CAs
1984 * - Load the Private key & the certificate
1985 * - Set the Context options & Verify options
1987 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
1990 X509_STORE *certstore;
1991 int verify_mode = SSL_VERIFY_NONE;
1992 int ctx_options = 0;
1996 * SHA256 is in all versions of OpenSSL, but isn't
1997 * initialized by default. It's needed for WiMAX
2000 #ifdef HAVE_OPENSSL_EVP_SHA256
2001 EVP_add_digest(EVP_sha256());
2004 ctx = SSL_CTX_new(TLSv1_method());
2007 while ((err = ERR_get_error())) {
2008 DEBUG("Failed creating SSL context: %s",
2009 ERR_error_string(err, NULL));
2015 * Save the config on the context so that callbacks which
2016 * only get SSL_CTX* e.g. session persistence, can get it
2018 SSL_CTX_set_app_data(ctx, conf);
2021 * Identify the type of certificates that needs to be loaded
2023 if (conf->file_type) {
2024 type = SSL_FILETYPE_PEM;
2026 type = SSL_FILETYPE_ASN1;
2030 * Set the password to load private key
2032 if (conf->private_key_password) {
2035 * We don't want to put the private key password in eap.conf, so check
2036 * for our special string which indicates we should get the password
2039 char const* special_string = "Apple:UseCertAdmin";
2040 if (strncmp(conf->private_key_password,
2042 strlen(special_string)) == 0)
2045 long const max_password_len = 128;
2046 snprintf(cmd, sizeof(cmd) - 1,
2047 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2048 conf->private_key_file);
2050 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2052 FILE* cmd_pipe = popen(cmd, "r");
2054 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2055 ERROR("Error reading private_key_file %s", conf->private_key_file);
2059 talloc_free(conf->private_key_password);
2060 conf->private_key_password = talloc_array(conf, char, max_password_len);
2061 if (!conf->private_key_password) {
2062 ERROR("TLS: Can't allocate space for private_key_password");
2063 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2068 fgets(conf->private_key_password, max_password_len, cmd_pipe);
2071 /* Get rid of newline at end of password. */
2072 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
2074 DEBUG3("tls: Password from command = \"%s\"", conf->private_key_password);
2077 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
2078 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2081 #ifdef PSK_MAX_IDENTITY_LEN
2082 if ((conf->psk_identity && !conf->psk_password) ||
2083 (!conf->psk_identity && conf->psk_password) ||
2084 (conf->psk_identity && !*conf->psk_identity) ||
2085 (conf->psk_password && !*conf->psk_password)) {
2086 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2090 if (conf->psk_identity) {
2091 size_t psk_len, hex_len;
2092 char buffer[PSK_MAX_PSK_LEN];
2094 if (conf->certificate_file ||
2095 conf->private_key_password || conf->private_key_file ||
2096 conf->ca_file || conf->ca_path) {
2097 ERROR("When PSKs are used, No certificate configuration is permitted");
2102 SSL_CTX_set_psk_client_callback(ctx,
2103 psk_client_callback);
2105 SSL_CTX_set_psk_server_callback(ctx,
2106 psk_server_callback);
2109 psk_len = strlen(conf->psk_password);
2110 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2111 ERROR("psk_hexphrase is too long (max %d)",
2116 hex_len = fr_hex2bin((uint8_t *) buffer, conf->psk_password, psk_len);
2117 if (psk_len != (2 * hex_len)) {
2118 ERROR("psk_hexphrase is not all hex");
2125 (void) client; /* -Wunused */
2129 * Load our keys and certificates
2131 * If certificates are of type PEM then we can make use
2132 * of cert chain authentication using openssl api call
2133 * SSL_CTX_use_certificate_chain_file. Please see how
2134 * the cert chain needs to be given in PEM from
2137 if (!conf->certificate_file) goto load_ca;
2139 if (type == SSL_FILETYPE_PEM) {
2140 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2141 ERROR("Error reading certificate file %s:%s",
2142 conf->certificate_file,
2143 ERR_error_string(ERR_get_error(), NULL));
2147 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2148 ERROR("Error reading certificate file %s:%s",
2149 conf->certificate_file,
2150 ERR_error_string(ERR_get_error(), NULL));
2154 /* Load the CAs we trust */
2156 if (conf->ca_file || conf->ca_path) {
2157 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2158 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2159 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2163 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2165 if (conf->private_key_file) {
2166 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2167 ERROR("Failed reading private key file %s:%s",
2168 conf->private_key_file,
2169 ERR_error_string(ERR_get_error(), NULL));
2174 * Check if the loaded private key is the right one
2176 if (!SSL_CTX_check_private_key(ctx)) {
2177 ERROR("Private key does not match the certificate public key");
2182 #ifdef PSK_MAX_IDENTITY_LEN
2189 ctx_options |= SSL_OP_NO_SSLv2;
2190 ctx_options |= SSL_OP_NO_SSLv3;
2191 #ifdef SSL_OP_NO_TICKET
2192 ctx_options |= SSL_OP_NO_TICKET ;
2196 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2197 * small subgroup attacks and forward secrecy. Always
2200 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2201 * time needed during negotiation, but it is not very
2204 ctx_options |= SSL_OP_SINGLE_DH_USE;
2207 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2208 * in Windows Vista client.
2209 * http://www.openssl.org/~bodo/tls-cbc.txt
2210 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2212 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2214 SSL_CTX_set_options(ctx, ctx_options);
2217 * TODO: Set the RSA & DH
2218 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2219 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2223 * set the message callback to identify the type of
2224 * message. For every new session, there can be a
2225 * different callback argument.
2227 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2231 * Set eliptical curve crypto configuration.
2233 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2234 #ifndef OPENSSL_NO_ECDH
2235 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2241 /* Set Info callback */
2242 SSL_CTX_set_info_callback(ctx, cbtls_info);
2245 * Callbacks, etc. for session resumption.
2247 if (conf->session_cache_enable) {
2248 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2249 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2250 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2252 SSL_CTX_set_quiet_shutdown(ctx, 1);
2253 if (FR_TLS_EX_INDEX_VPS < 0)
2254 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2258 * Check the certificates for revocation.
2260 #ifdef X509_V_FLAG_CRL_CHECK
2261 if (conf->check_crl) {
2262 certstore = SSL_CTX_get_cert_store(ctx);
2263 if (certstore == NULL) {
2264 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2265 ERROR("tls: Error reading Certificate Store");
2268 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2274 * Always verify the peer certificate
2276 verify_mode |= SSL_VERIFY_PEER;
2277 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2278 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2279 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2281 if (conf->verify_depth) {
2282 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2285 /* Load randomness */
2286 if (conf->random_file) {
2287 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2288 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2289 ERROR("tls: Error loading randomness");
2295 * Set the cipher list if we were told to
2297 if (conf->cipher_list) {
2298 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2299 ERROR("tls: Error setting cipher list");
2305 * Setup session caching
2307 if (conf->session_cache_enable) {
2309 * Create a unique context Id per EAP-TLS configuration.
2311 if (conf->session_id_name) {
2312 snprintf(conf->session_context_id,
2313 sizeof(conf->session_context_id),
2315 conf->session_id_name);
2317 snprintf(conf->session_context_id,
2318 sizeof(conf->session_context_id),
2323 * Cache it, and DON'T auto-clear it.
2325 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2327 SSL_CTX_set_session_id_context(ctx,
2328 (unsigned char *) conf->session_context_id,
2329 (unsigned int) strlen(conf->session_context_id));
2332 * Our timeout is in hours, this is in seconds.
2334 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2337 * Set the maximum number of entries in the
2340 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2343 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2351 * Free TLS client/server config
2352 * Should not be called outside this code, as a callback is
2353 * added to automatically free the data when the CONF_SECTION
2356 static int tls_server_conf_free(fr_tls_server_conf_t *conf)
2358 if (conf->ctx) SSL_CTX_free(conf->ctx);
2360 #ifdef HAVE_OPENSSL_OCSP_H
2361 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2362 conf->ocsp_store = NULL;
2366 memset(conf, 0, sizeof(*conf));
2372 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2374 fr_tls_server_conf_t *conf;
2377 * If cs has already been parsed there should be a cached copy
2378 * of conf already stored, so just return that.
2380 conf = cf_data_find(cs, "tls-conf");
2382 DEBUG("Using cached TLS configuration from previous invocation");
2386 conf = talloc_zero(cs, fr_tls_server_conf_t);
2388 ERROR("Out of memory");
2392 talloc_set_destructor(conf, tls_server_conf_free);
2394 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2401 * Save people from their own stupidity.
2403 if (conf->fragment_size < 100) conf->fragment_size = 100;
2405 if (!conf->private_key_file) {
2406 ERROR("TLS Server requires a private key file");
2410 if (!conf->certificate_file) {
2411 ERROR("TLS Server requires a certificate file");
2418 conf->ctx = init_tls_ctx(conf, 0);
2419 if (conf->ctx == NULL) {
2423 #ifdef HAVE_OPENSSL_OCSP_H
2425 * Initialize OCSP Revocation Store
2427 if (conf->ocsp_enable) {
2428 conf->ocsp_store = init_revocation_store(conf);
2429 if (conf->ocsp_store == NULL) goto error;
2431 #endif /*HAVE_OPENSSL_OCSP_H*/
2433 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2437 if (generate_eph_rsa_key(conf->ctx) < 0) {
2441 if (conf->verify_tmp_dir) {
2442 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2443 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2448 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2449 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2454 * Cache conf in cs in case we're asked to parse this again.
2456 cf_data_add(cs, "tls-conf", conf, NULL);
2461 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2463 fr_tls_server_conf_t *conf;
2465 conf = cf_data_find(cs, "tls-conf");
2467 DEBUG("Using cached TLS configuration from previous invocation");
2471 conf = talloc_zero(cs, fr_tls_server_conf_t);
2473 ERROR("Out of memory");
2477 talloc_set_destructor(conf, tls_server_conf_free);
2479 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2486 * Save people from their own stupidity.
2488 if (conf->fragment_size < 100) conf->fragment_size = 100;
2493 conf->ctx = init_tls_ctx(conf, 1);
2494 if (conf->ctx == NULL) {
2498 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2502 if (generate_eph_rsa_key(conf->ctx) < 0) {
2506 cf_data_add(cs, "tls-conf", conf, NULL);
2511 int tls_success(tls_session_t *ssn, REQUEST *request)
2513 VALUE_PAIR *vp, *vps = NULL;
2514 fr_tls_server_conf_t *conf;
2516 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2517 rad_assert(conf != NULL);
2520 * If there's no session resumption, delete the entry
2521 * from the cache. This means either it's disabled
2522 * globally for this SSL context, OR we were told to
2523 * disable it for this user.
2525 * This also means you can't turn it on just for one
2528 if ((!ssn->allow_session_resumption) ||
2529 (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2530 (vp->vp_integer == 0))) {
2531 SSL_CTX_remove_session(ssn->ctx,
2533 ssn->allow_session_resumption = 0;
2536 * If we're in a resumed session and it's
2539 if (SSL_session_reused(ssn->ssl)) {
2540 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed.");
2545 * Else resumption IS allowed, so we store the
2546 * user data in the cache.
2548 } else if (!SSL_session_reused(ssn->ssl)) {
2551 char buffer[2 * MAX_SESSION_SIZE + 1];
2553 size = ssn->ssl->session->session_id_length;
2554 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2556 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2558 vp = paircopy2(NULL, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2559 if (vp) pairadd(&vps, vp);
2561 vp = paircopy2(NULL, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2562 if (vp) pairadd(&vps, vp);
2564 vp = paircopy2(NULL, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2565 if (vp) pairadd(&vps, vp);
2567 vp = paircopy2(NULL, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2568 if (vp) pairadd(&vps, vp);
2570 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2573 * Hmm... the certs should probably be session data.
2577 * @todo: some go into reply, others into
2580 pairadd(&vps, paircopy(NULL, *certs));
2584 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2585 SSL_SESSION_set_ex_data(ssn->ssl->session,
2586 FR_TLS_EX_INDEX_VPS, vps);
2587 if (conf->session_cache_path) {
2588 /* write the VPs to the cache file */
2589 char filename[256], buf[1024];
2592 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2593 conf->session_cache_path, FR_DIR_SEP, buffer
2595 vp_file = fopen(filename, "w");
2596 if (vp_file == NULL) {
2597 RDEBUG2("Could not write session VPs to persistent cache: %s", fr_syserror(errno));
2600 /* generate a dummy user-style entry which is easy to read back */
2601 fprintf(vp_file, "# SSL cached session\n");
2602 fprintf(vp_file, "%s\n", buffer);
2603 for (vp = fr_cursor_init(&cursor, &vps);
2605 vp = fr_cursor_next(&cursor)) {
2606 vp_prints(buf, sizeof(buf), vp);
2607 fprintf(vp_file, "\t%s,\n", buf);
2613 RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2614 SSL_CTX_remove_session(ssn->ctx,
2619 * Else the session WAS allowed. Copy the cached
2624 char buffer[2 * MAX_SESSION_SIZE + 1];
2626 size = ssn->ssl->session->session_id_length;
2627 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2629 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2631 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2632 FR_TLS_EX_INDEX_VPS);
2634 RWDEBUG("No information in cached session %s", buffer);
2640 RDEBUG("Adding cached attributes for session %s:", buffer);
2641 debug_pair_list(vps);
2643 for (vp = fr_cursor_init(&cursor, &vps);
2645 vp = fr_cursor_next(&cursor)) {
2647 * TLS-* attrs get added back to
2650 if ((vp->da->vendor == 0) &&
2651 (vp->da->attr >= 1910) &&
2652 (vp->da->attr < 1929)) {
2653 pairadd(&request->packet->vps,
2654 paircopyvp(request->packet, vp));
2656 pairadd(&request->reply->vps,
2657 paircopyvp(request->packet, vp));
2661 if (conf->session_cache_path) {
2662 /* "touch" the cached session/vp file */
2665 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2666 conf->session_cache_path, FR_DIR_SEP, buffer
2668 utime(filename, NULL);
2669 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2670 conf->session_cache_path, FR_DIR_SEP, buffer
2672 utime(filename, NULL);
2676 * Mark the request as resumed.
2678 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2686 void tls_fail(tls_session_t *ssn)
2689 * Force the session to NOT be cached.
2691 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2694 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2701 * Decrypt the complete record.
2703 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2704 ssn->dirty_in.used);
2705 if (err != (int) ssn->dirty_in.used) {
2706 record_init(&ssn->dirty_in);
2707 RDEBUG("Failed writing %d to SSL BIO: %d",
2708 ssn->dirty_in.used, err);
2713 * Clear the dirty buffer now that we are done with it
2714 * and init the clean_out buffer to store decrypted data
2716 record_init(&ssn->dirty_in);
2717 record_init(&ssn->clean_out);
2720 * Read (and decrypt) the tunneled data from the
2721 * SSL session, and put it into the decrypted
2724 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2725 sizeof(ssn->clean_out.data));
2730 RDEBUG("SSL_read Error");
2732 code = SSL_get_error(ssn->ssl, err);
2734 case SSL_ERROR_WANT_READ:
2735 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2736 return FR_TLS_MORE_FRAGMENTS;
2738 case SSL_ERROR_WANT_WRITE:
2739 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2743 DEBUG("Error in fragmentation logic: %s",
2744 ERR_error_string(code, NULL));
2747 * FIXME: Call int_ssl_check?
2755 RWDEBUG("No data inside of the tunnel.");
2759 * Passed all checks, successfully decrypted data
2761 ssn->clean_out.used = err;
2768 * Acknowledge received is for one of the following messages sent earlier
2769 * 1. Handshake completed Message, so now send, EAP-Success
2770 * 2. Alert Message, now send, EAP-Failure
2771 * 3. Fragment Message, now send, next Fragment
2773 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2775 RDEBUG2("Received TLS ACK");
2778 RERROR("FAIL: Unexpected ACK received. Could not obtain session information.");
2779 return FR_TLS_INVALID;
2781 if (ssn->info.initialized == 0) {
2782 RDEBUG("No SSL info available. Waiting for more SSL data.");
2783 return FR_TLS_REQUEST;
2785 if ((ssn->info.content_type == handshake) &&
2786 (ssn->info.origin == 0)) {
2787 RERROR("FAIL: ACK without earlier message.");
2788 return FR_TLS_INVALID;
2791 switch (ssn->info.content_type) {
2793 RDEBUG2("ACK alert");
2797 if ((ssn->info.handshake_type == finished) &&
2798 (ssn->dirty_out.used == 0)) {
2799 RDEBUG2("ACK handshake is finished");
2802 * From now on all the content is
2803 * application data set it here as nobody else
2806 ssn->info.content_type = application_data;
2807 return FR_TLS_SUCCESS;
2808 } /* else more data to send */
2810 RDEBUG2("ACK handshake fragment handler");
2811 /* Fragmentation handler, send next fragment */
2812 return FR_TLS_REQUEST;
2814 case application_data:
2815 RDEBUG2("ACK handshake fragment handler in application data");
2816 return FR_TLS_REQUEST;
2819 * For the rest of the conditions, switch over
2820 * to the default section below.
2823 RDEBUG2("ACK default");
2824 RERROR("Invalid ACK received: %d",
2825 ssn->info.content_type);
2826 return FR_TLS_INVALID;
2830 #endif /* WITH_TLS */