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 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
378 if (err != (int) ssn->dirty_in.used) {
379 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
381 record_init(&ssn->dirty_in);
384 record_init(&ssn->dirty_in);
386 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
387 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
389 ssn->clean_out.used += err;
393 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
397 /* Some Extra STATE information for easy debugging */
398 if (SSL_is_init_finished(ssn->ssl)) {
399 DEBUG2("SSL Connection Established\n");
401 if (SSL_in_init(ssn->ssl)) {
402 DEBUG2("In SSL Handshake Phase\n");
404 if (SSL_in_before(ssn->ssl)) {
405 DEBUG2("Before SSL Handshake Phase\n");
407 if (SSL_in_accept_init(ssn->ssl)) {
408 DEBUG2("In SSL Accept mode \n");
410 if (SSL_in_connect_init(ssn->ssl)) {
411 DEBUG2("In SSL Connect mode \n");
414 err = BIO_ctrl_pending(ssn->from_ssl);
416 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
417 sizeof(ssn->dirty_out.data));
419 ssn->dirty_out.used = err;
421 } else if (BIO_should_retry(ssn->from_ssl)) {
422 record_init(&ssn->dirty_in);
423 DEBUG2(" tls: Asking for more data in tunnel");
427 int_ssl_check(request, ssn->ssl, err, "BIO_read");
428 record_init(&ssn->dirty_in);
432 DEBUG2("SSL Application Data");
433 /* Its clean application data, do whatever we want */
434 record_init(&ssn->clean_out);
437 /* We are done with dirty_in, reinitialize it */
438 record_init(&ssn->dirty_in);
443 * Take cleartext user data, and encrypt it into the output buffer,
444 * to send to the client at the other end of the SSL connection.
446 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
451 * If there's un-encrypted data in 'clean_in', then write
452 * that data to the SSL session, and then call the BIO function
453 * to get that encrypted data from the SSL session, into
454 * a buffer which we can then package into an EAP packet.
456 * Based on Server's logic this clean_in is expected to
457 * contain the data to send to the client.
459 if (ssn->clean_in.used > 0) {
462 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
463 record_minus(&ssn->clean_in, NULL, written);
465 /* Get the dirty data from Bio to send it */
466 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
467 sizeof(ssn->dirty_out.data));
469 ssn->dirty_out.used = err;
471 int_ssl_check(request, ssn->ssl, err, "handshake_send");
478 void session_init(tls_session_t *ssn)
481 ssn->into_ssl = ssn->from_ssl = NULL;
482 record_init(&ssn->clean_in);
483 record_init(&ssn->clean_out);
484 record_init(&ssn->dirty_in);
485 record_init(&ssn->dirty_out);
487 memset(&ssn->info, 0, sizeof(ssn->info));
491 ssn->tls_msg_len = 0;
492 ssn->length_flag = 0;
494 ssn->free_opaque = NULL;
497 void session_close(tls_session_t *ssn)
499 SSL_set_quiet_shutdown(ssn->ssl, 1);
500 SSL_shutdown(ssn->ssl);
507 record_close(&ssn->clean_in);
508 record_close(&ssn->clean_out);
509 record_close(&ssn->dirty_in);
510 record_close(&ssn->dirty_out);
514 void session_free(void *ssn)
516 tls_session_t *sess = (tls_session_t *)ssn;
521 * Free any opaque TTLS or PEAP data.
523 if ((sess->opaque) && (sess->free_opaque)) {
524 sess->free_opaque(sess->opaque);
533 static void record_init(record_t *rec)
538 static void record_close(record_t *rec)
545 * Copy data to the intermediate buffer, before we send
548 static unsigned int record_plus(record_t *rec, void const *ptr,
551 unsigned int added = MAX_RECORD_SIZE - rec->used;
557 memcpy(rec->data + rec->used, ptr, added);
563 * Take data from the buffer, and give it to the caller.
565 static unsigned int record_minus(record_t *rec, void *ptr,
568 unsigned int taken = rec->used;
575 memcpy(ptr, rec->data, taken);
579 * This is pretty bad...
582 memmove(rec->data, rec->data + taken, rec->used);
586 void tls_session_information(tls_session_t *tls_session)
588 char const *str_write_p, *str_version, *str_content_type = "";
589 char const *str_details1 = "", *str_details2= "";
593 * Don't print this out in the normal course of
596 if (debug_flag == 0) {
600 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
602 switch (tls_session->info.version) {
604 str_version = "SSL 2.0";
607 str_version = "SSL 3.0 ";
610 str_version = "TLS 1.0 ";
613 str_version = "Unknown TLS version";
617 if (tls_session->info.version == SSL3_VERSION ||
618 tls_session->info.version == TLS1_VERSION) {
619 switch (tls_session->info.content_type) {
620 case SSL3_RT_CHANGE_CIPHER_SPEC:
621 str_content_type = "ChangeCipherSpec";
624 str_content_type = "Alert";
626 case SSL3_RT_HANDSHAKE:
627 str_content_type = "Handshake";
629 case SSL3_RT_APPLICATION_DATA:
630 str_content_type = "ApplicationData";
633 str_content_type = "UnknownContentType";
637 if (tls_session->info.content_type == SSL3_RT_ALERT) {
638 str_details1 = ", ???";
640 if (tls_session->info.record_len == 2) {
642 switch (tls_session->info.alert_level) {
643 case SSL3_AL_WARNING:
644 str_details1 = ", warning";
647 str_details1 = ", fatal";
651 str_details2 = " ???";
652 switch (tls_session->info.alert_description) {
653 case SSL3_AD_CLOSE_NOTIFY:
654 str_details2 = " close_notify";
656 case SSL3_AD_UNEXPECTED_MESSAGE:
657 str_details2 = " unexpected_message";
659 case SSL3_AD_BAD_RECORD_MAC:
660 str_details2 = " bad_record_mac";
662 case TLS1_AD_DECRYPTION_FAILED:
663 str_details2 = " decryption_failed";
665 case TLS1_AD_RECORD_OVERFLOW:
666 str_details2 = " record_overflow";
668 case SSL3_AD_DECOMPRESSION_FAILURE:
669 str_details2 = " decompression_failure";
671 case SSL3_AD_HANDSHAKE_FAILURE:
672 str_details2 = " handshake_failure";
674 case SSL3_AD_BAD_CERTIFICATE:
675 str_details2 = " bad_certificate";
677 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
678 str_details2 = " unsupported_certificate";
680 case SSL3_AD_CERTIFICATE_REVOKED:
681 str_details2 = " certificate_revoked";
683 case SSL3_AD_CERTIFICATE_EXPIRED:
684 str_details2 = " certificate_expired";
686 case SSL3_AD_CERTIFICATE_UNKNOWN:
687 str_details2 = " certificate_unknown";
689 case SSL3_AD_ILLEGAL_PARAMETER:
690 str_details2 = " illegal_parameter";
692 case TLS1_AD_UNKNOWN_CA:
693 str_details2 = " unknown_ca";
695 case TLS1_AD_ACCESS_DENIED:
696 str_details2 = " access_denied";
698 case TLS1_AD_DECODE_ERROR:
699 str_details2 = " decode_error";
701 case TLS1_AD_DECRYPT_ERROR:
702 str_details2 = " decrypt_error";
704 case TLS1_AD_EXPORT_RESTRICTION:
705 str_details2 = " export_restriction";
707 case TLS1_AD_PROTOCOL_VERSION:
708 str_details2 = " protocol_version";
710 case TLS1_AD_INSUFFICIENT_SECURITY:
711 str_details2 = " insufficient_security";
713 case TLS1_AD_INTERNAL_ERROR:
714 str_details2 = " internal_error";
716 case TLS1_AD_USER_CANCELLED:
717 str_details2 = " user_canceled";
719 case TLS1_AD_NO_RENEGOTIATION:
720 str_details2 = " no_renegotiation";
726 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
727 str_details1 = "???";
729 if (tls_session->info.record_len > 0)
730 switch (tls_session->info.handshake_type) {
731 case SSL3_MT_HELLO_REQUEST:
732 str_details1 = ", HelloRequest";
734 case SSL3_MT_CLIENT_HELLO:
735 str_details1 = ", ClientHello";
737 case SSL3_MT_SERVER_HELLO:
738 str_details1 = ", ServerHello";
740 case SSL3_MT_CERTIFICATE:
741 str_details1 = ", Certificate";
743 case SSL3_MT_SERVER_KEY_EXCHANGE:
744 str_details1 = ", ServerKeyExchange";
746 case SSL3_MT_CERTIFICATE_REQUEST:
747 str_details1 = ", CertificateRequest";
749 case SSL3_MT_SERVER_DONE:
750 str_details1 = ", ServerHelloDone";
752 case SSL3_MT_CERTIFICATE_VERIFY:
753 str_details1 = ", CertificateVerify";
755 case SSL3_MT_CLIENT_KEY_EXCHANGE:
756 str_details1 = ", ClientKeyExchange";
758 case SSL3_MT_FINISHED:
759 str_details1 = ", Finished";
765 snprintf(tls_session->info.info_description,
766 sizeof(tls_session->info.info_description),
767 "%s %s%s [length %04lx]%s%s\n",
768 str_write_p, str_version, str_content_type,
769 (unsigned long)tls_session->info.record_len,
770 str_details1, str_details2);
772 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
774 RDEBUG2("%s\n", tls_session->info.info_description);
777 static CONF_PARSER cache_config[] = {
778 { "enable", PW_TYPE_BOOLEAN,
779 offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
780 { "lifetime", PW_TYPE_INTEGER,
781 offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
782 { "max_entries", PW_TYPE_INTEGER,
783 offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
784 { "name", PW_TYPE_STRING_PTR,
785 offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
786 { "persist_dir", PW_TYPE_STRING_PTR,
787 offsetof(fr_tls_server_conf_t, session_cache_path), NULL, NULL},
788 { NULL, -1, 0, NULL, NULL } /* end the list */
791 static CONF_PARSER verify_config[] = {
792 { "tmpdir", PW_TYPE_STRING_PTR,
793 offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
794 { "client", PW_TYPE_STRING_PTR,
795 offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
796 { NULL, -1, 0, NULL, NULL } /* end the list */
799 #ifdef HAVE_OPENSSL_OCSP_H
800 static CONF_PARSER ocsp_config[] = {
801 { "enable", PW_TYPE_BOOLEAN,
802 offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
803 { "override_cert_url", PW_TYPE_BOOLEAN,
804 offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
805 { "url", PW_TYPE_STRING_PTR,
806 offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
807 { "use_nonce", PW_TYPE_BOOLEAN,
808 offsetof(fr_tls_server_conf_t, ocsp_use_nonce), NULL, "yes"},
809 { "timeout", PW_TYPE_INTEGER,
810 offsetof(fr_tls_server_conf_t, ocsp_timeout), NULL, "yes"},
811 { "softfail", PW_TYPE_BOOLEAN,
812 offsetof(fr_tls_server_conf_t, ocsp_softfail), NULL, "yes"},
813 { NULL, -1, 0, NULL, NULL } /* end the list */
817 static CONF_PARSER tls_server_config[] = {
818 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
819 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
820 { "dh_key_exchange", PW_TYPE_BOOLEAN,
821 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
822 { "rsa_key_length", PW_TYPE_INTEGER,
823 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
824 { "dh_key_length", PW_TYPE_INTEGER,
825 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
826 { "verify_depth", PW_TYPE_INTEGER,
827 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
828 { "CA_path", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED,
829 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
830 { "ca_path", PW_TYPE_FILE_INPUT,
831 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
832 { "pem_file_type", PW_TYPE_BOOLEAN,
833 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
834 { "private_key_file", PW_TYPE_FILE_INPUT,
835 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
836 { "certificate_file", PW_TYPE_FILE_INPUT,
837 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
838 { "CA_file", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED,
839 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
840 { "ca_file", PW_TYPE_FILE_INPUT,
841 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
842 { "private_key_password", PW_TYPE_STRING_PTR | PW_TYPE_SECRET,
843 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
844 #ifdef PSK_MAX_IDENTITY_LEN
845 { "psk_identity", PW_TYPE_STRING_PTR,
846 offsetof(fr_tls_server_conf_t, psk_identity), NULL, NULL },
847 { "psk_hexphrase", PW_TYPE_STRING_PTR | PW_TYPE_SECRET,
848 offsetof(fr_tls_server_conf_t, psk_password), NULL, NULL },
850 { "dh_file", PW_TYPE_STRING_PTR,
851 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
852 { "random_file", PW_TYPE_STRING_PTR,
853 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
854 { "fragment_size", PW_TYPE_INTEGER,
855 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
856 { "include_length", PW_TYPE_BOOLEAN,
857 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
858 { "check_crl", PW_TYPE_BOOLEAN,
859 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
860 { "allow_expired_crl", PW_TYPE_BOOLEAN,
861 offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
862 { "check_cert_cn", PW_TYPE_STRING_PTR,
863 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
864 { "cipher_list", PW_TYPE_STRING_PTR,
865 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
866 { "check_cert_issuer", PW_TYPE_STRING_PTR,
867 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
868 { "require_client_cert", PW_TYPE_BOOLEAN,
869 offsetof(fr_tls_server_conf_t, require_client_cert), NULL, NULL },
871 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
872 #ifndef OPENSSL_NO_ECDH
873 { "ecdh_curve", PW_TYPE_STRING_PTR,
874 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
878 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (void const *) cache_config },
880 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (void const *) verify_config },
882 #ifdef HAVE_OPENSSL_OCSP_H
883 { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (void const *) ocsp_config },
886 { NULL, -1, 0, NULL, NULL } /* end the list */
890 static CONF_PARSER tls_client_config[] = {
891 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
892 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
893 { "dh_key_exchange", PW_TYPE_BOOLEAN,
894 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
895 { "rsa_key_length", PW_TYPE_INTEGER,
896 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
897 { "dh_key_length", PW_TYPE_INTEGER,
898 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
899 { "verify_depth", PW_TYPE_INTEGER,
900 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
901 { "ca_path", PW_TYPE_FILE_INPUT,
902 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
903 { "pem_file_type", PW_TYPE_BOOLEAN,
904 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
905 { "private_key_file", PW_TYPE_FILE_INPUT,
906 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
907 { "certificate_file", PW_TYPE_FILE_INPUT,
908 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
909 { "ca_file", PW_TYPE_FILE_INPUT,
910 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
911 { "private_key_password", PW_TYPE_STRING_PTR | PW_TYPE_SECRET,
912 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
913 { "dh_file", PW_TYPE_STRING_PTR,
914 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
915 { "random_file", PW_TYPE_STRING_PTR,
916 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
917 { "fragment_size", PW_TYPE_INTEGER,
918 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
919 { "include_length", PW_TYPE_BOOLEAN,
920 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
921 { "check_crl", PW_TYPE_BOOLEAN,
922 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
923 { "check_cert_cn", PW_TYPE_STRING_PTR,
924 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
925 { "cipher_list", PW_TYPE_STRING_PTR,
926 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
927 { "check_cert_issuer", PW_TYPE_STRING_PTR,
928 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
930 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
931 #ifndef OPENSSL_NO_ECDH
932 { "ecdh_curve", PW_TYPE_STRING_PTR,
933 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
937 { NULL, -1, 0, NULL, NULL } /* end the list */
942 * TODO: Check for the type of key exchange * like conf->dh_key
944 static int load_dh_params(SSL_CTX *ctx, char *file)
951 if ((bio = BIO_new_file(file, "r")) == NULL) {
952 ERROR("tls: Unable to open DH file - %s", file);
956 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
959 WDEBUG2("tls: Unable to set DH parameters. DH cipher suites may not work!");
960 WDEBUG2("Fix this by running the OpenSSL command listed in eap.conf");
964 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
965 ERROR("tls: Unable to set DH parameters");
976 * Generate ephemeral RSA keys.
978 static int generate_eph_rsa_key(SSL_CTX *ctx)
982 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
984 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
985 ERROR("tls: Couldn't set ephemeral RSA key");
993 /* index we use to store cached session VPs
994 * needs to be dynamic so we can supply a "free" function
996 static int FR_TLS_EX_INDEX_VPS = -1;
999 * Print debugging messages, and free data.
1001 * FIXME: Write sessions to some long-term storage, so that
1002 * session resumption can still occur after the server
1005 #define MAX_SESSION_SIZE (256)
1007 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1010 char buffer[2 * MAX_SESSION_SIZE + 1];
1011 fr_tls_server_conf_t *conf;
1013 size = sess->session_id_length;
1014 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1016 fr_bin2hex(buffer, sess->session_id, size);
1018 DEBUG2(" SSL: Removing session %s from the cache", buffer);
1019 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1020 if (conf && conf->session_cache_path) {
1024 /* remove session and any cached VPs */
1025 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1026 conf->session_cache_path, FR_DIR_SEP, buffer);
1027 rv = unlink(filename);
1029 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
1031 /* VPs might be absent; might not have been written to disk yet */
1032 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1033 conf->session_cache_path, FR_DIR_SEP, buffer);
1040 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1043 char buffer[2 * MAX_SESSION_SIZE + 1];
1044 fr_tls_server_conf_t *conf;
1045 unsigned char *sess_blob = NULL;
1047 size = sess->session_id_length;
1048 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1050 fr_bin2hex(buffer, sess->session_id, size);
1052 DEBUG2(" SSL: adding session %s to cache", buffer);
1054 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1055 if (conf && conf->session_cache_path) {
1056 int fd, rv, todo, blob_len;
1060 /* find out what length data we need */
1061 blob_len = i2d_SSL_SESSION(sess, NULL);
1063 /* something went wrong */
1064 DEBUG2(" SSL: could not find buffer length to persist session");
1068 /* alloc and convert to ASN.1 */
1069 sess_blob = talloc_array(conf, unsigned char, blob_len);
1071 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1074 /* openssl mutates &p */
1076 rv = i2d_SSL_SESSION(sess, &p);
1077 if (rv != blob_len) {
1078 DEBUG2(" SSL: could not persist session");
1082 /* open output file */
1083 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1084 conf->session_cache_path, FR_DIR_SEP, buffer);
1085 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1087 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1094 rv = write(fd, p, todo);
1096 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1104 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1108 if (sess_blob) talloc_free(sess_blob);
1113 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1114 unsigned char *data, int len,
1118 char buffer[2 * MAX_SESSION_SIZE + 1];
1119 fr_tls_server_conf_t *conf;
1121 SSL_SESSION *sess = NULL;
1122 unsigned char *sess_data = NULL;
1123 PAIR_LIST *pairlist = NULL;
1126 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1128 fr_bin2hex(buffer, data, size);
1130 DEBUG2(" SSL: Client requested cached session %s", buffer);
1132 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1133 if (conf && conf->session_cache_path) {
1140 /* read in the cached VPs from the .vps file */
1141 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1142 conf->session_cache_path, FR_DIR_SEP, buffer);
1143 rv = pairlist_read(NULL, filename, &pairlist, 1);
1145 /* not safe to un-persist a session w/o VPs */
1146 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1150 /* load the actual SSL session */
1151 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1152 conf->session_cache_path, FR_DIR_SEP, buffer);
1153 fd = open(filename, O_RDONLY);
1155 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1159 rv = fstat(fd, &st);
1161 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1166 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1168 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1176 rv = read(fd, p, todo);
1178 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1187 /* openssl mutates &p */
1189 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1192 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1196 /* cache the VPs into the session */
1197 vp = paircopy(NULL, pairlist->reply);
1198 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1199 DEBUG2(" SSL: Successfully restored session %s", buffer);
1202 if (sess_data) talloc_free(sess_data);
1203 if (pairlist) pairlist_free(&pairlist);
1209 #ifdef HAVE_OPENSSL_OCSP_H
1211 * This function extracts the OCSP Responder URL
1212 * from an existing x509 certificate.
1214 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1215 char **ppath, int *pssl)
1219 AUTHORITY_INFO_ACCESS *aia;
1220 ACCESS_DESCRIPTION *ad;
1222 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1224 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1225 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1226 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1227 if (ad->location->type == GEN_URI) {
1228 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1229 phost, pport, ppath, pssl))
1238 * This function sends a OCSP request to a defined OCSP responder
1239 * and checks the OCSP response for correctness.
1242 /* Maximum leeway in validity period: default 5 minutes */
1243 #define MAX_VALIDITY_PERIOD (5 * 60)
1245 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1246 fr_tls_server_conf_t *conf)
1248 OCSP_CERTID *certid;
1250 OCSP_RESPONSE *resp = NULL;
1251 OCSP_BASICRESP *bresp = NULL;
1256 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1257 BIO *cbio, *bio_out;
1260 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1262 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1266 struct timeval when;
1270 * Create OCSP Request
1272 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1273 req = OCSP_REQUEST_new();
1274 OCSP_request_add0_id(req, certid);
1275 if(conf->ocsp_use_nonce) {
1276 OCSP_request_add1_nonce(req, NULL, 8);
1280 * Send OCSP Request and get OCSP Response
1283 /* Get OCSP responder URL */
1284 if(conf->ocsp_override_url) {
1285 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
1288 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1291 if (!host || !port || !path) {
1292 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP.");
1297 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1299 /* Setup BIO socket to OCSP responder */
1300 cbio = BIO_new_connect(host);
1302 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1304 BIO_set_conn_port(cbio, port);
1305 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1306 BIO_do_connect(cbio);
1308 /* Send OCSP request and wait for response */
1309 resp = OCSP_sendreq_bio(cbio, path, req);
1311 ERROR("Couldn't get OCSP response");
1316 if (conf->ocsp_timeout)
1317 BIO_set_nbio(cbio, 1);
1319 rc = BIO_do_connect(cbio);
1320 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1321 ERROR("Couldn't connect to OCSP responder");
1326 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1328 ERROR("Couldn't send OCSP request");
1333 gettimeofday(&when, NULL);
1334 when.tv_sec += conf->ocsp_timeout;
1337 rc = OCSP_sendreq_nbio(&resp, ctx);
1338 if (conf->ocsp_timeout) {
1339 gettimeofday(&now, NULL);
1340 if (!timercmp(&now, &when, <))
1343 } while ((rc == -1) && BIO_should_retry(cbio));
1345 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1346 ERROR("OCSP response timed out");
1351 OCSP_REQ_CTX_free(ctx);
1354 ERROR("Couldn't get OCSP response");
1360 /* Verify OCSP response status */
1361 status = OCSP_response_status(resp);
1362 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1363 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1364 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1367 bresp = OCSP_response_get1_basic(resp);
1368 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1369 ERROR("OCSP response has wrong nonce value");
1372 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1373 ERROR("Couldn't verify OCSP basic response");
1377 /* Verify OCSP cert status */
1378 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1379 &rev, &thisupd, &nextupd)) {
1380 ERROR("No Status found.\n");
1384 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1385 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1386 ERR_print_errors(bio_out);
1389 BIO_puts(bio_out, "\tThis Update: ");
1390 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1391 BIO_puts(bio_out, "\n");
1393 BIO_puts(bio_out, "\tNext Update: ");
1394 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1395 BIO_puts(bio_out, "\n");
1399 case V_OCSP_CERTSTATUS_GOOD:
1400 DEBUG2("[oscp] --> Cert status: good");
1405 /* REVOKED / UNKNOWN */
1406 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1408 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1409 BIO_puts(bio_out, "\tRevocation Time: ");
1410 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1411 BIO_puts(bio_out, "\n");
1416 /* Free OCSP Stuff */
1417 OCSP_REQUEST_free(req);
1418 OCSP_RESPONSE_free(resp);
1423 OCSP_BASICRESP_free(bresp);
1428 DEBUG2("[ocsp] --> Certificate is valid!");
1431 if (conf->ocsp_softfail) {
1432 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid.");
1433 DEBUG2("[ocsp] --> Warning! This may be insecure.");
1436 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1441 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1447 #endif /* HAVE_OPENSSL_OCSP_H */
1450 * For creating certificate attributes.
1452 static char const *cert_attr_names[6][2] = {
1453 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1454 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1455 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1456 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1457 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1458 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" }
1461 #define FR_TLS_SERIAL (0)
1462 #define FR_TLS_EXPIRATION (1)
1463 #define FR_TLS_SUBJECT (2)
1464 #define FR_TLS_ISSUER (3)
1465 #define FR_TLS_CN (4)
1466 #define FR_TLS_SAN_EMAIL (5)
1469 * Before trusting a certificate, you must make sure that the
1470 * certificate is 'valid'. There are several steps that your
1471 * application can take in determining if a certificate is
1472 * valid. Commonly used steps are:
1474 * 1.Verifying the certificate's signature, and verifying that
1475 * the certificate has been issued by a trusted Certificate
1478 * 2.Verifying that the certificate is valid for the present date
1479 * (i.e. it is being presented within its validity dates).
1481 * 3.Verifying that the certificate has not been revoked by its
1482 * issuing Certificate Authority, by checking with respect to a
1483 * Certificate Revocation List (CRL).
1485 * 4.Verifying that the credentials presented by the certificate
1486 * fulfill additional requirements specific to the application,
1487 * such as with respect to access control lists or with respect
1488 * to OCSP (Online Certificate Status Processing).
1490 * NOTE: This callback will be called multiple times based on the
1491 * depth of the root certificate chain
1493 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1495 char subject[1024]; /* Used for the subject name */
1496 char issuer[1024]; /* Used for the issuer name */
1497 char attribute[1024];
1499 char common_name[1024];
1503 X509_CINF *client_inf;
1504 STACK_OF(X509_EXTENSION) *ext_list;
1506 int err, depth, lookup, loc;
1507 fr_tls_server_conf_t *conf;
1510 ASN1_INTEGER *sn = NULL;
1511 ASN1_TIME *asn_time = NULL;
1514 #ifdef HAVE_OPENSSL_OCSP_H
1515 X509_STORE *ocsp_store = NULL;
1519 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1520 err = X509_STORE_CTX_get_error(ctx);
1521 depth = X509_STORE_CTX_get_error_depth(ctx);
1526 * Log client/issuing cert. If there's an error, log
1529 if ((lookup > 1) && !my_ok) lookup = 1;
1532 * Retrieve the pointer to the SSL of the connection currently treated
1533 * and the application specific data stored into the SSL object.
1535 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1536 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1537 if (!conf) return 1;
1539 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1541 if (!request) return 1; /* FIXME: outbound TLS */
1543 rad_assert(request != NULL);
1544 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1545 rad_assert(certs != NULL);
1546 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1547 #ifdef HAVE_OPENSSL_OCSP_H
1548 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1552 * Get the Serial Number
1555 sn = X509_get_serialNumber(client_cert);
1558 * For this next bit, we create the attributes *only* if
1559 * we're at the client or issuing certificate, AND we
1560 * have a user identity. i.e. we don't create the
1561 * attributes for RadSec connections.
1564 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1568 for (i = 0; i < sn->length; i++) {
1569 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1572 pairmake(NULL, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1577 * Get the Expiration Date
1580 asn_time = X509_get_notAfter(client_cert);
1581 if (identity && (lookup <= 1) && asn_time &&
1582 (asn_time->length < (int) sizeof(buf))) {
1583 memcpy(buf, (char*) asn_time->data, asn_time->length);
1584 buf[asn_time->length] = '\0';
1585 pairmake(NULL, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1589 * Get the Subject & Issuer
1591 subject[0] = issuer[0] = '\0';
1592 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1594 subject[sizeof(subject) - 1] = '\0';
1595 if (identity && (lookup <= 1) && subject[0]) {
1596 pairmake(NULL, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1599 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1601 issuer[sizeof(issuer) - 1] = '\0';
1602 if (identity && (lookup <= 1) && issuer[0]) {
1603 pairmake(NULL, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1607 * Get the Common Name, if there is a subject.
1609 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1610 NID_commonName, common_name, sizeof(common_name));
1611 common_name[sizeof(common_name) - 1] = '\0';
1612 if (identity && (lookup <= 1) && common_name[0] && subject[0]) {
1613 pairmake(NULL, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1618 * Get the RFC822 Subject Alternative Name
1620 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1621 if (lookup <= 1 && loc >= 0) {
1622 X509_EXTENSION *ext = NULL;
1623 GENERAL_NAMES *names = NULL;
1626 if ((ext = X509_get_ext(client_cert, loc)) &&
1627 (names = X509V3_EXT_d2i(ext))) {
1628 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1629 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1631 switch (name->type) {
1633 pairmake(NULL, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1634 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1637 /* XXX TODO handle other SAN types */
1643 sk_GENERAL_NAME_free(names);
1645 #endif /* GEN_EMAIL */
1648 * If the CRL has expired, that might still be OK.
1651 (conf->allow_expired_crl) &&
1652 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1654 X509_STORE_CTX_set_error( ctx, 0 );
1658 char const *p = X509_verify_cert_error_string(err);
1659 ERROR("--> verify error:num=%d:%s\n",err, p);
1660 REDEBUG("SSL says error %d : %s", err, p);
1665 client_inf = client_cert->cert_info;
1666 ext_list = client_inf->extensions;
1672 * Grab the X509 extensions, and create attributes out of them.
1673 * For laziness, we re-use the OpenSSL names
1675 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1680 out = BIO_new(BIO_s_mem());
1681 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1683 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1685 X509_EXTENSION *ext;
1688 ext = sk_X509_EXTENSION_value(ext_list, i);
1690 obj = X509_EXTENSION_get_object(ext);
1691 i2a_ASN1_OBJECT(out, obj);
1692 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1693 if (len <= 0) continue;
1695 attribute[16 + len] = '\0';
1697 X509V3_EXT_print(out, ext, 0, 0);
1698 len = BIO_read(out, value , sizeof(value) - 1);
1699 if (len <= 0) continue;
1704 * Mash the OpenSSL name to our name, and
1705 * create the attribute.
1707 for (p = value + 16; *p != '\0'; p++) {
1708 if (*p == ' ') *p = '-';
1711 vp = pairmake(NULL, certs, attribute, value, T_OP_ADD);
1712 if (vp) debug_pair_list(vp);
1718 switch (ctx->error) {
1720 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1721 ERROR("issuer= %s\n", issuer);
1723 case X509_V_ERR_CERT_NOT_YET_VALID:
1724 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1725 ERROR("notBefore=");
1727 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1730 case X509_V_ERR_CERT_HAS_EXPIRED:
1731 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1734 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1740 * If we're at the actual client cert, apply additional
1745 * If the conf tells us to, check cert issuer
1746 * against the specified value and fail
1747 * verification if they don't match.
1749 if (conf->check_cert_issuer &&
1750 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1751 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1756 * If the conf tells us to, check the CN in the
1757 * cert against xlat'ed value, but only if the
1758 * previous checks passed.
1760 if (my_ok && conf->check_cert_cn) {
1761 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1762 /* if this fails, fail the verification */
1765 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1766 if (strcmp(cn_str, common_name) != 0) {
1767 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1771 } /* check_cert_cn */
1773 #ifdef HAVE_OPENSSL_OCSP_H
1774 if (my_ok && conf->ocsp_enable){
1775 RDEBUG2("--> Starting OCSP Request");
1776 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1777 ERROR("Couldn't get issuer_cert for %s", common_name);
1779 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1783 while (conf->verify_client_cert_cmd) {
1788 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1789 conf->verify_tmp_dir, progname);
1790 fd = mkstemp(filename);
1792 RDEBUG("Failed creating file in %s: %s",
1793 conf->verify_tmp_dir, fr_syserror(errno));
1797 fp = fdopen(fd, "w");
1799 RDEBUG("Failed opening file %s: %s",
1800 filename, fr_syserror(errno));
1804 if (!PEM_write_X509(fp, client_cert)) {
1806 RDEBUG("Failed writing certificate to file");
1811 if (!pairmake_packet("TLS-Client-Cert-Filename",
1812 filename, T_OP_SET)) {
1813 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1818 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1819 if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1820 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1821 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1824 RDEBUG("Client certificate CN %s passed external validation", common_name);
1835 if (debug_flag > 0) {
1836 RDEBUG2("chain-depth=%d, ", depth);
1837 RDEBUG2("error=%d", err);
1839 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1840 RDEBUG2("--> BUF-Name = %s", common_name);
1841 RDEBUG2("--> subject = %s", subject);
1842 RDEBUG2("--> issuer = %s", issuer);
1843 RDEBUG2("--> verify return:%d", my_ok);
1849 #ifdef HAVE_OPENSSL_OCSP_H
1851 * Create Global X509 revocation store and use it to verify
1854 * - Load the trusted CAs
1855 * - Load the trusted issuer certificates
1857 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1859 X509_STORE *store = NULL;
1861 store = X509_STORE_new();
1863 /* Load the CAs we trust */
1864 if (conf->ca_file || conf->ca_path)
1865 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1866 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1867 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1871 #ifdef X509_V_FLAG_CRL_CHECK
1872 if (conf->check_crl)
1873 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1877 #endif /* HAVE_OPENSSL_OCSP_H */
1879 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1880 #ifndef OPENSSL_NO_ECDH
1881 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1886 if (!ecdh_curve || !*ecdh_curve) return 0;
1888 nid = OBJ_sn2nid(ecdh_curve);
1890 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1894 ecdh = EC_KEY_new_by_curve_name(nid);
1896 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1900 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1902 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1912 * DIE OPENSSL DIE DIE DIE
1914 * What a palaver, just to free some data attached the
1915 * session. We need to do this because the "remove" callback
1916 * is called when refcount > 0 sometimes, if another thread
1917 * is using the session
1919 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1920 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1921 UNUSED long argl, UNUSED void *argp)
1923 VALUE_PAIR *vp = data_ptr;
1926 DEBUG2(" Freeing cached session VPs %p", vp);
1932 * Add all the default ciphers and message digests
1933 * Create our context.
1935 * This should be called exactly once from main.
1937 int tls_global_init(char const *acknowledged)
1941 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
1942 SSL_library_init(); /* initialize library */
1943 #ifdef HAVE_OPENSSL_EVP_H
1944 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
1947 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
1951 /* Check for bad versions */
1952 v = (uint64_t) SSLeay();
1954 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
1955 libssl_defect_t *defect = &libssl_defects[i];
1957 if ((v >= defect->low) && (v <= defect->high)) {
1958 ERROR("Refusing to start with libssl version %s (in range %s)",
1959 ssl_version(), ssl_version_range(defect->low, defect->high));
1960 ERROR("Security advisory %s (%s)", defect->id, defect->name);
1961 ERROR("%s", defect->comment);
1968 INFO("Once you have verified libssl has been correctly patched, "
1969 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
1978 * Create Global context SSL and use it in every new session
1980 * - Load the trusted CAs
1981 * - Load the Private key & the certificate
1982 * - Set the Context options & Verify options
1984 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
1987 X509_STORE *certstore;
1988 int verify_mode = SSL_VERIFY_NONE;
1989 int ctx_options = 0;
1993 * SHA256 is in all versions of OpenSSL, but isn't
1994 * initialized by default. It's needed for WiMAX
1997 #ifdef HAVE_OPENSSL_EVP_SHA256
1998 EVP_add_digest(EVP_sha256());
2001 ctx = SSL_CTX_new(TLSv1_method());
2004 * Save the config on the context so that callbacks which
2005 * only get SSL_CTX* e.g. session persistence, can get it
2007 SSL_CTX_set_app_data(ctx, conf);
2010 * Identify the type of certificates that needs to be loaded
2012 if (conf->file_type) {
2013 type = SSL_FILETYPE_PEM;
2015 type = SSL_FILETYPE_ASN1;
2019 * Set the password to load private key
2021 if (conf->private_key_password) {
2024 * We don't want to put the private key password in eap.conf, so check
2025 * for our special string which indicates we should get the password
2028 char const* special_string = "Apple:UseCertAdmin";
2029 if (strncmp(conf->private_key_password,
2031 strlen(special_string)) == 0)
2034 long const max_password_len = 128;
2035 snprintf(cmd, sizeof(cmd) - 1,
2036 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2037 conf->private_key_file);
2039 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2041 FILE* cmd_pipe = popen(cmd, "r");
2043 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2044 ERROR("Error reading private_key_file %s", conf->private_key_file);
2048 talloc_free(conf->private_key_password);
2049 conf->private_key_password = talloc_array(conf, char, max_password_len);
2050 if (!conf->private_key_password) {
2051 ERROR("TLS: Can't allocate space for private_key_password");
2052 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2057 fgets(conf->private_key_password, max_password_len, cmd_pipe);
2060 /* Get rid of newline at end of password. */
2061 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
2063 DEBUG3("tls: Password from command = \"%s\"", conf->private_key_password);
2066 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
2067 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2070 #ifdef PSK_MAX_IDENTITY_LEN
2071 if ((conf->psk_identity && !conf->psk_password) ||
2072 (!conf->psk_identity && conf->psk_password) ||
2073 (conf->psk_identity && !*conf->psk_identity) ||
2074 (conf->psk_password && !*conf->psk_password)) {
2075 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2079 if (conf->psk_identity) {
2080 size_t psk_len, hex_len;
2081 char buffer[PSK_MAX_PSK_LEN];
2083 if (conf->certificate_file ||
2084 conf->private_key_password || conf->private_key_file ||
2085 conf->ca_file || conf->ca_path) {
2086 ERROR("When PSKs are used, No certificate configuration is permitted");
2091 SSL_CTX_set_psk_client_callback(ctx,
2092 psk_client_callback);
2094 SSL_CTX_set_psk_server_callback(ctx,
2095 psk_server_callback);
2098 psk_len = strlen(conf->psk_password);
2099 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2100 ERROR("psk_hexphrase is too long (max %d)",
2105 hex_len = fr_hex2bin((uint8_t *) buffer, conf->psk_password, psk_len);
2106 if (psk_len != (2 * hex_len)) {
2107 ERROR("psk_hexphrase is not all hex");
2114 (void) client; /* -Wunused */
2118 * Load our keys and certificates
2120 * If certificates are of type PEM then we can make use
2121 * of cert chain authentication using openssl api call
2122 * SSL_CTX_use_certificate_chain_file. Please see how
2123 * the cert chain needs to be given in PEM from
2126 if (!conf->certificate_file) goto load_ca;
2128 if (type == SSL_FILETYPE_PEM) {
2129 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2130 ERROR("Error reading certificate file %s:%s",
2131 conf->certificate_file,
2132 ERR_error_string(ERR_get_error(), NULL));
2136 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2137 ERROR("Error reading certificate file %s:%s",
2138 conf->certificate_file,
2139 ERR_error_string(ERR_get_error(), NULL));
2143 /* Load the CAs we trust */
2145 if (conf->ca_file || conf->ca_path) {
2146 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2147 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2148 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2152 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2154 if (conf->private_key_file) {
2155 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2156 ERROR("Failed reading private key file %s:%s",
2157 conf->private_key_file,
2158 ERR_error_string(ERR_get_error(), NULL));
2163 * Check if the loaded private key is the right one
2165 if (!SSL_CTX_check_private_key(ctx)) {
2166 ERROR("Private key does not match the certificate public key");
2171 #ifdef PSK_MAX_IDENTITY_LEN
2178 ctx_options |= SSL_OP_NO_SSLv2;
2179 ctx_options |= SSL_OP_NO_SSLv3;
2180 #ifdef SSL_OP_NO_TICKET
2181 ctx_options |= SSL_OP_NO_TICKET ;
2185 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2186 * small subgroup attacks and forward secrecy. Always
2189 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2190 * time needed during negotiation, but it is not very
2193 ctx_options |= SSL_OP_SINGLE_DH_USE;
2196 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2197 * in Windows Vista client.
2198 * http://www.openssl.org/~bodo/tls-cbc.txt
2199 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2201 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2203 SSL_CTX_set_options(ctx, ctx_options);
2206 * TODO: Set the RSA & DH
2207 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2208 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2212 * set the message callback to identify the type of
2213 * message. For every new session, there can be a
2214 * different callback argument.
2216 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2220 * Set eliptical curve crypto configuration.
2222 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2223 #ifndef OPENSSL_NO_ECDH
2224 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2230 /* Set Info callback */
2231 SSL_CTX_set_info_callback(ctx, cbtls_info);
2234 * Callbacks, etc. for session resumption.
2236 if (conf->session_cache_enable) {
2237 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2238 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2239 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2241 SSL_CTX_set_quiet_shutdown(ctx, 1);
2242 if (FR_TLS_EX_INDEX_VPS < 0)
2243 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2247 * Check the certificates for revocation.
2249 #ifdef X509_V_FLAG_CRL_CHECK
2250 if (conf->check_crl) {
2251 certstore = SSL_CTX_get_cert_store(ctx);
2252 if (certstore == NULL) {
2253 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2254 ERROR("tls: Error reading Certificate Store");
2257 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2263 * Always verify the peer certificate
2265 verify_mode |= SSL_VERIFY_PEER;
2266 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2267 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2268 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2270 if (conf->verify_depth) {
2271 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2274 /* Load randomness */
2275 if (conf->random_file) {
2276 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2277 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2278 ERROR("tls: Error loading randomness");
2284 * Set the cipher list if we were told to
2286 if (conf->cipher_list) {
2287 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2288 ERROR("tls: Error setting cipher list");
2294 * Setup session caching
2296 if (conf->session_cache_enable) {
2298 * Create a unique context Id per EAP-TLS configuration.
2300 if (conf->session_id_name) {
2301 snprintf(conf->session_context_id,
2302 sizeof(conf->session_context_id),
2304 conf->session_id_name);
2306 snprintf(conf->session_context_id,
2307 sizeof(conf->session_context_id),
2312 * Cache it, and DON'T auto-clear it.
2314 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2316 SSL_CTX_set_session_id_context(ctx,
2317 (unsigned char *) conf->session_context_id,
2318 (unsigned int) strlen(conf->session_context_id));
2321 * Our timeout is in hours, this is in seconds.
2323 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2326 * Set the maximum number of entries in the
2329 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2332 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2340 * Free TLS client/server config
2341 * Should not be called outside this code, as a callback is
2342 * added to automatically free the data when the CONF_SECTION
2345 static int tls_server_conf_free(fr_tls_server_conf_t *conf)
2347 if (conf->ctx) SSL_CTX_free(conf->ctx);
2349 #ifdef HAVE_OPENSSL_OCSP_H
2350 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2351 conf->ocsp_store = NULL;
2355 memset(conf, 0, sizeof(*conf));
2361 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2363 fr_tls_server_conf_t *conf;
2366 * If cs has already been parsed there should be a cached copy
2367 * of conf already stored, so just return that.
2369 conf = cf_data_find(cs, "tls-conf");
2371 DEBUG("Using cached TLS configuration from previous invocation");
2375 conf = talloc_zero(cs, fr_tls_server_conf_t);
2377 ERROR("Out of memory");
2381 talloc_set_destructor(conf, tls_server_conf_free);
2383 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2390 * Save people from their own stupidity.
2392 if (conf->fragment_size < 100) conf->fragment_size = 100;
2394 if (!conf->private_key_file) {
2395 ERROR("TLS Server requires a private key file");
2399 if (!conf->certificate_file) {
2400 ERROR("TLS Server requires a certificate file");
2407 conf->ctx = init_tls_ctx(conf, 0);
2408 if (conf->ctx == NULL) {
2412 #ifdef HAVE_OPENSSL_OCSP_H
2414 * Initialize OCSP Revocation Store
2416 if (conf->ocsp_enable) {
2417 conf->ocsp_store = init_revocation_store(conf);
2418 if (conf->ocsp_store == NULL) goto error;
2420 #endif /*HAVE_OPENSSL_OCSP_H*/
2422 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2426 if (generate_eph_rsa_key(conf->ctx) < 0) {
2430 if (conf->verify_tmp_dir) {
2431 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2432 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2437 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2438 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2443 * Cache conf in cs in case we're asked to parse this again.
2445 cf_data_add(cs, "tls-conf", conf, NULL);
2450 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2452 fr_tls_server_conf_t *conf;
2454 conf = cf_data_find(cs, "tls-conf");
2456 DEBUG("Using cached TLS configuration from previous invocation");
2460 conf = talloc_zero(cs, fr_tls_server_conf_t);
2462 ERROR("Out of memory");
2466 talloc_set_destructor(conf, tls_server_conf_free);
2468 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2475 * Save people from their own stupidity.
2477 if (conf->fragment_size < 100) conf->fragment_size = 100;
2482 conf->ctx = init_tls_ctx(conf, 1);
2483 if (conf->ctx == NULL) {
2487 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2491 if (generate_eph_rsa_key(conf->ctx) < 0) {
2495 cf_data_add(cs, "tls-conf", conf, NULL);
2500 int tls_success(tls_session_t *ssn, REQUEST *request)
2502 VALUE_PAIR *vp, *vps = NULL;
2503 fr_tls_server_conf_t *conf;
2505 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2506 rad_assert(conf != NULL);
2509 * If there's no session resumption, delete the entry
2510 * from the cache. This means either it's disabled
2511 * globally for this SSL context, OR we were told to
2512 * disable it for this user.
2514 * This also means you can't turn it on just for one
2517 if ((!ssn->allow_session_resumption) ||
2518 (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2519 (vp->vp_integer == 0))) {
2520 SSL_CTX_remove_session(ssn->ctx,
2522 ssn->allow_session_resumption = 0;
2525 * If we're in a resumed session and it's
2528 if (SSL_session_reused(ssn->ssl)) {
2529 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed.");
2534 * Else resumption IS allowed, so we store the
2535 * user data in the cache.
2537 } else if (!SSL_session_reused(ssn->ssl)) {
2540 char buffer[2 * MAX_SESSION_SIZE + 1];
2542 size = ssn->ssl->session->session_id_length;
2543 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2545 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2547 vp = paircopy2(NULL, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2548 if (vp) pairadd(&vps, vp);
2550 vp = paircopy2(NULL, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2551 if (vp) pairadd(&vps, vp);
2553 vp = paircopy2(NULL, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2554 if (vp) pairadd(&vps, vp);
2556 vp = paircopy2(NULL, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2557 if (vp) pairadd(&vps, vp);
2559 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2562 * Hmm... the certs should probably be session data.
2566 * @todo: some go into reply, others into
2569 pairadd(&vps, paircopy(NULL, *certs));
2573 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2574 SSL_SESSION_set_ex_data(ssn->ssl->session,
2575 FR_TLS_EX_INDEX_VPS, vps);
2576 if (conf->session_cache_path) {
2577 /* write the VPs to the cache file */
2578 char filename[256], buf[1024];
2581 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2582 conf->session_cache_path, FR_DIR_SEP, buffer
2584 vp_file = fopen(filename, "w");
2585 if (vp_file == NULL) {
2586 RDEBUG2("Could not write session VPs to persistent cache: %s", fr_syserror(errno));
2589 /* generate a dummy user-style entry which is easy to read back */
2590 fprintf(vp_file, "# SSL cached session\n");
2591 fprintf(vp_file, "%s\n", buffer);
2592 for (vp = fr_cursor_init(&cursor, &vps);
2594 vp = fr_cursor_next(&cursor)) {
2595 vp_prints(buf, sizeof(buf), vp);
2596 fprintf(vp_file, "\t%s,\n", buf);
2602 RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2603 SSL_CTX_remove_session(ssn->ctx,
2608 * Else the session WAS allowed. Copy the cached
2613 char buffer[2 * MAX_SESSION_SIZE + 1];
2615 size = ssn->ssl->session->session_id_length;
2616 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2618 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2620 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2621 FR_TLS_EX_INDEX_VPS);
2623 RWDEBUG("No information in cached session %s", buffer);
2629 RDEBUG("Adding cached attributes for session %s:", buffer);
2630 debug_pair_list(vps);
2632 for (vp = fr_cursor_init(&cursor, &vps);
2634 vp = fr_cursor_next(&cursor)) {
2636 * TLS-* attrs get added back to
2639 if ((vp->da->vendor == 0) &&
2640 (vp->da->attr >= 1910) &&
2641 (vp->da->attr < 1929)) {
2642 pairadd(&request->packet->vps,
2643 paircopyvp(request->packet, vp));
2645 pairadd(&request->reply->vps,
2646 paircopyvp(request->packet, vp));
2650 if (conf->session_cache_path) {
2651 /* "touch" the cached session/vp file */
2654 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2655 conf->session_cache_path, FR_DIR_SEP, buffer
2657 utime(filename, NULL);
2658 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2659 conf->session_cache_path, FR_DIR_SEP, buffer
2661 utime(filename, NULL);
2665 * Mark the request as resumed.
2667 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2675 void tls_fail(tls_session_t *ssn)
2678 * Force the session to NOT be cached.
2680 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2683 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2690 * Decrypt the complete record.
2692 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2693 ssn->dirty_in.used);
2694 if (err != (int) ssn->dirty_in.used) {
2695 record_init(&ssn->dirty_in);
2696 RDEBUG("Failed writing %d to SSL BIO: %d",
2697 ssn->dirty_in.used, err);
2702 * Clear the dirty buffer now that we are done with it
2703 * and init the clean_out buffer to store decrypted data
2705 record_init(&ssn->dirty_in);
2706 record_init(&ssn->clean_out);
2709 * Read (and decrypt) the tunneled data from the
2710 * SSL session, and put it into the decrypted
2713 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2714 sizeof(ssn->clean_out.data));
2719 RDEBUG("SSL_read Error");
2721 code = SSL_get_error(ssn->ssl, err);
2723 case SSL_ERROR_WANT_READ:
2724 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2725 return FR_TLS_MORE_FRAGMENTS;
2727 case SSL_ERROR_WANT_WRITE:
2728 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2732 DEBUG("Error in fragmentation logic: %s",
2733 ERR_error_string(code, NULL));
2736 * FIXME: Call int_ssl_check?
2744 RWDEBUG("No data inside of the tunnel.");
2748 * Passed all checks, successfully decrypted data
2750 ssn->clean_out.used = err;
2757 * Acknowledge received is for one of the following messages sent earlier
2758 * 1. Handshake completed Message, so now send, EAP-Success
2759 * 2. Alert Message, now send, EAP-Failure
2760 * 3. Fragment Message, now send, next Fragment
2762 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2764 RDEBUG2("Received TLS ACK");
2767 RERROR("FAIL: Unexpected ACK received. Could not obtain session information.");
2768 return FR_TLS_INVALID;
2770 if (ssn->info.initialized == 0) {
2771 RDEBUG("No SSL info available. Waiting for more SSL data.");
2772 return FR_TLS_REQUEST;
2774 if ((ssn->info.content_type == handshake) &&
2775 (ssn->info.origin == 0)) {
2776 RERROR("FAIL: ACK without earlier message.");
2777 return FR_TLS_INVALID;
2780 switch (ssn->info.content_type) {
2782 RDEBUG2("ACK alert");
2786 if ((ssn->info.handshake_type == finished) &&
2787 (ssn->dirty_out.used == 0)) {
2788 RDEBUG2("ACK handshake is finished");
2791 * From now on all the content is
2792 * application data set it here as nobody else
2795 ssn->info.content_type = application_data;
2796 return FR_TLS_SUCCESS;
2797 } /* else more data to send */
2799 RDEBUG2("ACK handshake fragment handler");
2800 /* Fragmentation handler, send next fragment */
2801 return FR_TLS_REQUEST;
2803 case application_data:
2804 RDEBUG2("ACK handshake fragment handler in application data");
2805 return FR_TLS_REQUEST;
2808 * For the rest of the conditions, switch over
2809 * to the default section below.
2812 RDEBUG2("ACK default");
2813 RERROR("Invalid ACK received: %d",
2814 ssn->info.content_type);
2815 return FR_TLS_INVALID;
2819 #endif /* WITH_TLS */