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
46 #ifdef HAVE_OPENSSL_RAND_H
47 #include <openssl/rand.h>
50 #ifdef HAVE_OPENSSL_OCSP_H
51 #include <openssl/ocsp.h>
54 #ifdef ENABLE_OPENSSL_VERSION_CHECK
55 typedef struct libssl_defect {
64 /* Record critical defects in libssl here (newest first)*/
65 static libssl_defect_t libssl_defects[] =
68 .low = 0x010001000, /* 1.0.1 */
69 .high = 0x01000106f, /* 1.0.1f */
70 .id = "CVE-2014-0160",
72 .comment = "For more information see http://heartbleed.com"
77 /* index we use to store cached session VPs
78 * needs to be dynamic so we can supply a "free" function
80 static int fr_tls_ex_index_vps = -1;
81 int fr_tls_ex_index_certs = -1;
84 static void session_close(tls_session_t *ssn);
85 static void session_init(tls_session_t *ssn);
88 static void record_init(record_t *buf);
89 static void record_close(record_t *buf);
90 static unsigned int record_plus(record_t *buf, void const *ptr,
92 static unsigned int record_minus(record_t *buf, void *ptr,
95 #ifdef PSK_MAX_IDENTITY_LEN
96 static bool identity_is_safe(const char *identity)
100 if (!identity) return true;
102 while ((c = *(identity++)) != '\0') {
103 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
104 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
116 * When a client uses TLS-PSK to talk to a server, this callback
117 * is used by the server to determine the PSK to use.
119 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
121 unsigned int max_psk_len)
123 unsigned int psk_len = 0;
124 fr_tls_server_conf_t *conf;
127 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
128 FR_TLS_EX_INDEX_CONF);
131 request = (REQUEST *)SSL_get_ex_data(ssl,
132 FR_TLS_EX_INDEX_REQUEST);
133 if (request && conf->psk_query) {
136 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
139 * The passed identity is weird. Deny it.
141 if (!identity_is_safe(identity)) {
142 RWDEBUG("Invalid characters in PSK identity %s", identity);
146 vp = pairmake_packet("TLS-PSK-Identity", identity, T_OP_SET);
149 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
152 RWDEBUG("PSK expansion returned an empty string.");
157 * The returned key is truncated at MORE than
158 * OpenSSL can handle. That way we can detect
159 * the truncation, and complain about it.
161 if (hex_len > (2 * max_psk_len)) {
162 RWDEBUG("Returned PSK is too long (%u > %u)",
163 (unsigned int) hex_len, 2 * max_psk_len);
168 * Leave the TLS-PSK-Identity in the request, and
169 * convert the expansion from printable string
172 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
175 if (!conf->psk_identity) {
176 DEBUG("No static PSK identity set. Rejecting the user");
181 * No REQUEST, or no dynamic query. Just look for a
184 if (strcmp(identity, conf->psk_identity) != 0) {
185 ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
190 psk_len = strlen(conf->psk_password);
191 if (psk_len > (2 * max_psk_len)) return 0;
193 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
196 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
197 char *identity, unsigned int max_identity_len,
198 unsigned char *psk, unsigned int max_psk_len)
200 unsigned int psk_len;
201 fr_tls_server_conf_t *conf;
203 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
204 FR_TLS_EX_INDEX_CONF);
207 psk_len = strlen(conf->psk_password);
208 if (psk_len > (2 * max_psk_len)) return 0;
210 strlcpy(identity, conf->psk_identity, max_identity_len);
212 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
217 static int _tls_session_free(tls_session_t *ssn)
220 * Free any opaque TTLS or PEAP data.
222 if ((ssn->opaque) && (ssn->free_opaque)) {
223 ssn->free_opaque(ssn->opaque);
232 tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
235 tls_session_t *ssn = NULL;
238 ssn = talloc_zero(ctx, tls_session_t);
239 if (!ssn) return NULL;
241 talloc_set_destructor(ssn, _tls_session_free);
243 ssn->ctx = conf->ctx;
245 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
247 ssn->ssl = SSL_new(ssn->ctx);
253 request = request_alloc(ssn);
254 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
257 * Add the message callback to identify what type of
258 * message/handshake is passed
260 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
261 SSL_set_msg_callback_arg(ssn->ssl, ssn);
262 SSL_set_info_callback(ssn->ssl, cbtls_info);
265 * Always verify the peer certificate.
267 DEBUG2("Requiring Server certificate");
268 verify_mode = SSL_VERIFY_PEER;
269 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
270 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
272 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
273 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
274 SSL_set_fd(ssn->ssl, fd);
275 if (SSL_connect(ssn->ssl) <= 0) {
277 while ((err = ERR_get_error())) {
278 ERROR("tls: %s", ERR_error_string(err, NULL));
285 ssn->offset = conf->fragment_size;
290 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
292 tls_session_t *state = NULL;
297 rad_assert(request != NULL);
300 * Manually flush the sessions every so often. If HALF
301 * of the session lifetime has passed since we last
302 * flushed, then flush it again.
304 * FIXME: Also do it every N sessions?
306 if (conf->session_cache_enable &&
307 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
308 RDEBUG2("Flushing SSL sessions (of #%ld)",
309 SSL_CTX_sess_number(conf->ctx));
311 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
312 conf->session_last_flushed = request->timestamp;
315 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
316 ERROR("SSL: Error creating new SSL: %s",
317 ERR_error_string(ERR_get_error(), NULL));
321 /* We use the SSL's "app_data" to indicate a call-back */
322 SSL_set_app_data(new_tls, NULL);
324 if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
325 ERROR("SSL: Error allocating memory for SSL state");
329 talloc_set_destructor(state, _tls_session_free);
331 state->ctx = conf->ctx;
332 state->ssl = new_tls;
335 * Initialize callbacks
337 state->record_init = record_init;
338 state->record_close = record_close;
339 state->record_plus = record_plus;
340 state->record_minus = record_minus;
343 * Create & hook the BIOs to handle the dirty side of the
344 * SSL. This is *very important* as we want to handle
345 * the transmission part. Now the only IO interface
346 * that SSL is aware of, is our defined BIO buffers.
348 * This means that all SSL IO is done to/from memory,
349 * and we can update those BIOs from the packets we've
352 state->into_ssl = BIO_new(BIO_s_mem());
353 state->from_ssl = BIO_new(BIO_s_mem());
354 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
357 * Add the message callback to identify what type of
358 * message/handshake is passed
360 SSL_set_msg_callback(new_tls, cbtls_msg);
361 SSL_set_msg_callback_arg(new_tls, state);
362 SSL_set_info_callback(new_tls, cbtls_info);
365 * In Server mode we only accept.
367 SSL_set_accept_state(state->ssl);
370 * Verify the peer certificate, if asked.
373 RDEBUG2("Requiring client certificate");
374 verify_mode = SSL_VERIFY_PEER;
375 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
376 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
378 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
380 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
381 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
382 state->length_flag = conf->include_length;
385 * We use default fragment size, unless the Framed-MTU
386 * tells us it's too big. Note that we do NOT account
387 * for the EAP-TLS headers if conf->fragment_size is
388 * large, because that config item looks to be confusing.
390 * i.e. it should REALLY be called MTU, and the code here
391 * should figure out what that means for TLS fragment size.
392 * asking the administrator to know the internal details
393 * of EAP-TLS in order to calculate fragment sizes is
396 state->offset = conf->fragment_size;
397 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
398 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
399 state->offset = vp->vp_integer;
402 if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
410 * Print out some text describing the error.
412 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
417 if ((l = ERR_get_error()) != 0) {
418 char const *p = ERR_error_string(l, NULL);
420 if (request && p) REDEBUG("SSL says: %s", p);
422 e = SSL_get_error(s, ret);
426 * These seem to be harmless and already "dealt
427 * with" by our non-blocking environment. NB:
428 * "ZERO_RETURN" is the clean "error"
429 * indicating a successfully closed SSL
430 * tunnel. We let this happen because our IO
431 * loop should not appear to have broken on
432 * this condition - and outside the IO loop, the
433 * "shutdown" state is checked.
435 * Don't print anything if we ignore the error.
438 case SSL_ERROR_WANT_READ:
439 case SSL_ERROR_WANT_WRITE:
440 case SSL_ERROR_WANT_X509_LOOKUP:
441 case SSL_ERROR_ZERO_RETURN:
445 * These seem to be indications of a genuine
446 * error that should result in the SSL tunnel
447 * being regarded as "dead".
449 case SSL_ERROR_SYSCALL:
450 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
455 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
461 * For any other errors that (a) exist, and (b)
462 * crop up - we need to interpret what to do with
463 * them - so "politely inform" the caller that
464 * the code needs updating here.
466 ERROR("SSL: FATAL SSL error ..... %d\n", e);
474 * We are the server, we always get the dirty data
475 * (Handshake data is also considered as dirty data)
476 * During handshake, since SSL API handles itself,
477 * After clean-up, dirty_out will be filled with
478 * the data required for handshaking. So we check
479 * if dirty_out is empty then we simply send it back.
480 * As of now, if handshake is successful, then we keep going,
483 * Fill the Bio with the dirty data to clean it
484 * Get the cleaned data from SSL, if it is not Handshake data
486 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
490 if (ssn->invalid_hb_used) return 0;
492 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
493 if (err != (int) ssn->dirty_in.used) {
494 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
496 record_init(&ssn->dirty_in);
499 record_init(&ssn->dirty_in);
501 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
502 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
504 ssn->clean_out.used += err;
508 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
512 /* Some Extra STATE information for easy debugging */
513 if (SSL_is_init_finished(ssn->ssl)) {
514 DEBUG2("SSL Connection Established\n");
516 if (SSL_in_init(ssn->ssl)) {
517 DEBUG2("In SSL Handshake Phase\n");
519 if (SSL_in_before(ssn->ssl)) {
520 DEBUG2("Before SSL Handshake Phase\n");
522 if (SSL_in_accept_init(ssn->ssl)) {
523 DEBUG2("In SSL Accept mode \n");
525 if (SSL_in_connect_init(ssn->ssl)) {
526 DEBUG2("In SSL Connect mode \n");
529 err = BIO_ctrl_pending(ssn->from_ssl);
531 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
532 sizeof(ssn->dirty_out.data));
534 ssn->dirty_out.used = err;
536 } else if (BIO_should_retry(ssn->from_ssl)) {
537 record_init(&ssn->dirty_in);
538 DEBUG2(" tls: Asking for more data in tunnel");
542 int_ssl_check(request, ssn->ssl, err, "BIO_read");
543 record_init(&ssn->dirty_in);
547 DEBUG2("SSL Application Data");
548 /* Its clean application data, do whatever we want */
549 record_init(&ssn->clean_out);
552 /* We are done with dirty_in, reinitialize it */
553 record_init(&ssn->dirty_in);
558 * Take cleartext user data, and encrypt it into the output buffer,
559 * to send to the client at the other end of the SSL connection.
561 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
566 * If there's un-encrypted data in 'clean_in', then write
567 * that data to the SSL session, and then call the BIO function
568 * to get that encrypted data from the SSL session, into
569 * a buffer which we can then package into an EAP packet.
571 * Based on Server's logic this clean_in is expected to
572 * contain the data to send to the client.
574 if (ssn->clean_in.used > 0) {
577 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
578 record_minus(&ssn->clean_in, NULL, written);
580 /* Get the dirty data from Bio to send it */
581 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
582 sizeof(ssn->dirty_out.data));
584 ssn->dirty_out.used = err;
586 int_ssl_check(request, ssn->ssl, err, "handshake_send");
593 static void session_init(tls_session_t *ssn)
596 ssn->into_ssl = ssn->from_ssl = NULL;
597 record_init(&ssn->clean_in);
598 record_init(&ssn->clean_out);
599 record_init(&ssn->dirty_in);
600 record_init(&ssn->dirty_out);
602 memset(&ssn->info, 0, sizeof(ssn->info));
606 ssn->tls_msg_len = 0;
607 ssn->length_flag = 0;
609 ssn->free_opaque = NULL;
612 static void session_close(tls_session_t *ssn)
614 SSL_set_quiet_shutdown(ssn->ssl, 1);
615 SSL_shutdown(ssn->ssl);
622 record_close(&ssn->clean_in);
623 record_close(&ssn->clean_out);
624 record_close(&ssn->dirty_in);
625 record_close(&ssn->dirty_out);
629 static void record_init(record_t *rec)
634 static void record_close(record_t *rec)
641 * Copy data to the intermediate buffer, before we send
644 static unsigned int record_plus(record_t *rec, void const *ptr,
647 unsigned int added = MAX_RECORD_SIZE - rec->used;
653 memcpy(rec->data + rec->used, ptr, added);
659 * Take data from the buffer, and give it to the caller.
661 static unsigned int record_minus(record_t *rec, void *ptr,
664 unsigned int taken = rec->used;
671 memcpy(ptr, rec->data, taken);
675 * This is pretty bad...
678 memmove(rec->data, rec->data + taken, rec->used);
682 void tls_session_information(tls_session_t *tls_session)
684 char const *str_write_p, *str_version, *str_content_type = "";
685 char const *str_details1 = "", *str_details2= "";
689 * Don't print this out in the normal course of
692 if (debug_flag == 0) {
696 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
698 switch (tls_session->info.version) {
700 str_version = "SSL 2.0";
703 str_version = "SSL 3.0 ";
706 str_version = "TLS 1.0 ";
709 str_version = "Unknown TLS version";
713 if (tls_session->info.version == SSL3_VERSION ||
714 tls_session->info.version == TLS1_VERSION) {
715 switch (tls_session->info.content_type) {
716 case SSL3_RT_CHANGE_CIPHER_SPEC:
717 str_content_type = "ChangeCipherSpec";
721 str_content_type = "Alert";
724 case SSL3_RT_HANDSHAKE:
725 str_content_type = "Handshake";
728 case SSL3_RT_APPLICATION_DATA:
729 str_content_type = "ApplicationData";
733 str_content_type = "UnknownContentType";
737 if (tls_session->info.content_type == SSL3_RT_ALERT) {
738 str_details1 = ", ???";
740 if (tls_session->info.record_len == 2) {
742 switch (tls_session->info.alert_level) {
743 case SSL3_AL_WARNING:
744 str_details1 = ", warning";
747 str_details1 = ", fatal";
751 str_details2 = " ???";
752 switch (tls_session->info.alert_description) {
753 case SSL3_AD_CLOSE_NOTIFY:
754 str_details2 = " close_notify";
757 case SSL3_AD_UNEXPECTED_MESSAGE:
758 str_details2 = " unexpected_message";
761 case SSL3_AD_BAD_RECORD_MAC:
762 str_details2 = " bad_record_mac";
765 case TLS1_AD_DECRYPTION_FAILED:
766 str_details2 = " decryption_failed";
769 case TLS1_AD_RECORD_OVERFLOW:
770 str_details2 = " record_overflow";
773 case SSL3_AD_DECOMPRESSION_FAILURE:
774 str_details2 = " decompression_failure";
777 case SSL3_AD_HANDSHAKE_FAILURE:
778 str_details2 = " handshake_failure";
781 case SSL3_AD_BAD_CERTIFICATE:
782 str_details2 = " bad_certificate";
785 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
786 str_details2 = " unsupported_certificate";
789 case SSL3_AD_CERTIFICATE_REVOKED:
790 str_details2 = " certificate_revoked";
793 case SSL3_AD_CERTIFICATE_EXPIRED:
794 str_details2 = " certificate_expired";
797 case SSL3_AD_CERTIFICATE_UNKNOWN:
798 str_details2 = " certificate_unknown";
801 case SSL3_AD_ILLEGAL_PARAMETER:
802 str_details2 = " illegal_parameter";
805 case TLS1_AD_UNKNOWN_CA:
806 str_details2 = " unknown_ca";
809 case TLS1_AD_ACCESS_DENIED:
810 str_details2 = " access_denied";
813 case TLS1_AD_DECODE_ERROR:
814 str_details2 = " decode_error";
817 case TLS1_AD_DECRYPT_ERROR:
818 str_details2 = " decrypt_error";
821 case TLS1_AD_EXPORT_RESTRICTION:
822 str_details2 = " export_restriction";
825 case TLS1_AD_PROTOCOL_VERSION:
826 str_details2 = " protocol_version";
829 case TLS1_AD_INSUFFICIENT_SECURITY:
830 str_details2 = " insufficient_security";
833 case TLS1_AD_INTERNAL_ERROR:
834 str_details2 = " internal_error";
837 case TLS1_AD_USER_CANCELLED:
838 str_details2 = " user_canceled";
841 case TLS1_AD_NO_RENEGOTIATION:
842 str_details2 = " no_renegotiation";
848 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
849 str_details1 = "???";
851 if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
852 case SSL3_MT_HELLO_REQUEST:
853 str_details1 = ", HelloRequest";
856 case SSL3_MT_CLIENT_HELLO:
857 str_details1 = ", ClientHello";
860 case SSL3_MT_SERVER_HELLO:
861 str_details1 = ", ServerHello";
864 case SSL3_MT_CERTIFICATE:
865 str_details1 = ", Certificate";
868 case SSL3_MT_SERVER_KEY_EXCHANGE:
869 str_details1 = ", ServerKeyExchange";
872 case SSL3_MT_CERTIFICATE_REQUEST:
873 str_details1 = ", CertificateRequest";
876 case SSL3_MT_SERVER_DONE:
877 str_details1 = ", ServerHelloDone";
880 case SSL3_MT_CERTIFICATE_VERIFY:
881 str_details1 = ", CertificateVerify";
884 case SSL3_MT_CLIENT_KEY_EXCHANGE:
885 str_details1 = ", ClientKeyExchange";
888 case SSL3_MT_FINISHED:
889 str_details1 = ", Finished";
895 snprintf(tls_session->info.info_description,
896 sizeof(tls_session->info.info_description),
897 "%s %s%s [length %04lx]%s%s\n",
898 str_write_p, str_version, str_content_type,
899 (unsigned long)tls_session->info.record_len,
900 str_details1, str_details2);
902 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
904 RDEBUG2("%s", tls_session->info.info_description);
906 DEBUG2("%s", tls_session->info.info_description);
910 static CONF_PARSER cache_config[] = {
911 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
912 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
913 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
914 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
915 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
916 { NULL, -1, 0, NULL, NULL } /* end the list */
919 static CONF_PARSER verify_config[] = {
920 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
921 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
922 { NULL, -1, 0, NULL, NULL } /* end the list */
925 #ifdef HAVE_OPENSSL_OCSP_H
926 static CONF_PARSER ocsp_config[] = {
927 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
928 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
929 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
930 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
931 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
932 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
933 { NULL, -1, 0, NULL, NULL } /* end the list */
937 static CONF_PARSER tls_server_config[] = {
938 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
939 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
940 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
941 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
942 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
943 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
944 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
945 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
946 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
947 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
948 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
949 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
950 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
951 #ifdef PSK_MAX_IDENTITY_LEN
952 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
953 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
954 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
956 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
957 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
958 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
959 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
960 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
961 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
962 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
963 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
964 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
965 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
967 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
968 #ifndef OPENSSL_NO_ECDH
969 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
973 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
974 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
976 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
978 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
980 #ifdef HAVE_OPENSSL_OCSP_H
981 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
984 { NULL, -1, 0, NULL, NULL } /* end the list */
988 static CONF_PARSER tls_client_config[] = {
989 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
990 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
991 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
992 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
993 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
994 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
995 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
996 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
997 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
998 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
999 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1000 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1001 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1002 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1003 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1004 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1005 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1006 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1007 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1009 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1010 #ifndef OPENSSL_NO_ECDH
1011 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1015 #ifdef SSL_OP_NO_TLSv1_1
1016 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1018 #ifdef SSL_OP_NO_TLSv1_2
1019 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1022 { NULL, -1, 0, NULL, NULL } /* end the list */
1027 * TODO: Check for the type of key exchange * like conf->dh_key
1029 static int load_dh_params(SSL_CTX *ctx, char *file)
1034 if (!file) return 0;
1036 if ((bio = BIO_new_file(file, "r")) == NULL) {
1037 ERROR("tls: Unable to open DH file - %s", file);
1041 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1044 WARN("tls: Unable to set DH parameters. DH cipher suites may not work!");
1045 WARN("Fix this by running the OpenSSL command listed in eap.conf");
1049 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1050 ERROR("tls: Unable to set DH parameters");
1061 * Print debugging messages, and free data.
1063 * FIXME: Write sessions to some long-term storage, so that
1064 * session resumption can still occur after the server
1067 #define MAX_SESSION_SIZE (256)
1069 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1072 char buffer[2 * MAX_SESSION_SIZE + 1];
1073 fr_tls_server_conf_t *conf;
1075 size = sess->session_id_length;
1076 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1078 fr_bin2hex(buffer, sess->session_id, size);
1080 DEBUG2(" SSL: Removing session %s from the cache", buffer);
1081 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1082 if (conf && conf->session_cache_path) {
1086 /* remove session and any cached VPs */
1087 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1088 conf->session_cache_path, FR_DIR_SEP, buffer);
1089 rv = unlink(filename);
1091 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
1093 /* VPs might be absent; might not have been written to disk yet */
1094 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1095 conf->session_cache_path, FR_DIR_SEP, buffer);
1102 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1105 char buffer[2 * MAX_SESSION_SIZE + 1];
1106 fr_tls_server_conf_t *conf;
1107 unsigned char *sess_blob = NULL;
1109 size = sess->session_id_length;
1110 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1112 fr_bin2hex(buffer, sess->session_id, size);
1114 DEBUG2(" SSL: adding session %s to cache", buffer);
1116 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1117 if (conf && conf->session_cache_path) {
1118 int fd, rv, todo, blob_len;
1122 /* find out what length data we need */
1123 blob_len = i2d_SSL_SESSION(sess, NULL);
1125 /* something went wrong */
1126 DEBUG2(" SSL: could not find buffer length to persist session");
1131 /* Do not convert to TALLOC - Thread safety */
1132 /* alloc and convert to ASN.1 */
1133 sess_blob = malloc(blob_len);
1135 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1138 /* openssl mutates &p */
1140 rv = i2d_SSL_SESSION(sess, &p);
1141 if (rv != blob_len) {
1142 DEBUG2(" SSL: could not persist session");
1146 /* open output file */
1147 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1148 conf->session_cache_path, FR_DIR_SEP, buffer);
1149 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1151 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1158 rv = write(fd, p, todo);
1160 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1168 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1177 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1178 unsigned char *data, int len,
1182 char buffer[2 * MAX_SESSION_SIZE + 1];
1183 fr_tls_server_conf_t *conf;
1184 TALLOC_CTX *talloc_ctx;
1186 SSL_SESSION *sess = NULL;
1187 unsigned char *sess_data = NULL;
1188 PAIR_LIST *pairlist = NULL;
1191 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1193 fr_bin2hex(buffer, data, size);
1195 DEBUG2(" SSL: Client requested cached session %s", buffer);
1197 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1198 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1199 if (conf && conf->session_cache_path) {
1206 /* read in the cached VPs from the .vps file */
1207 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1208 conf->session_cache_path, FR_DIR_SEP, buffer);
1209 rv = pairlist_read(NULL, filename, &pairlist, 1);
1211 /* not safe to un-persist a session w/o VPs */
1212 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1216 /* load the actual SSL session */
1217 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1218 conf->session_cache_path, FR_DIR_SEP, buffer);
1219 fd = open(filename, O_RDONLY);
1221 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1225 rv = fstat(fd, &st);
1227 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1232 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1234 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1242 rv = read(fd, p, todo);
1244 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1253 /* openssl mutates &p */
1255 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1258 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1262 /* cache the VPs into the session */
1263 vp = paircopy(talloc_ctx, pairlist->reply);
1264 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vp);
1265 DEBUG2(" SSL: Successfully restored session %s", buffer);
1268 if (sess_data) talloc_free(sess_data);
1269 if (pairlist) pairlist_free(&pairlist);
1275 #ifdef HAVE_OPENSSL_OCSP_H
1277 * This function extracts the OCSP Responder URL
1278 * from an existing x509 certificate.
1280 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1281 char **ppath, int *pssl)
1285 AUTHORITY_INFO_ACCESS *aia;
1286 ACCESS_DESCRIPTION *ad;
1288 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1290 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1291 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1292 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1293 if (ad->location->type == GEN_URI) {
1294 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1295 phost, pport, ppath, pssl))
1304 * This function sends a OCSP request to a defined OCSP responder
1305 * and checks the OCSP response for correctness.
1308 /* Maximum leeway in validity period: default 5 minutes */
1309 #define MAX_VALIDITY_PERIOD (5 * 60)
1311 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1312 fr_tls_server_conf_t *conf)
1314 OCSP_CERTID *certid;
1316 OCSP_RESPONSE *resp = NULL;
1317 OCSP_BASICRESP *bresp = NULL;
1321 char hostheader[1024];
1323 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1324 BIO *cbio, *bio_out;
1327 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1329 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1333 struct timeval when;
1337 * Create OCSP Request
1339 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1340 req = OCSP_REQUEST_new();
1341 OCSP_request_add0_id(req, certid);
1342 if(conf->ocsp_use_nonce) {
1343 OCSP_request_add1_nonce(req, NULL, 8);
1347 * Send OCSP Request and get OCSP Response
1350 /* Get OCSP responder URL */
1351 if (conf->ocsp_override_url) {
1354 memcpy(&url, &conf->ocsp_url, sizeof(url));
1355 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1356 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1359 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1362 if (!host || !port || !path) {
1363 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP");
1368 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1370 /* Check host and port length are sane, then create Host: HTTP header */
1371 if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1372 ERROR("OCSP Host and port too long");
1375 snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1377 /* Setup BIO socket to OCSP responder */
1378 cbio = BIO_new_connect(host);
1382 if (default_log.dst == L_DST_STDOUT) {
1383 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1384 } else if (default_log.dst == L_DST_STDERR) {
1385 bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1389 BIO_set_conn_port(cbio, port);
1390 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1391 BIO_do_connect(cbio);
1393 /* Send OCSP request and wait for response */
1394 resp = OCSP_sendreq_bio(cbio, path, req);
1396 ERROR("Couldn't get OCSP response");
1401 if (conf->ocsp_timeout)
1402 BIO_set_nbio(cbio, 1);
1404 rc = BIO_do_connect(cbio);
1405 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1406 ERROR("Couldn't connect to OCSP responder");
1411 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1413 ERROR("Couldn't create OCSP request");
1418 if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1419 ERROR("Couldn't set Host header");
1424 if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1425 ERROR("Couldn't add data to OCSP request");
1430 gettimeofday(&when, NULL);
1431 when.tv_sec += conf->ocsp_timeout;
1434 rc = OCSP_sendreq_nbio(&resp, ctx);
1435 if (conf->ocsp_timeout) {
1436 gettimeofday(&now, NULL);
1437 if (!timercmp(&now, &when, <))
1440 } while ((rc == -1) && BIO_should_retry(cbio));
1442 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1443 ERROR("OCSP response timed out");
1448 OCSP_REQ_CTX_free(ctx);
1451 ERROR("Couldn't get OCSP response");
1457 /* Verify OCSP response status */
1458 status = OCSP_response_status(resp);
1459 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1460 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1461 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1464 bresp = OCSP_response_get1_basic(resp);
1465 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1466 ERROR("OCSP response has wrong nonce value");
1469 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1470 ERROR("Couldn't verify OCSP basic response");
1474 /* Verify OCSP cert status */
1475 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1476 &rev, &thisupd, &nextupd)) {
1477 ERROR("No Status found.\n");
1481 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1483 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1484 ERR_print_errors(bio_out);
1491 BIO_puts(bio_out, "\tThis Update: ");
1492 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1493 BIO_puts(bio_out, "\n");
1495 BIO_puts(bio_out, "\tNext Update: ");
1496 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1497 BIO_puts(bio_out, "\n");
1502 case V_OCSP_CERTSTATUS_GOOD:
1503 DEBUG2("[oscp] --> Cert status: good");
1508 /* REVOKED / UNKNOWN */
1509 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1511 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1514 BIO_puts(bio_out, "\tRevocation Time: ");
1515 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1516 BIO_puts(bio_out, "\n");
1522 /* Free OCSP Stuff */
1523 OCSP_REQUEST_free(req);
1524 OCSP_RESPONSE_free(resp);
1529 if (bio_out) BIO_free(bio_out);
1530 OCSP_BASICRESP_free(bresp);
1535 DEBUG2("[ocsp] --> Certificate is valid!");
1538 if (conf->ocsp_softfail) {
1539 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1540 DEBUG2("[ocsp] --> Warning! This may be insecure");
1543 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1548 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1554 #endif /* HAVE_OPENSSL_OCSP_H */
1557 * For creating certificate attributes.
1559 static char const *cert_attr_names[8][2] = {
1560 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1561 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1562 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1563 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1564 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1565 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1566 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1567 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1570 #define FR_TLS_SERIAL (0)
1571 #define FR_TLS_EXPIRATION (1)
1572 #define FR_TLS_SUBJECT (2)
1573 #define FR_TLS_ISSUER (3)
1574 #define FR_TLS_CN (4)
1575 #define FR_TLS_SAN_EMAIL (5)
1576 #define FR_TLS_SAN_DNS (6)
1577 #define FR_TLS_SAN_UPN (7)
1580 * Before trusting a certificate, you must make sure that the
1581 * certificate is 'valid'. There are several steps that your
1582 * application can take in determining if a certificate is
1583 * valid. Commonly used steps are:
1585 * 1.Verifying the certificate's signature, and verifying that
1586 * the certificate has been issued by a trusted Certificate
1589 * 2.Verifying that the certificate is valid for the present date
1590 * (i.e. it is being presented within its validity dates).
1592 * 3.Verifying that the certificate has not been revoked by its
1593 * issuing Certificate Authority, by checking with respect to a
1594 * Certificate Revocation List (CRL).
1596 * 4.Verifying that the credentials presented by the certificate
1597 * fulfill additional requirements specific to the application,
1598 * such as with respect to access control lists or with respect
1599 * to OCSP (Online Certificate Status Processing).
1601 * NOTE: This callback will be called multiple times based on the
1602 * depth of the root certificate chain
1604 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1606 char subject[1024]; /* Used for the subject name */
1607 char issuer[1024]; /* Used for the issuer name */
1608 char attribute[1024];
1610 char common_name[1024];
1614 X509_CINF *client_inf;
1615 STACK_OF(X509_EXTENSION) *ext_list;
1617 int err, depth, lookup, loc;
1618 fr_tls_server_conf_t *conf;
1621 ASN1_INTEGER *sn = NULL;
1622 ASN1_TIME *asn_time = NULL;
1625 #ifdef HAVE_OPENSSL_OCSP_H
1626 X509_STORE *ocsp_store = NULL;
1630 TALLOC_CTX *talloc_ctx;
1632 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1633 err = X509_STORE_CTX_get_error(ctx);
1634 depth = X509_STORE_CTX_get_error_depth(ctx);
1639 * Log client/issuing cert. If there's an error, log
1642 if ((lookup > 1) && !my_ok) lookup = 1;
1645 * Retrieve the pointer to the SSL of the connection currently treated
1646 * and the application specific data stored into the SSL object.
1648 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1649 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1650 if (!conf) return 1;
1652 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1653 rad_assert(request != NULL);
1654 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1656 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1657 #ifdef HAVE_OPENSSL_OCSP_H
1658 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1661 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1664 * Get the Serial Number
1667 sn = X509_get_serialNumber(client_cert);
1669 RDEBUG2("TLS Verify adding attributes");
1673 * For this next bit, we create the attributes *only* if
1674 * we're at the client or issuing certificate, AND we
1675 * have a user identity. i.e. we don't create the
1676 * attributes for RadSec connections.
1678 if (certs && identity &&
1679 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1683 for (i = 0; i < sn->length; i++) {
1684 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1687 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1688 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1693 * Get the Expiration Date
1696 asn_time = X509_get_notAfter(client_cert);
1697 if (certs && identity && (lookup <= 1) && asn_time &&
1698 (asn_time->length < (int) sizeof(buf))) {
1699 memcpy(buf, (char*) asn_time->data, asn_time->length);
1700 buf[asn_time->length] = '\0';
1701 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1702 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1706 * Get the Subject & Issuer
1708 subject[0] = issuer[0] = '\0';
1709 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1711 subject[sizeof(subject) - 1] = '\0';
1712 if (certs && identity && (lookup <= 1) && subject[0]) {
1713 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1714 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1717 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1719 issuer[sizeof(issuer) - 1] = '\0';
1720 if (certs && identity && (lookup <= 1) && issuer[0]) {
1721 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1722 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1726 * Get the Common Name, if there is a subject.
1728 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1729 NID_commonName, common_name, sizeof(common_name));
1730 common_name[sizeof(common_name) - 1] = '\0';
1731 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1732 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1733 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1737 * Get the RFC822 Subject Alternative Name
1739 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1740 if (certs && (lookup <= 1) && (loc >= 0)) {
1741 X509_EXTENSION *ext = NULL;
1742 GENERAL_NAMES *names = NULL;
1745 if ((ext = X509_get_ext(client_cert, loc)) &&
1746 (names = X509V3_EXT_d2i(ext))) {
1747 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1748 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1750 switch (name->type) {
1753 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1754 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1755 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1757 #endif /* GEN_EMAIL */
1760 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1761 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1762 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1764 #endif /* GEN_DNS */
1765 #ifdef GEN_OTHERNAME
1767 /* look for a MS UPN */
1768 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1769 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1770 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1771 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1772 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1773 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1776 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
1781 #endif /* GEN_OTHERNAME */
1783 /* XXX TODO handle other SAN types */
1789 sk_GENERAL_NAME_free(names);
1793 * If the CRL has expired, that might still be OK.
1796 (conf->allow_expired_crl) &&
1797 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1799 X509_STORE_CTX_set_error( ctx, 0 );
1803 char const *p = X509_verify_cert_error_string(err);
1804 RERROR("SSL says error %d : %s", err, p);
1810 client_inf = client_cert->cert_info;
1811 ext_list = client_inf->extensions;
1817 * Grab the X509 extensions, and create attributes out of them.
1818 * For laziness, we re-use the OpenSSL names
1820 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1825 out = BIO_new(BIO_s_mem());
1826 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1828 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1830 X509_EXTENSION *ext;
1832 ext = sk_X509_EXTENSION_value(ext_list, i);
1834 obj = X509_EXTENSION_get_object(ext);
1835 i2a_ASN1_OBJECT(out, obj);
1836 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1837 if (len <= 0) continue;
1839 attribute[16 + len] = '\0';
1841 X509V3_EXT_print(out, ext, 0, 0);
1842 len = BIO_read(out, value , sizeof(value) - 1);
1843 if (len <= 0) continue;
1848 * Mash the OpenSSL name to our name, and
1849 * create the attribute.
1851 for (p = value + 16; *p != '\0'; p++) {
1852 if (*p == ' ') *p = '-';
1855 vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1856 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
1864 switch (ctx->error) {
1865 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1866 RERROR("issuer=%s", issuer);
1869 case X509_V_ERR_CERT_NOT_YET_VALID:
1870 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1871 RERROR("notBefore=");
1873 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1877 case X509_V_ERR_CERT_HAS_EXPIRED:
1878 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1879 RERROR("notAfter=");
1881 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1887 * If we're at the actual client cert, apply additional
1892 * If the conf tells us to, check cert issuer
1893 * against the specified value and fail
1894 * verification if they don't match.
1896 if (conf->check_cert_issuer &&
1897 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1898 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1903 * If the conf tells us to, check the CN in the
1904 * cert against xlat'ed value, but only if the
1905 * previous checks passed.
1907 if (my_ok && conf->check_cert_cn) {
1908 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1909 /* if this fails, fail the verification */
1912 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1913 if (strcmp(cn_str, common_name) != 0) {
1914 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1918 } /* check_cert_cn */
1920 #ifdef HAVE_OPENSSL_OCSP_H
1921 if (my_ok && conf->ocsp_enable){
1922 RDEBUG2("--> Starting OCSP Request");
1923 if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
1924 RERROR("Couldn't get issuer_cert for %s", common_name);
1926 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1931 while (conf->verify_client_cert_cmd) {
1936 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1937 conf->verify_tmp_dir, progname);
1938 fd = mkstemp(filename);
1940 RDEBUG("Failed creating file in %s: %s",
1941 conf->verify_tmp_dir, fr_syserror(errno));
1945 fp = fdopen(fd, "w");
1948 RDEBUG("Failed opening file %s: %s",
1949 filename, fr_syserror(errno));
1953 if (!PEM_write_X509(fp, client_cert)) {
1955 RDEBUG("Failed writing certificate to file");
1960 if (!pairmake_packet("TLS-Client-Cert-Filename",
1961 filename, T_OP_SET)) {
1962 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1967 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1968 if (radius_exec_program(NULL, 0, NULL, request, conf->verify_client_cert_cmd,
1969 request->packet->vps,
1970 true, true, EXEC_TIMEOUT) != 0) {
1971 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1974 RDEBUG("Client certificate CN %s passed external validation", common_name);
1985 if (debug_flag > 0) {
1986 RDEBUG2("chain-depth=%d, ", depth);
1987 RDEBUG2("error=%d", err);
1989 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1990 RDEBUG2("--> BUF-Name = %s", common_name);
1991 RDEBUG2("--> subject = %s", subject);
1992 RDEBUG2("--> issuer = %s", issuer);
1993 RDEBUG2("--> verify return:%d", my_ok);
1999 #ifdef HAVE_OPENSSL_OCSP_H
2001 * Create Global X509 revocation store and use it to verify
2004 * - Load the trusted CAs
2005 * - Load the trusted issuer certificates
2007 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2009 X509_STORE *store = NULL;
2011 store = X509_STORE_new();
2013 /* Load the CAs we trust */
2014 if (conf->ca_file || conf->ca_path)
2015 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2016 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
2017 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2021 #ifdef X509_V_FLAG_CRL_CHECK
2022 if (conf->check_crl)
2023 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2027 #endif /* HAVE_OPENSSL_OCSP_H */
2029 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2030 #ifndef OPENSSL_NO_ECDH
2031 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
2036 if (!ecdh_curve || !*ecdh_curve) return 0;
2038 nid = OBJ_sn2nid(ecdh_curve);
2040 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
2044 ecdh = EC_KEY_new_by_curve_name(nid);
2046 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
2050 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2052 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2062 * DIE OPENSSL DIE DIE DIE
2064 * What a palaver, just to free some data attached the
2065 * session. We need to do this because the "remove" callback
2066 * is called when refcount > 0 sometimes, if another thread
2067 * is using the session
2069 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2070 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2071 UNUSED long argl, UNUSED void *argp)
2073 VALUE_PAIR *vp = data_ptr;
2076 DEBUG2(" Freeing cached session VPs");
2081 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2082 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2083 UNUSED long argl, UNUSED void *argp)
2085 VALUE_PAIR **certs = data_ptr;
2088 DEBUG2(" Freeing cached session Certificates");
2093 /** Add all the default ciphers and message digests reate our context.
2095 * This should be called exactly once from main, before reading the main config
2096 * or initialising any modules.
2098 void tls_global_init(void)
2100 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
2101 SSL_library_init(); /* initialize library */
2102 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2103 OPENSSL_config(NULL);
2106 * Initialize the index for the certificates.
2108 fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2111 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2112 /** Check for vulnerable versions of libssl
2114 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2115 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2117 int tls_global_version_check(char const *acknowledged)
2121 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2125 /* Check for bad versions */
2126 v = (uint64_t) SSLeay();
2128 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2129 libssl_defect_t *defect = &libssl_defects[i];
2131 if ((v >= defect->low) && (v <= defect->high)) {
2132 ERROR("Refusing to start with libssl version %s (in range %s)",
2133 ssl_version(), ssl_version_range(defect->low, defect->high));
2134 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2135 ERROR("%s", defect->comment);
2142 INFO("Once you have verified libssl has been correctly patched, "
2143 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2152 /** Free any memory alloced by libssl
2155 void tls_global_cleanup(void)
2157 ERR_remove_state(0);
2159 CONF_modules_unload(1);
2162 CRYPTO_cleanup_all_ex_data();
2166 * Create SSL context
2168 * - Load the trusted CAs
2169 * - Load the Private key & the certificate
2170 * - Set the Context options & Verify options
2172 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2175 X509_STORE *certstore;
2176 int verify_mode = SSL_VERIFY_NONE;
2177 int ctx_options = 0;
2181 * SHA256 is in all versions of OpenSSL, but isn't
2182 * initialized by default. It's needed for WiMAX
2185 #ifdef HAVE_OPENSSL_EVP_SHA256
2186 EVP_add_digest(EVP_sha256());
2189 ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
2192 while ((err = ERR_get_error())) {
2193 DEBUG("Failed creating SSL context: %s",
2194 ERR_error_string(err, NULL));
2200 * Save the config on the context so that callbacks which
2201 * only get SSL_CTX* e.g. session persistence, can get it
2203 SSL_CTX_set_app_data(ctx, conf);
2206 * Identify the type of certificates that needs to be loaded
2208 if (conf->file_type) {
2209 type = SSL_FILETYPE_PEM;
2211 type = SSL_FILETYPE_ASN1;
2215 * Set the password to load private key
2217 if (conf->private_key_password) {
2220 * We don't want to put the private key password in eap.conf, so check
2221 * for our special string which indicates we should get the password
2224 char const* special_string = "Apple:UseCertAdmin";
2225 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2228 long const max_password_len = 128;
2229 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2230 conf->private_key_file);
2232 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2234 FILE* cmd_pipe = popen(cmd, "r");
2236 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2237 ERROR("Error reading private_key_file %s", conf->private_key_file);
2241 rad_const_free(conf->private_key_password);
2242 password = talloc_array(conf, char, max_password_len);
2244 ERROR("TLS: Can't allocate space for private_key_password");
2245 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2250 fgets(password, max_password_len, cmd_pipe);
2253 /* Get rid of newline at end of password. */
2254 password[strlen(password) - 1] = '\0';
2256 DEBUG3("tls: Password from command = \"%s\"", password);
2257 conf->private_key_password = password;
2264 memcpy(&password, &conf->private_key_password, sizeof(password));
2265 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2266 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2270 #ifdef PSK_MAX_IDENTITY_LEN
2273 * No dynamic query exists. There MUST be a
2274 * statically configured identity and password.
2276 if (conf->psk_query && !*conf->psk_query) {
2277 ERROR("Invalid PSK Configuration: psk_query cannot be empty");
2282 * Set the callback only if we can check things.
2284 if (conf->psk_identity || conf->psk_query) {
2285 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2288 } else if (conf->psk_query) {
2289 ERROR("Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2294 * Now check that if PSK is being used, the config is valid.
2296 if ((conf->psk_identity && !conf->psk_password) ||
2297 (!conf->psk_identity && conf->psk_password) ||
2298 (conf->psk_identity && !*conf->psk_identity) ||
2299 (conf->psk_password && !*conf->psk_password)) {
2300 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2304 if (conf->psk_identity) {
2305 size_t psk_len, hex_len;
2306 uint8_t buffer[PSK_MAX_PSK_LEN];
2308 if (conf->certificate_file ||
2309 conf->private_key_password || conf->private_key_file ||
2310 conf->ca_file || conf->ca_path) {
2311 ERROR("When PSKs are used, No certificate configuration is permitted");
2316 SSL_CTX_set_psk_client_callback(ctx,
2317 psk_client_callback);
2320 psk_len = strlen(conf->psk_password);
2321 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2322 ERROR("psk_hexphrase is too long (max %d)",
2328 * Check the password now, so that we don't have
2329 * errors at run-time.
2331 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2332 if (psk_len != (2 * hex_len)) {
2333 ERROR("psk_hexphrase is not all hex");
2340 (void) client; /* -Wunused */
2344 * Load our keys and certificates
2346 * If certificates are of type PEM then we can make use
2347 * of cert chain authentication using openssl api call
2348 * SSL_CTX_use_certificate_chain_file. Please see how
2349 * the cert chain needs to be given in PEM from
2352 if (!conf->certificate_file) goto load_ca;
2354 if (type == SSL_FILETYPE_PEM) {
2355 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2356 ERROR("Error reading certificate file %s:%s",
2357 conf->certificate_file,
2358 ERR_error_string(ERR_get_error(), NULL));
2362 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2363 ERROR("Error reading certificate file %s:%s",
2364 conf->certificate_file,
2365 ERR_error_string(ERR_get_error(), NULL));
2369 /* Load the CAs we trust */
2371 if (conf->ca_file || conf->ca_path) {
2372 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2373 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2374 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2378 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2380 if (conf->private_key_file) {
2381 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2382 ERROR("Failed reading private key file %s:%s",
2383 conf->private_key_file,
2384 ERR_error_string(ERR_get_error(), NULL));
2389 * Check if the loaded private key is the right one
2391 if (!SSL_CTX_check_private_key(ctx)) {
2392 ERROR("Private key does not match the certificate public key");
2397 #ifdef PSK_MAX_IDENTITY_LEN
2402 * We never want SSLv2 or SSLv3.
2404 ctx_options |= SSL_OP_NO_SSLv2;
2405 ctx_options |= SSL_OP_NO_SSLv3;
2408 * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2409 * Though they can be *globally* disabled if necessary.x
2411 #ifdef SSL_OP_NO_TLSv1_1
2412 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2414 #ifdef SSL_OP_NO_TLSv1_2
2415 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2418 #ifdef SSL_OP_NO_TICKET
2419 ctx_options |= SSL_OP_NO_TICKET ;
2423 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2424 * small subgroup attacks and forward secrecy. Always
2427 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2428 * time needed during negotiation, but it is not very
2431 ctx_options |= SSL_OP_SINGLE_DH_USE;
2434 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2435 * in Windows Vista client.
2436 * http://www.openssl.org/~bodo/tls-cbc.txt
2437 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2439 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2441 SSL_CTX_set_options(ctx, ctx_options);
2444 * TODO: Set the RSA & DH
2445 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2446 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2450 * set the message callback to identify the type of
2451 * message. For every new session, there can be a
2452 * different callback argument.
2454 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2458 * Set eliptical curve crypto configuration.
2460 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2461 #ifndef OPENSSL_NO_ECDH
2462 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2468 /* Set Info callback */
2469 SSL_CTX_set_info_callback(ctx, cbtls_info);
2472 * Callbacks, etc. for session resumption.
2474 if (conf->session_cache_enable) {
2475 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2476 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2477 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2479 SSL_CTX_set_quiet_shutdown(ctx, 1);
2480 if (fr_tls_ex_index_vps < 0)
2481 fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2485 * Check the certificates for revocation.
2487 #ifdef X509_V_FLAG_CRL_CHECK
2488 if (conf->check_crl) {
2489 certstore = SSL_CTX_get_cert_store(ctx);
2490 if (certstore == NULL) {
2491 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2492 ERROR("tls: Error reading Certificate Store");
2495 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2501 * Always verify the peer certificate
2503 verify_mode |= SSL_VERIFY_PEER;
2504 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2505 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2506 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2508 if (conf->verify_depth) {
2509 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2512 /* Load randomness */
2513 if (conf->random_file) {
2514 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2515 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2516 ERROR("tls: Error loading randomness");
2522 * Set the cipher list if we were told to
2524 if (conf->cipher_list) {
2525 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2526 ERROR("tls: Error setting cipher list");
2532 * Setup session caching
2534 if (conf->session_cache_enable) {
2536 * Create a unique context Id per EAP-TLS configuration.
2538 if (conf->session_id_name) {
2539 snprintf(conf->session_context_id,
2540 sizeof(conf->session_context_id),
2542 conf->session_id_name);
2544 snprintf(conf->session_context_id,
2545 sizeof(conf->session_context_id),
2550 * Cache it, and DON'T auto-clear it.
2552 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2554 SSL_CTX_set_session_id_context(ctx,
2555 (unsigned char *) conf->session_context_id,
2556 (unsigned int) strlen(conf->session_context_id));
2559 * Our timeout is in hours, this is in seconds.
2561 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2564 * Set the maximum number of entries in the
2567 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2570 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2578 * Free TLS client/server config
2579 * Should not be called outside this code, as a callback is
2580 * added to automatically free the data when the CONF_SECTION
2583 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2585 if (conf->ctx) SSL_CTX_free(conf->ctx);
2587 #ifdef HAVE_OPENSSL_OCSP_H
2588 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2589 conf->ocsp_store = NULL;
2593 memset(conf, 0, sizeof(*conf));
2598 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2600 fr_tls_server_conf_t *conf;
2602 conf = talloc_zero(ctx, fr_tls_server_conf_t);
2604 ERROR("Out of memory");
2608 talloc_set_destructor(conf, _tls_server_conf_free);
2613 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2615 fr_tls_server_conf_t *conf;
2618 * If cs has already been parsed there should be a cached copy
2619 * of conf already stored, so just return that.
2621 conf = cf_data_find(cs, "tls-conf");
2623 DEBUG("Using cached TLS configuration from previous invocation");
2627 conf = tls_server_conf_alloc(cs);
2629 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2636 * Save people from their own stupidity.
2638 if (conf->fragment_size < 100) conf->fragment_size = 100;
2640 if (!conf->private_key_file) {
2641 ERROR("TLS Server requires a private key file");
2645 if (!conf->certificate_file) {
2646 ERROR("TLS Server requires a certificate file");
2653 conf->ctx = tls_init_ctx(conf, 0);
2654 if (conf->ctx == NULL) {
2658 #ifdef HAVE_OPENSSL_OCSP_H
2660 * Initialize OCSP Revocation Store
2662 if (conf->ocsp_enable) {
2663 conf->ocsp_store = init_revocation_store(conf);
2664 if (conf->ocsp_store == NULL) goto error;
2666 #endif /*HAVE_OPENSSL_OCSP_H*/
2670 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2671 if (load_dh_params(conf->ctx, dh_file) < 0) {
2676 if (conf->verify_tmp_dir) {
2677 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2678 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2683 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2684 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2689 * Cache conf in cs in case we're asked to parse this again.
2691 cf_data_add(cs, "tls-conf", conf, NULL);
2696 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2698 fr_tls_server_conf_t *conf;
2700 conf = cf_data_find(cs, "tls-conf");
2702 DEBUG("Using cached TLS configuration from previous invocation");
2706 conf = tls_server_conf_alloc(cs);
2708 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2715 * Save people from their own stupidity.
2717 if (conf->fragment_size < 100) conf->fragment_size = 100;
2722 conf->ctx = tls_init_ctx(conf, 1);
2723 if (conf->ctx == NULL) {
2730 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2731 if (load_dh_params(conf->ctx, dh_file) < 0) {
2736 cf_data_add(cs, "tls-conf", conf, NULL);
2741 int tls_success(tls_session_t *ssn, REQUEST *request)
2743 VALUE_PAIR *vp, *vps = NULL;
2744 fr_tls_server_conf_t *conf;
2745 TALLOC_CTX *talloc_ctx;
2747 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2748 rad_assert(conf != NULL);
2750 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2753 * If there's no session resumption, delete the entry
2754 * from the cache. This means either it's disabled
2755 * globally for this SSL context, OR we were told to
2756 * disable it for this user.
2758 * This also means you can't turn it on just for one
2761 if ((!ssn->allow_session_resumption) ||
2762 (((vp = pairfind(request->config_items, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
2763 (vp->vp_integer == 0))) {
2764 SSL_CTX_remove_session(ssn->ctx,
2766 ssn->allow_session_resumption = false;
2769 * If we're in a resumed session and it's
2772 if (SSL_session_reused(ssn->ssl)) {
2773 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2777 * Else resumption IS allowed, so we store the
2778 * user data in the cache.
2780 } else if (!SSL_session_reused(ssn->ssl)) {
2783 char buffer[2 * MAX_SESSION_SIZE + 1];
2785 size = ssn->ssl->session->session_id_length;
2786 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2788 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2790 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2791 if (vp) pairadd(&vps, vp);
2793 vp = paircopy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2794 if (vp) pairadd(&vps, vp);
2796 vp = paircopy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
2797 if (vp) pairadd(&vps, vp);
2799 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2800 if (vp) pairadd(&vps, vp);
2802 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2803 if (vp) pairadd(&vps, vp);
2805 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
2808 * Hmm... the certs should probably be session data.
2812 * @todo: some go into reply, others into
2815 pairadd(&vps, paircopy(talloc_ctx, *certs));
2819 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2820 SSL_SESSION_set_ex_data(ssn->ssl->session, fr_tls_ex_index_vps, vps);
2821 if (conf->session_cache_path) {
2822 /* write the VPs to the cache file */
2823 char filename[256], buf[1024];
2826 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
2827 FR_DIR_SEP, buffer);
2828 vp_file = fopen(filename, "w");
2829 if (vp_file == NULL) {
2830 RDEBUG2("Could not write session VPs to persistent cache: %s",
2831 fr_syserror(errno));
2834 /* generate a dummy user-style entry which is easy to read back */
2835 fprintf(vp_file, "# SSL cached session\n");
2836 fprintf(vp_file, "%s\n", buffer);
2837 for (vp = fr_cursor_init(&cursor, &vps);
2839 vp = fr_cursor_next(&cursor)) {
2840 vp_prints(buf, sizeof(buf), vp);
2841 fprintf(vp_file, "\t%s,\n", buf);
2847 RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2848 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2852 * Else the session WAS allowed. Copy the cached reply.
2856 char buffer[2 * MAX_SESSION_SIZE + 1];
2858 size = ssn->ssl->session->session_id_length;
2859 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2861 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2863 vps = SSL_SESSION_get_ex_data(ssn->ssl->session, fr_tls_ex_index_vps);
2865 RWDEBUG("No information in cached session %s", buffer);
2870 RDEBUG("Adding cached attributes for session %s:", buffer);
2871 rdebug_pair_list(L_DBG_LVL_1, request, vps, NULL);
2872 for (vp = fr_cursor_init(&cursor, &vps);
2874 vp = fr_cursor_next(&cursor)) {
2876 * TLS-* attrs get added back to
2879 if ((vp->da->vendor == 0) &&
2880 (vp->da->attr >= PW_TLS_CERT_SERIAL) &&
2881 (vp->da->attr <= PW_TLS_CLIENT_CERT_SUBJECT_ALT_NAME_UPN)) {
2882 pairadd(&request->packet->vps, paircopyvp(request->packet, vp));
2884 pairadd(&request->reply->vps, paircopyvp(request->reply, vp));
2888 if (conf->session_cache_path) {
2889 /* "touch" the cached session/vp file */
2892 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2893 conf->session_cache_path, FR_DIR_SEP, buffer);
2894 utime(filename, NULL);
2895 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2896 conf->session_cache_path, FR_DIR_SEP, buffer);
2897 utime(filename, NULL);
2901 * Mark the request as resumed.
2903 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2911 void tls_fail(tls_session_t *ssn)
2914 * Force the session to NOT be cached.
2916 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2919 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2926 * Decrypt the complete record.
2928 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2929 ssn->dirty_in.used);
2930 if (err != (int) ssn->dirty_in.used) {
2931 record_init(&ssn->dirty_in);
2932 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used, err);
2937 * Clear the dirty buffer now that we are done with it
2938 * and init the clean_out buffer to store decrypted data
2940 record_init(&ssn->dirty_in);
2941 record_init(&ssn->clean_out);
2944 * Read (and decrypt) the tunneled data from the
2945 * SSL session, and put it into the decrypted
2948 err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
2952 RDEBUG("SSL_read Error");
2954 code = SSL_get_error(ssn->ssl, err);
2956 case SSL_ERROR_WANT_READ:
2957 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2958 return FR_TLS_MORE_FRAGMENTS;
2960 case SSL_ERROR_WANT_WRITE:
2961 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2965 DEBUG("Error in fragmentation logic: %s", ERR_error_string(code, NULL));
2968 * FIXME: Call int_ssl_check?
2975 if (err == 0) RWDEBUG("No data inside of the tunnel");
2978 * Passed all checks, successfully decrypted data
2980 ssn->clean_out.used = err;
2987 * Acknowledge received is for one of the following messages sent earlier
2988 * 1. Handshake completed Message, so now send, EAP-Success
2989 * 2. Alert Message, now send, EAP-Failure
2990 * 3. Fragment Message, now send, next Fragment
2992 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2994 RDEBUG2("Received TLS ACK");
2997 RERROR("FAIL: Unexpected ACK received. Could not obtain session information");
2998 return FR_TLS_INVALID;
3000 if (ssn->info.initialized == 0) {
3001 RDEBUG("No SSL info available. Waiting for more SSL data");
3002 return FR_TLS_REQUEST;
3004 if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3005 RERROR("FAIL: ACK without earlier message");
3006 return FR_TLS_INVALID;
3009 switch (ssn->info.content_type) {
3011 RDEBUG2("ACK alert");
3015 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3016 RDEBUG2("ACK handshake is finished");
3019 * From now on all the content is
3020 * application data set it here as nobody else
3023 ssn->info.content_type = application_data;
3024 return FR_TLS_SUCCESS;
3025 } /* else more data to send */
3027 RDEBUG2("ACK handshake fragment handler");
3028 /* Fragmentation handler, send next fragment */
3029 return FR_TLS_REQUEST;
3031 case application_data:
3032 RDEBUG2("ACK handshake fragment handler in application data");
3033 return FR_TLS_REQUEST;
3036 * For the rest of the conditions, switch over
3037 * to the default section below.
3040 RERROR("Invalid ACK received: %d", ssn->info.content_type);
3042 return FR_TLS_INVALID;
3046 #endif /* WITH_TLS */