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 static void tls_server_conf_free(fr_tls_server_conf_t *conf);
56 static void record_init(record_t *buf);
57 static void record_close(record_t *buf);
58 static unsigned int record_plus(record_t *buf, void const *ptr,
60 static unsigned int record_minus(record_t *buf, void *ptr,
63 #ifdef PSK_MAX_IDENTITY_LEN
64 static unsigned int psk_server_callback(SSL *ssl, char const *identity,
66 unsigned int max_psk_len)
69 fr_tls_server_conf_t *conf;
71 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
72 FR_TLS_EX_INDEX_CONF);
76 * FIXME: Look up the PSK password based on the identity!
78 if (strcmp(identity, conf->psk_identity) != 0) {
82 psk_len = strlen(conf->psk_password);
83 if (psk_len > (2 * max_psk_len)) return 0;
85 return fr_hex2bin(psk, conf->psk_password, psk_len);
88 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
89 char *identity, unsigned int max_identity_len,
90 unsigned char *psk, unsigned int max_psk_len)
93 fr_tls_server_conf_t *conf;
95 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
96 FR_TLS_EX_INDEX_CONF);
99 psk_len = strlen(conf->psk_password);
100 if (psk_len > (2 * max_psk_len)) return 0;
102 strlcpy(identity, conf->psk_identity, max_identity_len);
104 return fr_hex2bin(psk, conf->psk_password, psk_len);
109 tls_session_t *tls_new_client_session(fr_tls_server_conf_t *conf, int fd)
112 tls_session_t *ssn = NULL;
114 ssn = talloc_zero(conf, tls_session_t);
115 if (!ssn) return NULL;
117 ssn->ctx = conf->ctx;
118 ssn->ssl = SSL_new(ssn->ctx);
119 rad_assert(ssn->ssl != NULL);
122 * Add the message callback to identify what type of
123 * message/handshake is passed
125 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
126 SSL_set_msg_callback_arg(ssn->ssl, ssn);
127 SSL_set_info_callback(ssn->ssl, cbtls_info);
130 * Always verify the peer certificate.
132 DEBUG2("Requiring Server certificate");
133 verify_mode = SSL_VERIFY_PEER;
134 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
135 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
137 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
138 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
139 SSL_set_fd(ssn->ssl, fd);
140 if (SSL_connect(ssn->ssl) <= 0) {
142 while ((err = ERR_get_error())) {
143 DEBUG("OpenSSL Err says %s",
144 ERR_error_string(err, NULL));
150 ssn->offset = conf->fragment_size;
155 tls_session_t *tls_new_session(fr_tls_server_conf_t *conf, REQUEST *request,
158 tls_session_t *state = NULL;
163 rad_assert(request != NULL);
166 * Manually flush the sessions every so often. If HALF
167 * of the session lifetime has passed since we last
168 * flushed, then flush it again.
170 * FIXME: Also do it every N sessions?
172 if (conf->session_cache_enable &&
173 ((conf->session_last_flushed + (conf->session_timeout * 1800)) <= request->timestamp)){
174 RDEBUG2("Flushing SSL sessions (of #%ld)",
175 SSL_CTX_sess_number(conf->ctx));
177 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
178 conf->session_last_flushed = request->timestamp;
181 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
182 ERROR("SSL: Error creating new SSL: %s",
183 ERR_error_string(ERR_get_error(), NULL));
187 /* We use the SSL's "app_data" to indicate a call-back */
188 SSL_set_app_data(new_tls, NULL);
190 state = talloc_zero(conf, tls_session_t);
193 state->ctx = conf->ctx;
194 state->ssl = new_tls;
197 * Initialize callbacks
199 state->record_init = record_init;
200 state->record_close = record_close;
201 state->record_plus = record_plus;
202 state->record_minus = record_minus;
205 * Create & hook the BIOs to handle the dirty side of the
206 * SSL. This is *very important* as we want to handle
207 * the transmission part. Now the only IO interface
208 * that SSL is aware of, is our defined BIO buffers.
210 * This means that all SSL IO is done to/from memory,
211 * and we can update those BIOs from the packets we've
214 state->into_ssl = BIO_new(BIO_s_mem());
215 state->from_ssl = BIO_new(BIO_s_mem());
216 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
219 * Add the message callback to identify what type of
220 * message/handshake is passed
222 SSL_set_msg_callback(new_tls, cbtls_msg);
223 SSL_set_msg_callback_arg(new_tls, state);
224 SSL_set_info_callback(new_tls, cbtls_info);
227 * In Server mode we only accept.
229 SSL_set_accept_state(state->ssl);
232 * Verify the peer certificate, if asked.
235 RDEBUG2("Requiring client certificate");
236 verify_mode = SSL_VERIFY_PEER;
237 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
238 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
240 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
242 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
243 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
244 state->length_flag = conf->include_length;
247 * We use default fragment size, unless the Framed-MTU
248 * tells us it's too big. Note that we do NOT account
249 * for the EAP-TLS headers if conf->fragment_size is
250 * large, because that config item looks to be confusing.
252 * i.e. it should REALLY be called MTU, and the code here
253 * should figure out what that means for TLS fragment size.
254 * asking the administrator to know the internal details
255 * of EAP-TLS in order to calculate fragment sizes is
258 state->offset = conf->fragment_size;
259 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
260 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
261 state->offset = vp->vp_integer;
264 if (conf->session_cache_enable) {
265 state->allow_session_resumption = 1; /* otherwise it's zero */
274 * Print out some text describing the error.
276 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
281 if ((l = ERR_get_error()) != 0) {
282 char const *p = ERR_error_string(l, NULL);
284 if (request && p) REDEBUG("SSL says: %s", p);
286 e = SSL_get_error(s, ret);
290 * These seem to be harmless and already "dealt
291 * with" by our non-blocking environment. NB:
292 * "ZERO_RETURN" is the clean "error"
293 * indicating a successfully closed SSL
294 * tunnel. We let this happen because our IO
295 * loop should not appear to have broken on
296 * this condition - and outside the IO loop, the
297 * "shutdown" state is checked.
299 * Don't print anything if we ignore the error.
302 case SSL_ERROR_WANT_READ:
303 case SSL_ERROR_WANT_WRITE:
304 case SSL_ERROR_WANT_X509_LOOKUP:
305 case SSL_ERROR_ZERO_RETURN:
309 * These seem to be indications of a genuine
310 * error that should result in the SSL tunnel
311 * being regarded as "dead".
313 case SSL_ERROR_SYSCALL:
314 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
319 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
325 * For any other errors that (a) exist, and (b)
326 * crop up - we need to interpret what to do with
327 * them - so "politely inform" the caller that
328 * the code needs updating here.
330 ERROR("SSL: FATAL SSL error ..... %d\n", e);
338 * We are the server, we always get the dirty data
339 * (Handshake data is also considered as dirty data)
340 * During handshake, since SSL API handles itself,
341 * After clean-up, dirty_out will be filled with
342 * the data required for handshaking. So we check
343 * if dirty_out is empty then we simply send it back.
344 * As of now, if handshake is successful, then we keep going,
347 * Fill the Bio with the dirty data to clean it
348 * Get the cleaned data from SSL, if it is not Handshake data
350 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
354 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
355 if (err != (int) ssn->dirty_in.used) {
356 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
358 record_init(&ssn->dirty_in);
361 record_init(&ssn->dirty_in);
363 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
364 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
366 ssn->clean_out.used += err;
370 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
374 /* Some Extra STATE information for easy debugging */
375 if (SSL_is_init_finished(ssn->ssl)) {
376 DEBUG2("SSL Connection Established\n");
378 if (SSL_in_init(ssn->ssl)) {
379 DEBUG2("In SSL Handshake Phase\n");
381 if (SSL_in_before(ssn->ssl)) {
382 DEBUG2("Before SSL Handshake Phase\n");
384 if (SSL_in_accept_init(ssn->ssl)) {
385 DEBUG2("In SSL Accept mode \n");
387 if (SSL_in_connect_init(ssn->ssl)) {
388 DEBUG2("In SSL Connect mode \n");
391 err = BIO_ctrl_pending(ssn->from_ssl);
393 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
394 sizeof(ssn->dirty_out.data));
396 ssn->dirty_out.used = err;
398 } else if (BIO_should_retry(ssn->from_ssl)) {
399 record_init(&ssn->dirty_in);
400 DEBUG2(" tls: Asking for more data in tunnel");
404 int_ssl_check(request, ssn->ssl, err, "BIO_read");
405 record_init(&ssn->dirty_in);
409 DEBUG2("SSL Application Data");
410 /* Its clean application data, do whatever we want */
411 record_init(&ssn->clean_out);
414 /* We are done with dirty_in, reinitialize it */
415 record_init(&ssn->dirty_in);
420 * Take clear-text user data, and encrypt it into the output buffer,
421 * to send to the client at the other end of the SSL connection.
423 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
428 * If there's un-encrypted data in 'clean_in', then write
429 * that data to the SSL session, and then call the BIO function
430 * to get that encrypted data from the SSL session, into
431 * a buffer which we can then package into an EAP packet.
433 * Based on Server's logic this clean_in is expected to
434 * contain the data to send to the client.
436 if (ssn->clean_in.used > 0) {
439 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
440 record_minus(&ssn->clean_in, NULL, written);
442 /* Get the dirty data from Bio to send it */
443 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
444 sizeof(ssn->dirty_out.data));
446 ssn->dirty_out.used = err;
448 int_ssl_check(request, ssn->ssl, err, "handshake_send");
455 void session_init(tls_session_t *ssn)
458 ssn->into_ssl = ssn->from_ssl = NULL;
459 record_init(&ssn->clean_in);
460 record_init(&ssn->clean_out);
461 record_init(&ssn->dirty_in);
462 record_init(&ssn->dirty_out);
464 memset(&ssn->info, 0, sizeof(ssn->info));
468 ssn->tls_msg_len = 0;
469 ssn->length_flag = 0;
471 ssn->free_opaque = NULL;
474 void session_close(tls_session_t *ssn)
476 SSL_set_quiet_shutdown(ssn->ssl, 1);
477 SSL_shutdown(ssn->ssl);
482 record_close(&ssn->clean_in);
483 record_close(&ssn->clean_out);
484 record_close(&ssn->dirty_in);
485 record_close(&ssn->dirty_out);
489 void session_free(void *ssn)
491 tls_session_t *sess = (tls_session_t *)ssn;
496 * Free any opaque TTLS or PEAP data.
498 if ((sess->opaque) && (sess->free_opaque)) {
499 sess->free_opaque(sess->opaque);
508 static void record_init(record_t *rec)
513 static void record_close(record_t *rec)
520 * Copy data to the intermediate buffer, before we send
523 static unsigned int record_plus(record_t *rec, void const *ptr,
526 unsigned int added = MAX_RECORD_SIZE - rec->used;
532 memcpy(rec->data + rec->used, ptr, added);
538 * Take data from the buffer, and give it to the caller.
540 static unsigned int record_minus(record_t *rec, void *ptr,
543 unsigned int taken = rec->used;
550 memcpy(ptr, rec->data, taken);
554 * This is pretty bad...
557 memmove(rec->data, rec->data + taken, rec->used);
561 void tls_session_information(tls_session_t *tls_session)
563 char const *str_write_p, *str_version, *str_content_type = "";
564 char const *str_details1 = "", *str_details2= "";
568 * Don't print this out in the normal course of
571 if (debug_flag == 0) {
575 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
577 switch (tls_session->info.version) {
579 str_version = "SSL 2.0";
582 str_version = "SSL 3.0 ";
585 str_version = "TLS 1.0 ";
588 str_version = "Unknown TLS version";
592 if (tls_session->info.version == SSL3_VERSION ||
593 tls_session->info.version == TLS1_VERSION) {
594 switch (tls_session->info.content_type) {
595 case SSL3_RT_CHANGE_CIPHER_SPEC:
596 str_content_type = "ChangeCipherSpec";
599 str_content_type = "Alert";
601 case SSL3_RT_HANDSHAKE:
602 str_content_type = "Handshake";
604 case SSL3_RT_APPLICATION_DATA:
605 str_content_type = "ApplicationData";
608 str_content_type = "UnknownContentType";
612 if (tls_session->info.content_type == SSL3_RT_ALERT) {
613 str_details1 = ", ???";
615 if (tls_session->info.record_len == 2) {
617 switch (tls_session->info.alert_level) {
618 case SSL3_AL_WARNING:
619 str_details1 = ", warning";
622 str_details1 = ", fatal";
626 str_details2 = " ???";
627 switch (tls_session->info.alert_description) {
628 case SSL3_AD_CLOSE_NOTIFY:
629 str_details2 = " close_notify";
631 case SSL3_AD_UNEXPECTED_MESSAGE:
632 str_details2 = " unexpected_message";
634 case SSL3_AD_BAD_RECORD_MAC:
635 str_details2 = " bad_record_mac";
637 case TLS1_AD_DECRYPTION_FAILED:
638 str_details2 = " decryption_failed";
640 case TLS1_AD_RECORD_OVERFLOW:
641 str_details2 = " record_overflow";
643 case SSL3_AD_DECOMPRESSION_FAILURE:
644 str_details2 = " decompression_failure";
646 case SSL3_AD_HANDSHAKE_FAILURE:
647 str_details2 = " handshake_failure";
649 case SSL3_AD_BAD_CERTIFICATE:
650 str_details2 = " bad_certificate";
652 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
653 str_details2 = " unsupported_certificate";
655 case SSL3_AD_CERTIFICATE_REVOKED:
656 str_details2 = " certificate_revoked";
658 case SSL3_AD_CERTIFICATE_EXPIRED:
659 str_details2 = " certificate_expired";
661 case SSL3_AD_CERTIFICATE_UNKNOWN:
662 str_details2 = " certificate_unknown";
664 case SSL3_AD_ILLEGAL_PARAMETER:
665 str_details2 = " illegal_parameter";
667 case TLS1_AD_UNKNOWN_CA:
668 str_details2 = " unknown_ca";
670 case TLS1_AD_ACCESS_DENIED:
671 str_details2 = " access_denied";
673 case TLS1_AD_DECODE_ERROR:
674 str_details2 = " decode_error";
676 case TLS1_AD_DECRYPT_ERROR:
677 str_details2 = " decrypt_error";
679 case TLS1_AD_EXPORT_RESTRICTION:
680 str_details2 = " export_restriction";
682 case TLS1_AD_PROTOCOL_VERSION:
683 str_details2 = " protocol_version";
685 case TLS1_AD_INSUFFICIENT_SECURITY:
686 str_details2 = " insufficient_security";
688 case TLS1_AD_INTERNAL_ERROR:
689 str_details2 = " internal_error";
691 case TLS1_AD_USER_CANCELLED:
692 str_details2 = " user_canceled";
694 case TLS1_AD_NO_RENEGOTIATION:
695 str_details2 = " no_renegotiation";
701 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
702 str_details1 = "???";
704 if (tls_session->info.record_len > 0)
705 switch (tls_session->info.handshake_type) {
706 case SSL3_MT_HELLO_REQUEST:
707 str_details1 = ", HelloRequest";
709 case SSL3_MT_CLIENT_HELLO:
710 str_details1 = ", ClientHello";
712 case SSL3_MT_SERVER_HELLO:
713 str_details1 = ", ServerHello";
715 case SSL3_MT_CERTIFICATE:
716 str_details1 = ", Certificate";
718 case SSL3_MT_SERVER_KEY_EXCHANGE:
719 str_details1 = ", ServerKeyExchange";
721 case SSL3_MT_CERTIFICATE_REQUEST:
722 str_details1 = ", CertificateRequest";
724 case SSL3_MT_SERVER_DONE:
725 str_details1 = ", ServerHelloDone";
727 case SSL3_MT_CERTIFICATE_VERIFY:
728 str_details1 = ", CertificateVerify";
730 case SSL3_MT_CLIENT_KEY_EXCHANGE:
731 str_details1 = ", ClientKeyExchange";
733 case SSL3_MT_FINISHED:
734 str_details1 = ", Finished";
740 snprintf(tls_session->info.info_description,
741 sizeof(tls_session->info.info_description),
742 "%s %s%s [length %04lx]%s%s\n",
743 str_write_p, str_version, str_content_type,
744 (unsigned long)tls_session->info.record_len,
745 str_details1, str_details2);
747 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
749 RDEBUG2("%s\n", tls_session->info.info_description);
752 static CONF_PARSER cache_config[] = {
753 { "enable", PW_TYPE_BOOLEAN,
754 offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
755 { "lifetime", PW_TYPE_INTEGER,
756 offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
757 { "max_entries", PW_TYPE_INTEGER,
758 offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
759 { "name", PW_TYPE_STRING_PTR,
760 offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
761 { "persist_dir", PW_TYPE_STRING_PTR,
762 offsetof(fr_tls_server_conf_t, session_cache_path), NULL, NULL},
763 { NULL, -1, 0, NULL, NULL } /* end the list */
766 static CONF_PARSER verify_config[] = {
767 { "tmpdir", PW_TYPE_STRING_PTR,
768 offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
769 { "client", PW_TYPE_STRING_PTR,
770 offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
771 { NULL, -1, 0, NULL, NULL } /* end the list */
774 #ifdef HAVE_OPENSSL_OCSP_H
775 static CONF_PARSER ocsp_config[] = {
776 { "enable", PW_TYPE_BOOLEAN,
777 offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
778 { "override_cert_url", PW_TYPE_BOOLEAN,
779 offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
780 { "url", PW_TYPE_STRING_PTR,
781 offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
782 { "use_nonce", PW_TYPE_BOOLEAN,
783 offsetof(fr_tls_server_conf_t, ocsp_use_nonce), NULL, "yes"},
784 { "timeout", PW_TYPE_INTEGER,
785 offsetof(fr_tls_server_conf_t, ocsp_timeout), NULL, "yes"},
786 { "softfail", PW_TYPE_BOOLEAN,
787 offsetof(fr_tls_server_conf_t, ocsp_softfail), NULL, "yes"},
788 { NULL, -1, 0, NULL, NULL } /* end the list */
792 static CONF_PARSER tls_server_config[] = {
793 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
794 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
795 { "dh_key_exchange", PW_TYPE_BOOLEAN,
796 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
797 { "rsa_key_length", PW_TYPE_INTEGER,
798 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
799 { "dh_key_length", PW_TYPE_INTEGER,
800 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
801 { "verify_depth", PW_TYPE_INTEGER,
802 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
803 { "CA_path", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED,
804 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
805 { "ca_path", PW_TYPE_FILE_INPUT,
806 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
807 { "pem_file_type", PW_TYPE_BOOLEAN,
808 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
809 { "private_key_file", PW_TYPE_FILE_INPUT,
810 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
811 { "certificate_file", PW_TYPE_FILE_INPUT,
812 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
813 { "CA_file", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED,
814 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
815 { "ca_file", PW_TYPE_FILE_INPUT,
816 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
817 { "private_key_password", PW_TYPE_STRING_PTR,
818 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
819 #ifdef PSK_MAX_IDENTITY_LEN
820 { "psk_identity", PW_TYPE_STRING_PTR,
821 offsetof(fr_tls_server_conf_t, psk_identity), NULL, NULL },
822 { "psk_hexphrase", PW_TYPE_STRING_PTR,
823 offsetof(fr_tls_server_conf_t, psk_password), NULL, NULL },
825 { "dh_file", PW_TYPE_STRING_PTR,
826 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
827 { "random_file", PW_TYPE_STRING_PTR,
828 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
829 { "fragment_size", PW_TYPE_INTEGER,
830 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
831 { "include_length", PW_TYPE_BOOLEAN,
832 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
833 { "check_crl", PW_TYPE_BOOLEAN,
834 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
835 { "allow_expired_crl", PW_TYPE_BOOLEAN,
836 offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
837 { "check_cert_cn", PW_TYPE_STRING_PTR,
838 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
839 { "cipher_list", PW_TYPE_STRING_PTR,
840 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
841 { "check_cert_issuer", PW_TYPE_STRING_PTR,
842 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
843 { "require_client_cert", PW_TYPE_BOOLEAN,
844 offsetof(fr_tls_server_conf_t, require_client_cert), NULL, NULL },
846 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
847 #ifndef OPENSSL_NO_ECDH
848 { "ecdh_curve", PW_TYPE_STRING_PTR,
849 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
853 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (void const *) cache_config },
855 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (void const *) verify_config },
857 #ifdef HAVE_OPENSSL_OCSP_H
858 { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (void const *) ocsp_config },
861 { NULL, -1, 0, NULL, NULL } /* end the list */
865 static CONF_PARSER tls_client_config[] = {
866 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
867 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
868 { "dh_key_exchange", PW_TYPE_BOOLEAN,
869 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
870 { "rsa_key_length", PW_TYPE_INTEGER,
871 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
872 { "dh_key_length", PW_TYPE_INTEGER,
873 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
874 { "verify_depth", PW_TYPE_INTEGER,
875 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
876 { "ca_path", PW_TYPE_FILE_INPUT,
877 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
878 { "pem_file_type", PW_TYPE_BOOLEAN,
879 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
880 { "private_key_file", PW_TYPE_FILE_INPUT,
881 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
882 { "certificate_file", PW_TYPE_FILE_INPUT,
883 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
884 { "ca_file", PW_TYPE_FILE_INPUT,
885 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
886 { "private_key_password", PW_TYPE_STRING_PTR,
887 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
888 { "dh_file", PW_TYPE_STRING_PTR,
889 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
890 { "random_file", PW_TYPE_STRING_PTR,
891 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
892 { "fragment_size", PW_TYPE_INTEGER,
893 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
894 { "include_length", PW_TYPE_BOOLEAN,
895 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
896 { "check_crl", PW_TYPE_BOOLEAN,
897 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
898 { "check_cert_cn", PW_TYPE_STRING_PTR,
899 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
900 { "cipher_list", PW_TYPE_STRING_PTR,
901 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
902 { "check_cert_issuer", PW_TYPE_STRING_PTR,
903 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
905 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
906 #ifndef OPENSSL_NO_ECDH
907 { "ecdh_curve", PW_TYPE_STRING_PTR,
908 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
912 { NULL, -1, 0, NULL, NULL } /* end the list */
917 * TODO: Check for the type of key exchange * like conf->dh_key
919 static int load_dh_params(SSL_CTX *ctx, char *file)
924 if ((bio = BIO_new_file(file, "r")) == NULL) {
925 ERROR("tls: Unable to open DH file - %s", file);
929 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
932 WDEBUG2("tls: Unable to set DH parameters. DH cipher suites may not work!");
933 WDEBUG2("Fix this by running the OpenSSL command listed in eap.conf");
937 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
938 ERROR("tls: Unable to set DH parameters");
949 * Generate ephemeral RSA keys.
951 static int generate_eph_rsa_key(SSL_CTX *ctx)
955 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
957 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
958 ERROR("tls: Couldn't set ephemeral RSA key");
966 /* index we use to store cached session VPs
967 * needs to be dynamic so we can supply a "free" function
969 static int FR_TLS_EX_INDEX_VPS = -1;
972 * Print debugging messages, and free data.
974 * FIXME: Write sessions to some long-term storage, so that
975 * session resumption can still occur after the server
978 #define MAX_SESSION_SIZE (256)
980 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
983 char buffer[2 * MAX_SESSION_SIZE + 1];
984 fr_tls_server_conf_t *conf;
986 size = sess->session_id_length;
987 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
989 fr_bin2hex(buffer, sess->session_id, size);
991 DEBUG2(" SSL: Removing session %s from the cache", buffer);
992 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
993 if (conf && conf->session_cache_path) {
997 /* remove session and any cached VPs */
998 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
999 conf->session_cache_path, FR_DIR_SEP, buffer);
1000 rv = unlink(filename);
1002 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, strerror(errno));
1004 /* VPs might be absent; might not have been written to disk yet */
1005 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1006 conf->session_cache_path, FR_DIR_SEP, buffer);
1013 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1016 char buffer[2 * MAX_SESSION_SIZE + 1];
1017 fr_tls_server_conf_t *conf;
1018 unsigned char *sess_blob = NULL;
1020 size = sess->session_id_length;
1021 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1023 fr_bin2hex(buffer, sess->session_id, size);
1025 DEBUG2(" SSL: adding session %s to cache", buffer);
1027 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1028 if (conf && conf->session_cache_path) {
1029 int fd, rv, todo, blob_len;
1033 /* find out what length data we need */
1034 blob_len = i2d_SSL_SESSION(sess, NULL);
1036 /* something went wrong */
1037 DEBUG2(" SSL: could not find buffer length to persist session");
1041 /* alloc and convert to ASN.1 */
1042 sess_blob = talloc_array(conf, unsigned char, blob_len);
1044 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1047 /* openssl mutates &p */
1049 rv = i2d_SSL_SESSION(sess, &p);
1050 if (rv != blob_len) {
1051 DEBUG2(" SSL: could not persist session");
1055 /* open output file */
1056 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1057 conf->session_cache_path, FR_DIR_SEP, buffer);
1058 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1060 DEBUG2(" SSL: could not open session file %s: %s", filename, strerror(errno));
1067 rv = write(fd, p, todo);
1069 DEBUG2(" SSL: failed writing session: %s", strerror(errno));
1077 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1081 if (sess_blob) talloc_free(sess_blob);
1086 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1087 unsigned char *data, int len,
1091 char buffer[2 * MAX_SESSION_SIZE + 1];
1092 fr_tls_server_conf_t *conf;
1094 SSL_SESSION *sess = NULL;
1095 unsigned char *sess_data = NULL;
1096 PAIR_LIST *pairlist = NULL;
1099 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1101 fr_bin2hex(buffer, data, size);
1103 DEBUG2(" SSL: Client requested cached session %s", buffer);
1105 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1106 if (conf && conf->session_cache_path) {
1113 /* read in the cached VPs from the .vps file */
1114 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1115 conf->session_cache_path, FR_DIR_SEP, buffer);
1116 rv = pairlist_read(NULL, filename, &pairlist, 1);
1118 /* not safe to un-persist a session w/o VPs */
1119 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1123 /* load the actual SSL session */
1124 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1125 conf->session_cache_path, FR_DIR_SEP, buffer);
1126 fd = open(filename, O_RDONLY);
1128 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, strerror(errno));
1132 rv = fstat(fd, &st);
1134 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, strerror(errno));
1139 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1141 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1149 rv = read(fd, p, todo);
1151 DEBUG2(" SSL: could not read from persisted session: %s", strerror(errno));
1160 /* openssl mutates &p */
1162 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1165 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1169 /* cache the VPs into the session */
1170 vp = paircopy(NULL, pairlist->reply);
1171 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1172 DEBUG2(" SSL: Successfully restored session %s", buffer);
1175 if (sess_data) talloc_free(sess_data);
1176 if (pairlist) pairlist_free(&pairlist);
1182 #ifdef HAVE_OPENSSL_OCSP_H
1184 * This function extracts the OCSP Responder URL
1185 * from an existing x509 certificate.
1187 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1188 char **ppath, int *pssl)
1192 AUTHORITY_INFO_ACCESS *aia;
1193 ACCESS_DESCRIPTION *ad;
1195 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1197 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1198 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1199 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1200 if (ad->location->type == GEN_URI) {
1201 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1202 phost, pport, ppath, pssl))
1211 * This function sends a OCSP request to a defined OCSP responder
1212 * and checks the OCSP response for correctness.
1215 /* Maximum leeway in validity period: default 5 minutes */
1216 #define MAX_VALIDITY_PERIOD (5 * 60)
1218 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1219 fr_tls_server_conf_t *conf)
1221 OCSP_CERTID *certid;
1223 OCSP_RESPONSE *resp = NULL;
1224 OCSP_BASICRESP *bresp = NULL;
1229 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1230 BIO *cbio, *bio_out;
1233 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1235 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1239 struct timeval when;
1243 * Create OCSP Request
1245 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1246 req = OCSP_REQUEST_new();
1247 OCSP_request_add0_id(req, certid);
1248 if(conf->ocsp_use_nonce) {
1249 OCSP_request_add1_nonce(req, NULL, 8);
1253 * Send OCSP Request and get OCSP Response
1256 /* Get OCSP responder URL */
1257 if(conf->ocsp_override_url) {
1258 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
1261 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1264 if (!host || !port || !path) {
1265 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP.");
1270 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1272 /* Setup BIO socket to OCSP responder */
1273 cbio = BIO_new_connect(host);
1275 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1277 BIO_set_conn_port(cbio, port);
1278 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1279 BIO_do_connect(cbio);
1281 /* Send OCSP request and wait for response */
1282 resp = OCSP_sendreq_bio(cbio, path, req);
1284 ERROR("Couldn't get OCSP response");
1289 if (conf->ocsp_timeout)
1290 BIO_set_nbio(cbio, 1);
1292 rc = BIO_do_connect(cbio);
1293 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1294 ERROR("Couldn't connect to OCSP responder");
1299 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1301 ERROR("Couldn't send OCSP request");
1306 gettimeofday(&when, NULL);
1307 when.tv_sec += conf->ocsp_timeout;
1310 rc = OCSP_sendreq_nbio(&resp, ctx);
1311 if (conf->ocsp_timeout) {
1312 gettimeofday(&now, NULL);
1313 if (!timercmp(&now, &when, <))
1316 } while ((rc == -1) && BIO_should_retry(cbio));
1318 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1319 ERROR("OCSP response timed out");
1324 OCSP_REQ_CTX_free(ctx);
1327 ERROR("Couldn't get OCSP response");
1333 /* Verify OCSP response status */
1334 status = OCSP_response_status(resp);
1335 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1336 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1337 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1340 bresp = OCSP_response_get1_basic(resp);
1341 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1342 ERROR("OCSP response has wrong nonce value");
1345 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1346 ERROR("Couldn't verify OCSP basic response");
1350 /* Verify OCSP cert status */
1351 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1352 &rev, &thisupd, &nextupd)) {
1353 ERROR("No Status found.\n");
1357 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1358 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1359 ERR_print_errors(bio_out);
1362 BIO_puts(bio_out, "\tThis Update: ");
1363 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1364 BIO_puts(bio_out, "\n");
1366 BIO_puts(bio_out, "\tNext Update: ");
1367 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1368 BIO_puts(bio_out, "\n");
1372 case V_OCSP_CERTSTATUS_GOOD:
1373 DEBUG2("[oscp] --> Cert status: good");
1378 /* REVOKED / UNKNOWN */
1379 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1381 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1382 BIO_puts(bio_out, "\tRevocation Time: ");
1383 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1384 BIO_puts(bio_out, "\n");
1389 /* Free OCSP Stuff */
1390 OCSP_REQUEST_free(req);
1391 OCSP_RESPONSE_free(resp);
1396 OCSP_BASICRESP_free(bresp);
1401 DEBUG2("[ocsp] --> Certificate is valid!");
1404 if (conf->ocsp_softfail) {
1405 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid.");
1406 DEBUG2("[ocsp] --> Warning! This may be insecure.");
1409 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1414 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1420 #endif /* HAVE_OPENSSL_OCSP_H */
1423 * For creating certificate attributes.
1425 static char const *cert_attr_names[6][2] = {
1426 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1427 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1428 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1429 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1430 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1431 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" }
1434 #define FR_TLS_SERIAL (0)
1435 #define FR_TLS_EXPIRATION (1)
1436 #define FR_TLS_SUBJECT (2)
1437 #define FR_TLS_ISSUER (3)
1438 #define FR_TLS_CN (4)
1439 #define FR_TLS_SAN_EMAIL (5)
1442 * Before trusting a certificate, you must make sure that the
1443 * certificate is 'valid'. There are several steps that your
1444 * application can take in determining if a certificate is
1445 * valid. Commonly used steps are:
1447 * 1.Verifying the certificate's signature, and verifying that
1448 * the certificate has been issued by a trusted Certificate
1451 * 2.Verifying that the certificate is valid for the present date
1452 * (i.e. it is being presented within its validity dates).
1454 * 3.Verifying that the certificate has not been revoked by its
1455 * issuing Certificate Authority, by checking with respect to a
1456 * Certificate Revocation List (CRL).
1458 * 4.Verifying that the credentials presented by the certificate
1459 * fulfill additional requirements specific to the application,
1460 * such as with respect to access control lists or with respect
1461 * to OCSP (Online Certificate Status Processing).
1463 * NOTE: This callback will be called multiple times based on the
1464 * depth of the root certificate chain
1466 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1468 char subject[1024]; /* Used for the subject name */
1469 char issuer[1024]; /* Used for the issuer name */
1470 char attribute[1024];
1472 char common_name[1024];
1476 X509_CINF *client_inf;
1477 STACK_OF(X509_EXTENSION) *ext_list;
1479 int err, depth, lookup, loc;
1480 fr_tls_server_conf_t *conf;
1483 ASN1_INTEGER *sn = NULL;
1484 ASN1_TIME *asn_time = NULL;
1487 #ifdef HAVE_OPENSSL_OCSP_H
1488 X509_STORE *ocsp_store = NULL;
1492 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1493 err = X509_STORE_CTX_get_error(ctx);
1494 depth = X509_STORE_CTX_get_error_depth(ctx);
1499 * Log client/issuing cert. If there's an error, log
1502 if ((lookup > 1) && !my_ok) lookup = 1;
1505 * Retrieve the pointer to the SSL of the connection currently treated
1506 * and the application specific data stored into the SSL object.
1508 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1509 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1510 if (!conf) return 1;
1512 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1514 if (!request) return 1; /* FIXME: outbound TLS */
1516 rad_assert(request != NULL);
1517 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1518 rad_assert(certs != NULL);
1519 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1520 #ifdef HAVE_OPENSSL_OCSP_H
1521 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1525 * Get the Serial Number
1528 sn = X509_get_serialNumber(client_cert);
1531 * For this next bit, we create the attributes *only* if
1532 * we're at the client or issuing certificate, AND we
1533 * have a user identity. i.e. we don't create the
1534 * attributes for RadSec connections.
1537 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1541 for (i = 0; i < sn->length; i++) {
1542 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1545 pairmake(NULL, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1550 * Get the Expiration Date
1553 asn_time = X509_get_notAfter(client_cert);
1554 if (identity && (lookup <= 1) && asn_time &&
1555 (asn_time->length < (int) sizeof(buf))) {
1556 memcpy(buf, (char*) asn_time->data, asn_time->length);
1557 buf[asn_time->length] = '\0';
1558 pairmake(NULL, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1562 * Get the Subject & Issuer
1564 subject[0] = issuer[0] = '\0';
1565 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1567 subject[sizeof(subject) - 1] = '\0';
1568 if (identity && (lookup <= 1) && subject[0]) {
1569 pairmake(NULL, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1572 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1574 issuer[sizeof(issuer) - 1] = '\0';
1575 if (identity && (lookup <= 1) && issuer[0]) {
1576 pairmake(NULL, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1580 * Get the Common Name, if there is a subject.
1582 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1583 NID_commonName, common_name, sizeof(common_name));
1584 common_name[sizeof(common_name) - 1] = '\0';
1585 if (identity && (lookup <= 1) && common_name[0] && subject[0]) {
1586 pairmake(NULL, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1591 * Get the RFC822 Subject Alternative Name
1593 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1594 if (lookup <= 1 && loc >= 0) {
1595 X509_EXTENSION *ext = NULL;
1596 GENERAL_NAMES *names = NULL;
1599 if ((ext = X509_get_ext(client_cert, loc)) &&
1600 (names = X509V3_EXT_d2i(ext))) {
1601 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1602 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1604 switch (name->type) {
1606 pairmake(NULL, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1607 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1610 /* XXX TODO handle other SAN types */
1616 sk_GENERAL_NAME_free(names);
1618 #endif /* GEN_EMAIL */
1621 * If the CRL has expired, that might still be OK.
1624 (conf->allow_expired_crl) &&
1625 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1627 X509_STORE_CTX_set_error( ctx, 0 );
1631 char const *p = X509_verify_cert_error_string(err);
1632 ERROR("--> verify error:num=%d:%s\n",err, p);
1633 REDEBUG("SSL says error %d : %s", err, p);
1638 client_inf = client_cert->cert_info;
1639 ext_list = client_inf->extensions;
1645 * Grab the X509 extensions, and create attributes out of them.
1646 * For laziness, we re-use the OpenSSL names
1648 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1653 out = BIO_new(BIO_s_mem());
1654 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1656 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1658 X509_EXTENSION *ext;
1661 ext = sk_X509_EXTENSION_value(ext_list, i);
1663 obj = X509_EXTENSION_get_object(ext);
1664 i2a_ASN1_OBJECT(out, obj);
1665 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1666 if (len <= 0) continue;
1668 attribute[16 + len] = '\0';
1670 X509V3_EXT_print(out, ext, 0, 0);
1671 len = BIO_read(out, value , sizeof(issuer) - 1);
1672 if (len <= 0) continue;
1677 * Mash the OpenSSL name to our name, and
1678 * create the attribute.
1680 for (p = value + 16; *p != '\0'; p++) {
1681 if (*p == ' ') *p = '-';
1684 vp = pairmake(NULL, certs, attribute, value, T_OP_ADD);
1685 if (vp) debug_pair_list(vp);
1691 switch (ctx->error) {
1693 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1694 ERROR("issuer= %s\n", issuer);
1696 case X509_V_ERR_CERT_NOT_YET_VALID:
1697 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1698 ERROR("notBefore=");
1700 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1703 case X509_V_ERR_CERT_HAS_EXPIRED:
1704 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1707 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1713 * If we're at the actual client cert, apply additional
1718 * If the conf tells us to, check cert issuer
1719 * against the specified value and fail
1720 * verification if they don't match.
1722 if (conf->check_cert_issuer &&
1723 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1724 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1729 * If the conf tells us to, check the CN in the
1730 * cert against xlat'ed value, but only if the
1731 * previous checks passed.
1733 if (my_ok && conf->check_cert_cn) {
1734 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1735 /* if this fails, fail the verification */
1738 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1739 if (strcmp(cn_str, common_name) != 0) {
1740 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1744 } /* check_cert_cn */
1746 #ifdef HAVE_OPENSSL_OCSP_H
1747 if (my_ok && conf->ocsp_enable){
1748 RDEBUG2("--> Starting OCSP Request");
1749 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1750 ERROR("Couldn't get issuer_cert for %s", common_name);
1752 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1756 while (conf->verify_client_cert_cmd) {
1761 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1762 conf->verify_tmp_dir, progname);
1763 fd = mkstemp(filename);
1765 RDEBUG("Failed creating file in %s: %s",
1766 conf->verify_tmp_dir, strerror(errno));
1770 fp = fdopen(fd, "w");
1772 RDEBUG("Failed opening file %s: %s",
1773 filename, strerror(errno));
1777 if (!PEM_write_X509(fp, client_cert)) {
1779 RDEBUG("Failed writing certificate to file");
1784 if (!pairmake_packet("TLS-Client-Cert-Filename",
1785 filename, T_OP_SET)) {
1786 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1791 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1792 if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1793 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1794 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1797 RDEBUG("Client certificate CN %s passed external validation", common_name);
1808 if (debug_flag > 0) {
1809 RDEBUG2("chain-depth=%d, ", depth);
1810 RDEBUG2("error=%d", err);
1812 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1813 RDEBUG2("--> BUF-Name = %s", common_name);
1814 RDEBUG2("--> subject = %s", subject);
1815 RDEBUG2("--> issuer = %s", issuer);
1816 RDEBUG2("--> verify return:%d", my_ok);
1822 #ifdef HAVE_OPENSSL_OCSP_H
1824 * Create Global X509 revocation store and use it to verify
1827 * - Load the trusted CAs
1828 * - Load the trusted issuer certificates
1830 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1832 X509_STORE *store = NULL;
1834 store = X509_STORE_new();
1836 /* Load the CAs we trust */
1837 if (conf->ca_file || conf->ca_path)
1838 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1839 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1840 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1844 #ifdef X509_V_FLAG_CRL_CHECK
1845 if (conf->check_crl)
1846 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1850 #endif /* HAVE_OPENSSL_OCSP_H */
1852 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1853 #ifndef OPENSSL_NO_ECDH
1854 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1859 if (!ecdh_curve || !*ecdh_curve) return 0;
1861 nid = OBJ_sn2nid(ecdh_curve);
1863 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1867 ecdh = EC_KEY_new_by_curve_name(nid);
1869 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1873 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1875 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1885 * DIE OPENSSL DIE DIE DIE
1887 * What a palaver, just to free some data attached the
1888 * session. We need to do this because the "remove" callback
1889 * is called when refcount > 0 sometimes, if another thread
1890 * is using the session
1892 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1893 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1894 UNUSED long argl, UNUSED void *argp)
1896 VALUE_PAIR *vp = data_ptr;
1899 DEBUG2(" Freeing cached session VPs %p", vp);
1906 * Create Global context SSL and use it in every new session
1908 * - Load the trusted CAs
1909 * - Load the Private key & the certificate
1910 * - Set the Context options & Verify options
1912 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
1915 X509_STORE *certstore;
1916 int verify_mode = SSL_VERIFY_NONE;
1917 int ctx_options = 0;
1921 * Add all the default ciphers and message digests
1922 * Create our context.
1925 SSL_load_error_strings();
1928 * SHA256 is in all versions of OpenSSL, but isn't
1929 * initialized by default. It's needed for WiMAX
1932 #ifdef HAVE_OPENSSL_EVP_SHA256
1933 EVP_add_digest(EVP_sha256());
1936 ctx = SSL_CTX_new(TLSv1_method());
1939 * Save the config on the context so that callbacks which
1940 * only get SSL_CTX* e.g. session persistence, can get it
1942 SSL_CTX_set_app_data(ctx, conf);
1945 * Identify the type of certificates that needs to be loaded
1947 if (conf->file_type) {
1948 type = SSL_FILETYPE_PEM;
1950 type = SSL_FILETYPE_ASN1;
1954 * Set the password to load private key
1956 if (conf->private_key_password) {
1959 * We don't want to put the private key password in eap.conf, so check
1960 * for our special string which indicates we should get the password
1963 char const* special_string = "Apple:UseCertAdmin";
1964 if (strncmp(conf->private_key_password,
1966 strlen(special_string)) == 0)
1969 long const max_password_len = 128;
1970 snprintf(cmd, sizeof(cmd) - 1,
1971 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
1972 conf->private_key_file);
1974 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
1976 FILE* cmd_pipe = popen(cmd, "r");
1978 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
1979 ERROR("Error reading private_key_file %s", conf->private_key_file);
1983 talloc_free(conf->private_key_password);
1984 conf->private_key_password = talloc_array(conf, char, max_password_len);
1985 if (!conf->private_key_password) {
1986 ERROR("TLS: Can't allocate space for private_key_password");
1987 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
1992 fgets(conf->private_key_password, max_password_len, cmd_pipe);
1995 /* Get rid of newline at end of password. */
1996 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
1997 DEBUG2("tls: Password from command = \"%s\"", conf->private_key_password);
2000 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
2001 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2004 #ifdef PSK_MAX_IDENTITY_LEN
2005 if ((conf->psk_identity && !conf->psk_password) ||
2006 (!conf->psk_identity && conf->psk_password) ||
2007 (conf->psk_identity && !*conf->psk_identity) ||
2008 (conf->psk_password && !*conf->psk_password)) {
2009 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2013 if (conf->psk_identity) {
2014 size_t psk_len, hex_len;
2015 char buffer[PSK_MAX_PSK_LEN];
2017 if (conf->certificate_file ||
2018 conf->private_key_password || conf->private_key_file ||
2019 conf->ca_file || conf->ca_path) {
2020 ERROR("When PSKs are used, No certificate configuration is permitted");
2025 SSL_CTX_set_psk_client_callback(ctx,
2026 psk_client_callback);
2028 SSL_CTX_set_psk_server_callback(ctx,
2029 psk_server_callback);
2032 psk_len = strlen(conf->psk_password);
2033 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2034 ERROR("psk_hexphrase is too long (max %d)",
2039 hex_len = fr_hex2bin((uint8_t *) buffer, conf->psk_password, psk_len);
2040 if (psk_len != (2 * hex_len)) {
2041 ERROR("psk_hexphrase is not all hex");
2048 (void) client; /* -Wunused */
2052 * Load our keys and certificates
2054 * If certificates are of type PEM then we can make use
2055 * of cert chain authentication using openssl api call
2056 * SSL_CTX_use_certificate_chain_file. Please see how
2057 * the cert chain needs to be given in PEM from
2060 if (!conf->certificate_file) goto load_ca;
2062 if (type == SSL_FILETYPE_PEM) {
2063 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2064 ERROR("Error reading certificate file %s:%s",
2065 conf->certificate_file,
2066 ERR_error_string(ERR_get_error(), NULL));
2070 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2071 ERROR("Error reading certificate file %s:%s",
2072 conf->certificate_file,
2073 ERR_error_string(ERR_get_error(), NULL));
2077 /* Load the CAs we trust */
2079 if (conf->ca_file || conf->ca_path) {
2080 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2081 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2082 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2086 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2088 if (conf->private_key_file) {
2089 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2090 ERROR("Failed reading private key file %s:%s",
2091 conf->private_key_file,
2092 ERR_error_string(ERR_get_error(), NULL));
2097 * Check if the loaded private key is the right one
2099 if (!SSL_CTX_check_private_key(ctx)) {
2100 ERROR("Private key does not match the certificate public key");
2105 #ifdef PSK_MAX_IDENTITY_LEN
2112 ctx_options |= SSL_OP_NO_SSLv2;
2113 ctx_options |= SSL_OP_NO_SSLv3;
2114 #ifdef SSL_OP_NO_TICKET
2115 ctx_options |= SSL_OP_NO_TICKET ;
2119 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2120 * small subgroup attacks and forward secrecy. Always
2123 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2124 * time needed during negotiation, but it is not very
2127 ctx_options |= SSL_OP_SINGLE_DH_USE;
2130 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2131 * in Windows Vista client.
2132 * http://www.openssl.org/~bodo/tls-cbc.txt
2133 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2135 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2137 SSL_CTX_set_options(ctx, ctx_options);
2140 * TODO: Set the RSA & DH
2141 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2142 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2146 * set the message callback to identify the type of
2147 * message. For every new session, there can be a
2148 * different callback argument.
2150 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2154 * Set eliptical curve crypto configuration.
2156 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2157 #ifndef OPENSSL_NO_ECDH
2158 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2164 /* Set Info callback */
2165 SSL_CTX_set_info_callback(ctx, cbtls_info);
2168 * Callbacks, etc. for session resumption.
2170 if (conf->session_cache_enable) {
2171 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2172 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2173 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2175 SSL_CTX_set_quiet_shutdown(ctx, 1);
2176 if (FR_TLS_EX_INDEX_VPS < 0)
2177 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2181 * Check the certificates for revocation.
2183 #ifdef X509_V_FLAG_CRL_CHECK
2184 if (conf->check_crl) {
2185 certstore = SSL_CTX_get_cert_store(ctx);
2186 if (certstore == NULL) {
2187 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2188 ERROR("tls: Error reading Certificate Store");
2191 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2197 * Always verify the peer certificate
2199 verify_mode |= SSL_VERIFY_PEER;
2200 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2201 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2202 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2204 if (conf->verify_depth) {
2205 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2208 /* Load randomness */
2209 if (conf->random_file) {
2210 if (!(RAND_load_file(conf->random_file, 1024*1024))) {
2211 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2212 ERROR("tls: Error loading randomness");
2218 * Set the cipher list if we were told to
2220 if (conf->cipher_list) {
2221 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2222 ERROR("tls: Error setting cipher list");
2228 * Setup session caching
2230 if (conf->session_cache_enable) {
2232 * Create a unique context Id per EAP-TLS configuration.
2234 if (conf->session_id_name) {
2235 snprintf(conf->session_context_id,
2236 sizeof(conf->session_context_id),
2238 conf->session_id_name);
2240 snprintf(conf->session_context_id,
2241 sizeof(conf->session_context_id),
2246 * Cache it, and DON'T auto-clear it.
2248 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2250 SSL_CTX_set_session_id_context(ctx,
2251 (unsigned char *) conf->session_context_id,
2252 (unsigned int) strlen(conf->session_context_id));
2255 * Our timeout is in hours, this is in seconds.
2257 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2260 * Set the maximum number of entries in the
2263 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2266 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2274 * Free TLS client/server config
2275 * Should not be called outside this code, as a callback is
2276 * added to automatically free the data when the CONF_SECTION
2279 static void tls_server_conf_free(fr_tls_server_conf_t *conf)
2283 if (conf->ctx) SSL_CTX_free(conf->ctx);
2285 #ifdef HAVE_OPENSSL_OCSP_H
2286 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2287 conf->ocsp_store = NULL;
2291 memset(conf, 0, sizeof(*conf));
2297 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2299 fr_tls_server_conf_t *conf;
2302 * If cs has already been parsed there should be a cached copy
2303 * of conf already stored, so just return that.
2305 conf = cf_data_find(cs, "tls-conf");
2307 DEBUG("Using cached TLS configuration from previous invocation");
2311 conf = talloc_zero(cs, fr_tls_server_conf_t);
2313 ERROR("Out of memory");
2317 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2319 tls_server_conf_free(conf);
2324 * Save people from their own stupidity.
2326 if (conf->fragment_size < 100) conf->fragment_size = 100;
2328 if (!conf->private_key_file) {
2329 ERROR("TLS Server requires a private key file");
2333 if (!conf->certificate_file) {
2334 ERROR("TLS Server requires a certificate file");
2341 conf->ctx = init_tls_ctx(conf, 0);
2342 if (conf->ctx == NULL) {
2346 #ifdef HAVE_OPENSSL_OCSP_H
2348 * Initialize OCSP Revocation Store
2350 if (conf->ocsp_enable) {
2351 conf->ocsp_store = init_revocation_store(conf);
2352 if (conf->ocsp_store == NULL) goto error;
2354 #endif /*HAVE_OPENSSL_OCSP_H*/
2356 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2360 if (generate_eph_rsa_key(conf->ctx) < 0) {
2364 if (conf->verify_tmp_dir) {
2365 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2366 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
2371 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2372 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2377 * Cache conf in cs in case we're asked to parse this again.
2379 cf_data_add(cs, "tls-conf", conf, (void *)(void *) tls_server_conf_free);
2384 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2386 fr_tls_server_conf_t *conf;
2388 conf = cf_data_find(cs, "tls-conf");
2390 DEBUG("Using cached TLS configuration from previous invocation");
2394 conf = talloc_zero(cs, fr_tls_server_conf_t);
2396 ERROR("Out of memory");
2400 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2402 tls_server_conf_free(conf);
2407 * Save people from their own stupidity.
2409 if (conf->fragment_size < 100) conf->fragment_size = 100;
2414 conf->ctx = init_tls_ctx(conf, 1);
2415 if (conf->ctx == NULL) {
2419 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2423 if (generate_eph_rsa_key(conf->ctx) < 0) {
2427 cf_data_add(cs, "tls-conf", conf, (void *)(void *) tls_server_conf_free);
2432 int tls_success(tls_session_t *ssn, REQUEST *request)
2434 VALUE_PAIR *vp, *vps = NULL;
2435 fr_tls_server_conf_t *conf;
2437 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2438 rad_assert(conf != NULL);
2441 * If there's no session resumption, delete the entry
2442 * from the cache. This means either it's disabled
2443 * globally for this SSL context, OR we were told to
2444 * disable it for this user.
2446 * This also means you can't turn it on just for one
2449 if ((!ssn->allow_session_resumption) ||
2450 (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2451 (vp->vp_integer == 0))) {
2452 SSL_CTX_remove_session(ssn->ctx,
2454 ssn->allow_session_resumption = 0;
2457 * If we're in a resumed session and it's
2460 if (SSL_session_reused(ssn->ssl)) {
2461 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed.");
2466 * Else resumption IS allowed, so we store the
2467 * user data in the cache.
2469 } else if (!SSL_session_reused(ssn->ssl)) {
2472 char buffer[2 * MAX_SESSION_SIZE + 1];
2474 size = ssn->ssl->session->session_id_length;
2475 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2477 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2479 vp = paircopy2(NULL, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2480 if (vp) pairadd(&vps, vp);
2482 vp = paircopy2(NULL, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2483 if (vp) pairadd(&vps, vp);
2485 vp = paircopy2(NULL, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2486 if (vp) pairadd(&vps, vp);
2488 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2491 * Hmm... the certs should probably be session data.
2495 * @todo: some go into reply, others into
2498 pairadd(&vps, paircopy(NULL, *certs));
2502 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2503 SSL_SESSION_set_ex_data(ssn->ssl->session,
2504 FR_TLS_EX_INDEX_VPS, vps);
2505 if (conf->session_cache_path) {
2506 /* write the VPs to the cache file */
2507 char filename[256], buf[1024];
2510 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2511 conf->session_cache_path, FR_DIR_SEP, buffer
2513 vp_file = fopen(filename, "w");
2514 if (vp_file == NULL) {
2515 RDEBUG2("Could not write session VPs to persistent cache: %s", strerror(errno));
2518 /* generate a dummy user-style entry which is easy to read back */
2519 fprintf(vp_file, "# SSL cached session\n");
2520 fprintf(vp_file, "%s\n", buffer);
2521 for (vp = paircursor(&cursor, &vps);
2523 vp = pairnext(&cursor)) {
2524 vp_prints(buf, sizeof(buf), vp);
2525 fprintf(vp_file, "\t%s%s\n", buf, ",");
2531 RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2532 SSL_CTX_remove_session(ssn->ctx,
2537 * Else the session WAS allowed. Copy the cached
2542 char buffer[2 * MAX_SESSION_SIZE + 1];
2544 size = ssn->ssl->session->session_id_length;
2545 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2547 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2549 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2550 FR_TLS_EX_INDEX_VPS);
2552 RWDEBUG("No information in cached session %s", buffer);
2558 RDEBUG("Adding cached attributes for session %s:", buffer);
2559 debug_pair_list(vps);
2561 for (vp = paircursor(&cursor, &vps);
2563 vp = pairnext(&cursor)) {
2565 * TLS-* attrs get added back to
2568 if ((vp->da->vendor == 0) &&
2569 (vp->da->attr >= 1910) &&
2570 (vp->da->attr < 1929)) {
2571 pairadd(&request->packet->vps,
2572 paircopyvp(request->packet, vp));
2574 pairadd(&request->reply->vps,
2575 paircopyvp(request->packet, vp));
2579 if (conf->session_cache_path) {
2580 /* "touch" the cached session/vp file */
2583 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2584 conf->session_cache_path, FR_DIR_SEP, buffer
2586 utime(filename, NULL);
2587 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2588 conf->session_cache_path, FR_DIR_SEP, buffer
2590 utime(filename, NULL);
2594 * Mark the request as resumed.
2596 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2604 void tls_fail(tls_session_t *ssn)
2607 * Force the session to NOT be cached.
2609 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2612 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2619 * Decrypt the complete record.
2621 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2622 ssn->dirty_in.used);
2623 if (err != (int) ssn->dirty_in.used) {
2624 record_init(&ssn->dirty_in);
2625 RDEBUG("Failed writing %d to SSL BIO: %d",
2626 ssn->dirty_in.used, err);
2631 * Clear the dirty buffer now that we are done with it
2632 * and init the clean_out buffer to store decrypted data
2634 record_init(&ssn->dirty_in);
2635 record_init(&ssn->clean_out);
2638 * Read (and decrypt) the tunneled data from the
2639 * SSL session, and put it into the decrypted
2642 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2643 sizeof(ssn->clean_out.data));
2648 RDEBUG("SSL_read Error");
2650 code = SSL_get_error(ssn->ssl, err);
2652 case SSL_ERROR_WANT_READ:
2653 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2654 return FR_TLS_MORE_FRAGMENTS;
2656 case SSL_ERROR_WANT_WRITE:
2657 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2661 DEBUG("Error in fragmentation logic: ?");
2664 * FIXME: Call int_ssl_check?
2672 RWDEBUG("No data inside of the tunnel.");
2676 * Passed all checks, successfully decrypted data
2678 ssn->clean_out.used = err;
2685 * Acknowledge received is for one of the following messages sent earlier
2686 * 1. Handshake completed Message, so now send, EAP-Success
2687 * 2. Alert Message, now send, EAP-Failure
2688 * 3. Fragment Message, now send, next Fragment
2690 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2692 RDEBUG2("Received TLS ACK");
2695 RERROR("FAIL: Unexpected ACK received. Could not obtain session information.");
2696 return FR_TLS_INVALID;
2698 if (ssn->info.initialized == 0) {
2699 RDEBUG("No SSL info available. Waiting for more SSL data.");
2700 return FR_TLS_REQUEST;
2702 if ((ssn->info.content_type == handshake) &&
2703 (ssn->info.origin == 0)) {
2704 RERROR("FAIL: ACK without earlier message.");
2705 return FR_TLS_INVALID;
2708 switch (ssn->info.content_type) {
2710 RDEBUG2("ACK alert");
2714 if ((ssn->info.handshake_type == finished) &&
2715 (ssn->dirty_out.used == 0)) {
2716 RDEBUG2("ACK handshake is finished");
2719 * From now on all the content is
2720 * application data set it here as nobody else
2723 ssn->info.content_type = application_data;
2724 return FR_TLS_SUCCESS;
2725 } /* else more data to send */
2727 RDEBUG2("ACK handshake fragment handler");
2728 /* Fragmentation handler, send next fragment */
2729 return FR_TLS_REQUEST;
2731 case application_data:
2732 RDEBUG2("ACK handshake fragment handler in application data");
2733 return FR_TLS_REQUEST;
2736 * For the rest of the conditions, switch over
2737 * to the default section below.
2740 RDEBUG2("ACK default");
2741 RERROR("Invalid ACK received: %d",
2742 ssn->info.content_type);
2743 return FR_TLS_INVALID;
2747 #endif /* WITH_TLS */