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 HAVE_OPENSSL_EVP_H
55 # include <openssl/evp.h>
57 # include <openssl/ssl.h>
59 #ifdef ENABLE_OPENSSL_VERSION_CHECK
60 typedef struct libssl_defect {
69 /* Record critical defects in libssl here (newest first)*/
70 static libssl_defect_t libssl_defects[] =
73 .low = 0x010001000, /* 1.0.1 */
74 .high = 0x01000106f, /* 1.0.1f */
75 .id = "CVE-2014-0160",
77 .comment = "For more information see http://heartbleed.com"
82 /* index we use to store cached session VPs
83 * needs to be dynamic so we can supply a "free" function
85 static int fr_tls_ex_index_vps = -1;
86 int fr_tls_ex_index_certs = -1;
89 static void session_close(tls_session_t *ssn);
90 static void session_init(tls_session_t *ssn);
93 static void record_init(record_t *buf);
94 static void record_close(record_t *buf);
95 static unsigned int record_plus(record_t *buf, void const *ptr,
97 static unsigned int record_minus(record_t *buf, void *ptr,
100 #ifdef PSK_MAX_IDENTITY_LEN
101 static bool identity_is_safe(const char *identity)
105 if (!identity) return true;
107 while ((c = *(identity++)) != '\0') {
108 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
109 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
121 * When a client uses TLS-PSK to talk to a server, this callback
122 * is used by the server to determine the PSK to use.
124 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
126 unsigned int max_psk_len)
128 unsigned int psk_len = 0;
129 fr_tls_server_conf_t *conf;
132 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
133 FR_TLS_EX_INDEX_CONF);
136 request = (REQUEST *)SSL_get_ex_data(ssl,
137 FR_TLS_EX_INDEX_REQUEST);
138 if (request && conf->psk_query) {
141 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
144 * The passed identity is weird. Deny it.
146 if (!identity_is_safe(identity)) {
147 RWDEBUG("Invalid characters in PSK identity %s", identity);
151 vp = pairmake_packet("TLS-PSK-Identity", identity, T_OP_SET);
154 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
157 RWDEBUG("PSK expansion returned an empty string.");
162 * The returned key is truncated at MORE than
163 * OpenSSL can handle. That way we can detect
164 * the truncation, and complain about it.
166 if (hex_len > (2 * max_psk_len)) {
167 RWDEBUG("Returned PSK is too long (%u > %u)",
168 (unsigned int) hex_len, 2 * max_psk_len);
173 * Leave the TLS-PSK-Identity in the request, and
174 * convert the expansion from printable string
177 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
180 if (!conf->psk_identity) {
181 DEBUG("No static PSK identity set. Rejecting the user");
186 * No REQUEST, or no dynamic query. Just look for a
189 if (strcmp(identity, conf->psk_identity) != 0) {
190 ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
195 psk_len = strlen(conf->psk_password);
196 if (psk_len > (2 * max_psk_len)) return 0;
198 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
201 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
202 char *identity, unsigned int max_identity_len,
203 unsigned char *psk, unsigned int max_psk_len)
205 unsigned int psk_len;
206 fr_tls_server_conf_t *conf;
208 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
209 FR_TLS_EX_INDEX_CONF);
212 psk_len = strlen(conf->psk_password);
213 if (psk_len > (2 * max_psk_len)) return 0;
215 strlcpy(identity, conf->psk_identity, max_identity_len);
217 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
222 static int _tls_session_free(tls_session_t *ssn)
225 * Free any opaque TTLS or PEAP data.
227 if ((ssn->opaque) && (ssn->free_opaque)) {
228 ssn->free_opaque(ssn->opaque);
237 tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
240 tls_session_t *ssn = NULL;
243 ssn = talloc_zero(ctx, tls_session_t);
244 if (!ssn) return NULL;
246 talloc_set_destructor(ssn, _tls_session_free);
248 ssn->ctx = conf->ctx;
250 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
252 ssn->ssl = SSL_new(ssn->ctx);
258 request = request_alloc(ssn);
259 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
262 * Add the message callback to identify what type of
263 * message/handshake is passed
265 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
266 SSL_set_msg_callback_arg(ssn->ssl, ssn);
267 SSL_set_info_callback(ssn->ssl, cbtls_info);
270 * Always verify the peer certificate.
272 DEBUG2("Requiring Server certificate");
273 verify_mode = SSL_VERIFY_PEER;
274 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
275 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
277 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
278 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
279 SSL_set_fd(ssn->ssl, fd);
280 if (SSL_connect(ssn->ssl) <= 0) {
282 while ((err = ERR_get_error())) {
283 ERROR("tls: %s", ERR_error_string(err, NULL));
290 ssn->offset = conf->fragment_size;
296 /** Create a new TLS session
298 * Configures a new TLS session, configuring options, setting callbacks etc...
300 * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
301 * session is tied to another talloc'd object.
302 * @param conf to use to configure the tls session.
303 * @param request The current #REQUEST.
304 * @param client_cert Whether to require a client_cert.
305 * @return a new session on success, or NULL on error.
307 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
309 tls_session_t *state = NULL;
314 rad_assert(request != NULL);
317 * Manually flush the sessions every so often. If HALF
318 * of the session lifetime has passed since we last
319 * flushed, then flush it again.
321 * FIXME: Also do it every N sessions?
323 if (conf->session_cache_enable &&
324 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
325 RDEBUG2("Flushing SSL sessions (of #%ld)",
326 SSL_CTX_sess_number(conf->ctx));
328 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
329 conf->session_last_flushed = request->timestamp;
332 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
333 RERROR("Error creating new SSL session: %s", ERR_error_string(ERR_get_error(), NULL));
337 /* We use the SSL's "app_data" to indicate a call-back */
338 SSL_set_app_data(new_tls, NULL);
340 if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
341 RERROR("Error allocating memory for SSL state");
345 talloc_set_destructor(state, _tls_session_free);
347 state->ctx = conf->ctx;
348 state->ssl = new_tls;
351 * Initialize callbacks
353 state->record_init = record_init;
354 state->record_close = record_close;
355 state->record_plus = record_plus;
356 state->record_minus = record_minus;
359 * Create & hook the BIOs to handle the dirty side of the
360 * SSL. This is *very important* as we want to handle
361 * the transmission part. Now the only IO interface
362 * that SSL is aware of, is our defined BIO buffers.
364 * This means that all SSL IO is done to/from memory,
365 * and we can update those BIOs from the packets we've
368 state->into_ssl = BIO_new(BIO_s_mem());
369 state->from_ssl = BIO_new(BIO_s_mem());
370 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
373 * Add the message callback to identify what type of
374 * message/handshake is passed
376 SSL_set_msg_callback(new_tls, cbtls_msg);
377 SSL_set_msg_callback_arg(new_tls, state);
378 SSL_set_info_callback(new_tls, cbtls_info);
381 * In Server mode we only accept.
383 SSL_set_accept_state(state->ssl);
386 * Verify the peer certificate, if asked.
389 RDEBUG2("Requiring client certificate");
390 verify_mode = SSL_VERIFY_PEER;
391 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
392 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
394 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
396 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
397 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
398 state->length_flag = conf->include_length;
401 * We use default fragment size, unless the Framed-MTU
402 * tells us it's too big. Note that we do NOT account
403 * for the EAP-TLS headers if conf->fragment_size is
404 * large, because that config item looks to be confusing.
406 * i.e. it should REALLY be called MTU, and the code here
407 * should figure out what that means for TLS fragment size.
408 * asking the administrator to know the internal details
409 * of EAP-TLS in order to calculate fragment sizes is
412 state->offset = conf->fragment_size;
413 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
414 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
415 state->offset = vp->vp_integer;
418 if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
426 * Print out some text describing the error.
428 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
433 if ((l = ERR_get_error()) != 0) {
434 char const *p = ERR_error_string(l, NULL);
436 if (request && p) REDEBUG("SSL says: %s", p);
438 e = SSL_get_error(s, ret);
442 * These seem to be harmless and already "dealt
443 * with" by our non-blocking environment. NB:
444 * "ZERO_RETURN" is the clean "error"
445 * indicating a successfully closed SSL
446 * tunnel. We let this happen because our IO
447 * loop should not appear to have broken on
448 * this condition - and outside the IO loop, the
449 * "shutdown" state is checked.
451 * Don't print anything if we ignore the error.
454 case SSL_ERROR_WANT_READ:
455 case SSL_ERROR_WANT_WRITE:
456 case SSL_ERROR_WANT_X509_LOOKUP:
457 case SSL_ERROR_ZERO_RETURN:
461 * These seem to be indications of a genuine
462 * error that should result in the SSL tunnel
463 * being regarded as "dead".
465 case SSL_ERROR_SYSCALL:
466 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
471 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
477 * For any other errors that (a) exist, and (b)
478 * crop up - we need to interpret what to do with
479 * them - so "politely inform" the caller that
480 * the code needs updating here.
482 ERROR("SSL: FATAL SSL error ..... %d\n", e);
490 * We are the server, we always get the dirty data
491 * (Handshake data is also considered as dirty data)
492 * During handshake, since SSL API handles itself,
493 * After clean-up, dirty_out will be filled with
494 * the data required for handshaking. So we check
495 * if dirty_out is empty then we simply send it back.
496 * As of now, if handshake is successful, then we keep going,
499 * Fill the Bio with the dirty data to clean it
500 * Get the cleaned data from SSL, if it is not Handshake data
502 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
506 if (ssn->invalid_hb_used) return 0;
508 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
509 if (err != (int) ssn->dirty_in.used) {
510 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
512 record_init(&ssn->dirty_in);
515 record_init(&ssn->dirty_in);
517 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
518 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
520 ssn->clean_out.used += err;
524 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
528 /* Some Extra STATE information for easy debugging */
529 if (SSL_is_init_finished(ssn->ssl)) {
530 DEBUG2("SSL Connection Established\n");
532 if (SSL_in_init(ssn->ssl)) {
533 DEBUG2("In SSL Handshake Phase\n");
535 if (SSL_in_before(ssn->ssl)) {
536 DEBUG2("Before SSL Handshake Phase\n");
538 if (SSL_in_accept_init(ssn->ssl)) {
539 DEBUG2("In SSL Accept mode \n");
541 if (SSL_in_connect_init(ssn->ssl)) {
542 DEBUG2("In SSL Connect mode \n");
545 err = BIO_ctrl_pending(ssn->from_ssl);
547 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
548 sizeof(ssn->dirty_out.data));
550 ssn->dirty_out.used = err;
552 } else if (BIO_should_retry(ssn->from_ssl)) {
553 record_init(&ssn->dirty_in);
554 DEBUG2(" tls: Asking for more data in tunnel");
558 int_ssl_check(request, ssn->ssl, err, "BIO_read");
559 record_init(&ssn->dirty_in);
563 DEBUG2("SSL Application Data");
564 /* Its clean application data, do whatever we want */
565 record_init(&ssn->clean_out);
568 /* We are done with dirty_in, reinitialize it */
569 record_init(&ssn->dirty_in);
574 * Take cleartext user data, and encrypt it into the output buffer,
575 * to send to the client at the other end of the SSL connection.
577 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
582 * If there's un-encrypted data in 'clean_in', then write
583 * that data to the SSL session, and then call the BIO function
584 * to get that encrypted data from the SSL session, into
585 * a buffer which we can then package into an EAP packet.
587 * Based on Server's logic this clean_in is expected to
588 * contain the data to send to the client.
590 if (ssn->clean_in.used > 0) {
593 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
594 record_minus(&ssn->clean_in, NULL, written);
596 /* Get the dirty data from Bio to send it */
597 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
598 sizeof(ssn->dirty_out.data));
600 ssn->dirty_out.used = err;
602 int_ssl_check(request, ssn->ssl, err, "handshake_send");
609 static void session_init(tls_session_t *ssn)
612 ssn->into_ssl = ssn->from_ssl = NULL;
613 record_init(&ssn->clean_in);
614 record_init(&ssn->clean_out);
615 record_init(&ssn->dirty_in);
616 record_init(&ssn->dirty_out);
618 memset(&ssn->info, 0, sizeof(ssn->info));
622 ssn->tls_msg_len = 0;
623 ssn->length_flag = 0;
625 ssn->free_opaque = NULL;
628 static void session_close(tls_session_t *ssn)
630 SSL_set_quiet_shutdown(ssn->ssl, 1);
631 SSL_shutdown(ssn->ssl);
638 record_close(&ssn->clean_in);
639 record_close(&ssn->clean_out);
640 record_close(&ssn->dirty_in);
641 record_close(&ssn->dirty_out);
645 static void record_init(record_t *rec)
650 static void record_close(record_t *rec)
657 * Copy data to the intermediate buffer, before we send
660 static unsigned int record_plus(record_t *rec, void const *ptr,
663 unsigned int added = MAX_RECORD_SIZE - rec->used;
669 memcpy(rec->data + rec->used, ptr, added);
675 * Take data from the buffer, and give it to the caller.
677 static unsigned int record_minus(record_t *rec, void *ptr,
680 unsigned int taken = rec->used;
687 memcpy(ptr, rec->data, taken);
691 * This is pretty bad...
694 memmove(rec->data, rec->data + taken, rec->used);
698 void tls_session_information(tls_session_t *tls_session)
700 char const *str_write_p, *str_version, *str_content_type = "";
701 char const *str_details1 = "", *str_details2= "";
705 * Don't print this out in the normal course of
708 if (debug_flag == 0) {
712 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
714 switch (tls_session->info.version) {
716 str_version = "SSL 2.0";
719 str_version = "SSL 3.0 ";
722 str_version = "TLS 1.0 ";
725 str_version = "Unknown TLS version";
729 if (tls_session->info.version == SSL3_VERSION ||
730 tls_session->info.version == TLS1_VERSION) {
731 switch (tls_session->info.content_type) {
732 case SSL3_RT_CHANGE_CIPHER_SPEC:
733 str_content_type = "ChangeCipherSpec";
737 str_content_type = "Alert";
740 case SSL3_RT_HANDSHAKE:
741 str_content_type = "Handshake";
744 case SSL3_RT_APPLICATION_DATA:
745 str_content_type = "ApplicationData";
749 str_content_type = "UnknownContentType";
753 if (tls_session->info.content_type == SSL3_RT_ALERT) {
754 str_details1 = ", ???";
756 if (tls_session->info.record_len == 2) {
758 switch (tls_session->info.alert_level) {
759 case SSL3_AL_WARNING:
760 str_details1 = ", warning";
763 str_details1 = ", fatal";
767 str_details2 = " ???";
768 switch (tls_session->info.alert_description) {
769 case SSL3_AD_CLOSE_NOTIFY:
770 str_details2 = " close_notify";
773 case SSL3_AD_UNEXPECTED_MESSAGE:
774 str_details2 = " unexpected_message";
777 case SSL3_AD_BAD_RECORD_MAC:
778 str_details2 = " bad_record_mac";
781 case TLS1_AD_DECRYPTION_FAILED:
782 str_details2 = " decryption_failed";
785 case TLS1_AD_RECORD_OVERFLOW:
786 str_details2 = " record_overflow";
789 case SSL3_AD_DECOMPRESSION_FAILURE:
790 str_details2 = " decompression_failure";
793 case SSL3_AD_HANDSHAKE_FAILURE:
794 str_details2 = " handshake_failure";
797 case SSL3_AD_BAD_CERTIFICATE:
798 str_details2 = " bad_certificate";
801 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
802 str_details2 = " unsupported_certificate";
805 case SSL3_AD_CERTIFICATE_REVOKED:
806 str_details2 = " certificate_revoked";
809 case SSL3_AD_CERTIFICATE_EXPIRED:
810 str_details2 = " certificate_expired";
813 case SSL3_AD_CERTIFICATE_UNKNOWN:
814 str_details2 = " certificate_unknown";
817 case SSL3_AD_ILLEGAL_PARAMETER:
818 str_details2 = " illegal_parameter";
821 case TLS1_AD_UNKNOWN_CA:
822 str_details2 = " unknown_ca";
825 case TLS1_AD_ACCESS_DENIED:
826 str_details2 = " access_denied";
829 case TLS1_AD_DECODE_ERROR:
830 str_details2 = " decode_error";
833 case TLS1_AD_DECRYPT_ERROR:
834 str_details2 = " decrypt_error";
837 case TLS1_AD_EXPORT_RESTRICTION:
838 str_details2 = " export_restriction";
841 case TLS1_AD_PROTOCOL_VERSION:
842 str_details2 = " protocol_version";
845 case TLS1_AD_INSUFFICIENT_SECURITY:
846 str_details2 = " insufficient_security";
849 case TLS1_AD_INTERNAL_ERROR:
850 str_details2 = " internal_error";
853 case TLS1_AD_USER_CANCELLED:
854 str_details2 = " user_canceled";
857 case TLS1_AD_NO_RENEGOTIATION:
858 str_details2 = " no_renegotiation";
864 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
865 str_details1 = "???";
867 if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
868 case SSL3_MT_HELLO_REQUEST:
869 str_details1 = ", HelloRequest";
872 case SSL3_MT_CLIENT_HELLO:
873 str_details1 = ", ClientHello";
876 case SSL3_MT_SERVER_HELLO:
877 str_details1 = ", ServerHello";
880 case SSL3_MT_CERTIFICATE:
881 str_details1 = ", Certificate";
884 case SSL3_MT_SERVER_KEY_EXCHANGE:
885 str_details1 = ", ServerKeyExchange";
888 case SSL3_MT_CERTIFICATE_REQUEST:
889 str_details1 = ", CertificateRequest";
892 case SSL3_MT_SERVER_DONE:
893 str_details1 = ", ServerHelloDone";
896 case SSL3_MT_CERTIFICATE_VERIFY:
897 str_details1 = ", CertificateVerify";
900 case SSL3_MT_CLIENT_KEY_EXCHANGE:
901 str_details1 = ", ClientKeyExchange";
904 case SSL3_MT_FINISHED:
905 str_details1 = ", Finished";
911 snprintf(tls_session->info.info_description,
912 sizeof(tls_session->info.info_description),
913 "%s %s%s [length %04lx]%s%s\n",
914 str_write_p, str_version, str_content_type,
915 (unsigned long)tls_session->info.record_len,
916 str_details1, str_details2);
918 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
920 RDEBUG2("%s", tls_session->info.info_description);
922 DEBUG2("%s", tls_session->info.info_description);
926 static CONF_PARSER cache_config[] = {
927 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
929 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
930 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
932 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
933 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
934 { NULL, -1, 0, NULL, NULL } /* end the list */
937 static CONF_PARSER verify_config[] = {
938 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
939 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
940 { NULL, -1, 0, NULL, NULL } /* end the list */
943 #ifdef HAVE_OPENSSL_OCSP_H
944 static CONF_PARSER ocsp_config[] = {
945 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
946 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
947 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
948 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
949 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
950 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
951 { NULL, -1, 0, NULL, NULL } /* end the list */
955 static CONF_PARSER tls_server_config[] = {
956 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
957 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
958 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
959 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
960 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
961 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
962 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
963 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
964 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
965 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
966 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
967 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
968 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
969 #ifdef PSK_MAX_IDENTITY_LEN
970 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
971 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
972 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
974 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
975 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
976 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
977 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
978 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
979 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
980 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
981 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
982 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
983 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
985 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
986 #ifndef OPENSSL_NO_ECDH
987 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
991 #ifdef SSL_OP_NO_TLSv1_1
992 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
996 * @fixme Disabled because using TLS1.2 seems to cause MPPE key issues with eapol_test
997 * need to fix FreeRADIUS or wpa_supplicant.
999 #ifdef SSL_OP_NO_TLSv1_2
1000 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), "yes" },
1003 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
1005 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
1007 #ifdef HAVE_OPENSSL_OCSP_H
1008 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
1011 { NULL, -1, 0, NULL, NULL } /* end the list */
1015 static CONF_PARSER tls_client_config[] = {
1016 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
1017 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
1018 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
1019 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
1020 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1021 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1022 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1023 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1024 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1025 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1026 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1027 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1028 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1029 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1030 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1031 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1032 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1033 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1034 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1036 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1037 #ifndef OPENSSL_NO_ECDH
1038 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1042 #ifdef SSL_OP_NO_TLSv1_1
1043 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1045 #ifdef SSL_OP_NO_TLSv1_2
1046 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1049 { NULL, -1, 0, NULL, NULL } /* end the list */
1054 * TODO: Check for the type of key exchange * like conf->dh_key
1056 static int load_dh_params(SSL_CTX *ctx, char *file)
1061 if (!file) return 0;
1063 if ((bio = BIO_new_file(file, "r")) == NULL) {
1064 ERROR("tls: Unable to open DH file - %s", file);
1068 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1071 WARN("tls: Unable to set DH parameters. DH cipher suites may not work!");
1072 WARN("Fix this by running the OpenSSL command listed in eap.conf");
1076 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1077 ERROR("tls: Unable to set DH parameters");
1088 * Print debugging messages, and free data.
1090 * FIXME: Write sessions to some long-term storage, so that
1091 * session resumption can still occur after the server
1094 #define MAX_SESSION_SIZE (256)
1096 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1099 char buffer[2 * MAX_SESSION_SIZE + 1];
1100 fr_tls_server_conf_t *conf;
1102 size = sess->session_id_length;
1103 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1105 fr_bin2hex(buffer, sess->session_id, size);
1107 DEBUG2(" SSL: Removing session %s from the cache", buffer);
1108 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1109 if (conf && conf->session_cache_path) {
1113 /* remove session and any cached VPs */
1114 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1115 conf->session_cache_path, FR_DIR_SEP, buffer);
1116 rv = unlink(filename);
1118 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
1120 /* VPs might be absent; might not have been written to disk yet */
1121 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1122 conf->session_cache_path, FR_DIR_SEP, buffer);
1129 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1132 char buffer[2 * MAX_SESSION_SIZE + 1];
1133 fr_tls_server_conf_t *conf;
1134 unsigned char *sess_blob = NULL;
1136 size = sess->session_id_length;
1137 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1139 fr_bin2hex(buffer, sess->session_id, size);
1141 DEBUG2(" SSL: adding session %s to cache", buffer);
1143 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1144 if (conf && conf->session_cache_path) {
1145 int fd, rv, todo, blob_len;
1149 /* find out what length data we need */
1150 blob_len = i2d_SSL_SESSION(sess, NULL);
1152 /* something went wrong */
1153 DEBUG2(" SSL: could not find buffer length to persist session");
1158 /* Do not convert to TALLOC - Thread safety */
1159 /* alloc and convert to ASN.1 */
1160 sess_blob = malloc(blob_len);
1162 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1165 /* openssl mutates &p */
1167 rv = i2d_SSL_SESSION(sess, &p);
1168 if (rv != blob_len) {
1169 DEBUG2(" SSL: could not persist session");
1173 /* open output file */
1174 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1175 conf->session_cache_path, FR_DIR_SEP, buffer);
1176 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1178 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1185 rv = write(fd, p, todo);
1187 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1195 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1204 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1205 unsigned char *data, int len,
1209 char buffer[2 * MAX_SESSION_SIZE + 1];
1210 fr_tls_server_conf_t *conf;
1211 TALLOC_CTX *talloc_ctx;
1213 SSL_SESSION *sess = NULL;
1214 unsigned char *sess_data = NULL;
1215 PAIR_LIST *pairlist = NULL;
1218 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1220 fr_bin2hex(buffer, data, size);
1222 DEBUG2(" SSL: Client requested cached session %s", buffer);
1224 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1225 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1226 if (conf && conf->session_cache_path) {
1233 /* read in the cached VPs from the .vps file */
1234 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1235 conf->session_cache_path, FR_DIR_SEP, buffer);
1236 rv = pairlist_read(NULL, filename, &pairlist, 1);
1238 /* not safe to un-persist a session w/o VPs */
1239 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1243 /* load the actual SSL session */
1244 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1245 conf->session_cache_path, FR_DIR_SEP, buffer);
1246 fd = open(filename, O_RDONLY);
1248 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1252 rv = fstat(fd, &st);
1254 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1259 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1261 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1269 rv = read(fd, p, todo);
1271 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1280 /* openssl mutates &p */
1282 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1285 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1289 /* cache the VPs into the session */
1290 vp = paircopy(talloc_ctx, pairlist->reply);
1291 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vp);
1292 DEBUG2(" SSL: Successfully restored session %s", buffer);
1295 if (sess_data) talloc_free(sess_data);
1296 if (pairlist) pairlist_free(&pairlist);
1302 #ifdef HAVE_OPENSSL_OCSP_H
1304 * This function extracts the OCSP Responder URL
1305 * from an existing x509 certificate.
1307 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1308 char **ppath, int *pssl)
1312 AUTHORITY_INFO_ACCESS *aia;
1313 ACCESS_DESCRIPTION *ad;
1315 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1317 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1318 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1319 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1320 if (ad->location->type == GEN_URI) {
1321 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1322 phost, pport, ppath, pssl))
1331 * This function sends a OCSP request to a defined OCSP responder
1332 * and checks the OCSP response for correctness.
1335 /* Maximum leeway in validity period: default 5 minutes */
1336 #define MAX_VALIDITY_PERIOD (5 * 60)
1338 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1339 fr_tls_server_conf_t *conf)
1341 OCSP_CERTID *certid;
1343 OCSP_RESPONSE *resp = NULL;
1344 OCSP_BASICRESP *bresp = NULL;
1348 char hostheader[1024];
1350 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1351 BIO *cbio, *bio_out;
1354 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1356 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1360 struct timeval when;
1364 * Create OCSP Request
1366 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1367 req = OCSP_REQUEST_new();
1368 OCSP_request_add0_id(req, certid);
1369 if(conf->ocsp_use_nonce) {
1370 OCSP_request_add1_nonce(req, NULL, 8);
1374 * Send OCSP Request and get OCSP Response
1377 /* Get OCSP responder URL */
1378 if (conf->ocsp_override_url) {
1381 memcpy(&url, &conf->ocsp_url, sizeof(url));
1382 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1383 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1386 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1389 if (!host || !port || !path) {
1390 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP");
1395 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1397 /* Check host and port length are sane, then create Host: HTTP header */
1398 if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1399 ERROR("OCSP Host and port too long");
1402 snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1404 /* Setup BIO socket to OCSP responder */
1405 cbio = BIO_new_connect(host);
1409 if (default_log.dst == L_DST_STDOUT) {
1410 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1411 } else if (default_log.dst == L_DST_STDERR) {
1412 bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1416 BIO_set_conn_port(cbio, port);
1417 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1418 BIO_do_connect(cbio);
1420 /* Send OCSP request and wait for response */
1421 resp = OCSP_sendreq_bio(cbio, path, req);
1423 ERROR("Couldn't get OCSP response");
1428 if (conf->ocsp_timeout)
1429 BIO_set_nbio(cbio, 1);
1431 rc = BIO_do_connect(cbio);
1432 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1433 ERROR("Couldn't connect to OCSP responder");
1438 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1440 ERROR("Couldn't create OCSP request");
1445 if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1446 ERROR("Couldn't set Host header");
1451 if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1452 ERROR("Couldn't add data to OCSP request");
1457 gettimeofday(&when, NULL);
1458 when.tv_sec += conf->ocsp_timeout;
1461 rc = OCSP_sendreq_nbio(&resp, ctx);
1462 if (conf->ocsp_timeout) {
1463 gettimeofday(&now, NULL);
1464 if (!timercmp(&now, &when, <))
1467 } while ((rc == -1) && BIO_should_retry(cbio));
1469 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1470 ERROR("OCSP response timed out");
1475 OCSP_REQ_CTX_free(ctx);
1478 ERROR("Couldn't get OCSP response");
1484 /* Verify OCSP response status */
1485 status = OCSP_response_status(resp);
1486 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1487 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1488 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1491 bresp = OCSP_response_get1_basic(resp);
1492 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1493 ERROR("OCSP response has wrong nonce value");
1496 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1497 ERROR("Couldn't verify OCSP basic response");
1501 /* Verify OCSP cert status */
1502 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1503 &rev, &thisupd, &nextupd)) {
1504 ERROR("No Status found.\n");
1508 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1510 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1511 ERR_print_errors(bio_out);
1518 BIO_puts(bio_out, "\tThis Update: ");
1519 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1520 BIO_puts(bio_out, "\n");
1522 BIO_puts(bio_out, "\tNext Update: ");
1523 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1524 BIO_puts(bio_out, "\n");
1529 case V_OCSP_CERTSTATUS_GOOD:
1530 DEBUG2("[oscp] --> Cert status: good");
1535 /* REVOKED / UNKNOWN */
1536 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1538 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1541 BIO_puts(bio_out, "\tRevocation Time: ");
1542 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1543 BIO_puts(bio_out, "\n");
1549 /* Free OCSP Stuff */
1550 OCSP_REQUEST_free(req);
1551 OCSP_RESPONSE_free(resp);
1556 if (bio_out) BIO_free(bio_out);
1557 OCSP_BASICRESP_free(bresp);
1562 DEBUG2("[ocsp] --> Certificate is valid!");
1565 if (conf->ocsp_softfail) {
1566 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1567 DEBUG2("[ocsp] --> Warning! This may be insecure");
1570 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1575 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1581 #endif /* HAVE_OPENSSL_OCSP_H */
1584 * For creating certificate attributes.
1586 static char const *cert_attr_names[8][2] = {
1587 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1588 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1589 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1590 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1591 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1592 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1593 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1594 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1597 #define FR_TLS_SERIAL (0)
1598 #define FR_TLS_EXPIRATION (1)
1599 #define FR_TLS_SUBJECT (2)
1600 #define FR_TLS_ISSUER (3)
1601 #define FR_TLS_CN (4)
1602 #define FR_TLS_SAN_EMAIL (5)
1603 #define FR_TLS_SAN_DNS (6)
1604 #define FR_TLS_SAN_UPN (7)
1607 * Before trusting a certificate, you must make sure that the
1608 * certificate is 'valid'. There are several steps that your
1609 * application can take in determining if a certificate is
1610 * valid. Commonly used steps are:
1612 * 1.Verifying the certificate's signature, and verifying that
1613 * the certificate has been issued by a trusted Certificate
1616 * 2.Verifying that the certificate is valid for the present date
1617 * (i.e. it is being presented within its validity dates).
1619 * 3.Verifying that the certificate has not been revoked by its
1620 * issuing Certificate Authority, by checking with respect to a
1621 * Certificate Revocation List (CRL).
1623 * 4.Verifying that the credentials presented by the certificate
1624 * fulfill additional requirements specific to the application,
1625 * such as with respect to access control lists or with respect
1626 * to OCSP (Online Certificate Status Processing).
1628 * NOTE: This callback will be called multiple times based on the
1629 * depth of the root certificate chain
1631 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1633 char subject[1024]; /* Used for the subject name */
1634 char issuer[1024]; /* Used for the issuer name */
1635 char attribute[1024];
1637 char common_name[1024];
1641 X509_CINF *client_inf;
1642 STACK_OF(X509_EXTENSION) *ext_list;
1644 int err, depth, lookup, loc;
1645 fr_tls_server_conf_t *conf;
1648 ASN1_INTEGER *sn = NULL;
1649 ASN1_TIME *asn_time = NULL;
1652 #ifdef HAVE_OPENSSL_OCSP_H
1653 X509_STORE *ocsp_store = NULL;
1657 TALLOC_CTX *talloc_ctx;
1659 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1660 err = X509_STORE_CTX_get_error(ctx);
1661 depth = X509_STORE_CTX_get_error_depth(ctx);
1666 * Log client/issuing cert. If there's an error, log
1669 if ((lookup > 1) && !my_ok) lookup = 1;
1672 * Retrieve the pointer to the SSL of the connection currently treated
1673 * and the application specific data stored into the SSL object.
1675 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1676 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1677 if (!conf) return 1;
1679 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1680 rad_assert(request != NULL);
1681 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1683 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1684 #ifdef HAVE_OPENSSL_OCSP_H
1685 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1688 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1691 * Get the Serial Number
1694 sn = X509_get_serialNumber(client_cert);
1696 RDEBUG2("TLS Verify adding attributes");
1700 * For this next bit, we create the attributes *only* if
1701 * we're at the client or issuing certificate, AND we
1702 * have a user identity. i.e. we don't create the
1703 * attributes for RadSec connections.
1705 if (certs && identity &&
1706 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1710 for (i = 0; i < sn->length; i++) {
1711 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1714 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1715 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1720 * Get the Expiration Date
1723 asn_time = X509_get_notAfter(client_cert);
1724 if (certs && identity && (lookup <= 1) && asn_time &&
1725 (asn_time->length < (int) sizeof(buf))) {
1726 memcpy(buf, (char*) asn_time->data, asn_time->length);
1727 buf[asn_time->length] = '\0';
1728 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1729 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1733 * Get the Subject & Issuer
1735 subject[0] = issuer[0] = '\0';
1736 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1738 subject[sizeof(subject) - 1] = '\0';
1739 if (certs && identity && (lookup <= 1) && subject[0]) {
1740 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1741 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1744 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1746 issuer[sizeof(issuer) - 1] = '\0';
1747 if (certs && identity && (lookup <= 1) && issuer[0]) {
1748 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1749 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1753 * Get the Common Name, if there is a subject.
1755 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1756 NID_commonName, common_name, sizeof(common_name));
1757 common_name[sizeof(common_name) - 1] = '\0';
1758 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1759 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1760 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1764 * Get the RFC822 Subject Alternative Name
1766 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1767 if (certs && (lookup <= 1) && (loc >= 0)) {
1768 X509_EXTENSION *ext = NULL;
1769 GENERAL_NAMES *names = NULL;
1772 if ((ext = X509_get_ext(client_cert, loc)) &&
1773 (names = X509V3_EXT_d2i(ext))) {
1774 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1775 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1777 switch (name->type) {
1780 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1781 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1782 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1784 #endif /* GEN_EMAIL */
1787 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1788 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1789 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1791 #endif /* GEN_DNS */
1792 #ifdef GEN_OTHERNAME
1794 /* look for a MS UPN */
1795 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1796 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1797 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1798 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1799 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1800 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1803 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
1808 #endif /* GEN_OTHERNAME */
1810 /* XXX TODO handle other SAN types */
1816 sk_GENERAL_NAME_free(names);
1820 * If the CRL has expired, that might still be OK.
1823 (conf->allow_expired_crl) &&
1824 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1826 X509_STORE_CTX_set_error( ctx, 0 );
1830 char const *p = X509_verify_cert_error_string(err);
1831 RERROR("SSL says error %d : %s", err, p);
1837 client_inf = client_cert->cert_info;
1838 ext_list = client_inf->extensions;
1844 * Grab the X509 extensions, and create attributes out of them.
1845 * For laziness, we re-use the OpenSSL names
1847 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1852 out = BIO_new(BIO_s_mem());
1853 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1855 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1857 X509_EXTENSION *ext;
1859 ext = sk_X509_EXTENSION_value(ext_list, i);
1861 obj = X509_EXTENSION_get_object(ext);
1862 i2a_ASN1_OBJECT(out, obj);
1863 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1864 if (len <= 0) continue;
1866 attribute[16 + len] = '\0';
1868 X509V3_EXT_print(out, ext, 0, 0);
1869 len = BIO_read(out, value , sizeof(value) - 1);
1870 if (len <= 0) continue;
1875 * Mash the OpenSSL name to our name, and
1876 * create the attribute.
1878 for (p = value + 16; *p != '\0'; p++) {
1879 if (*p == ' ') *p = '-';
1882 vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1884 RDEBUG3("Skipping %s += '%s'. Define %s in the server dictionary "
1885 "if you require this attribute", attribute, value, attribute);
1887 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
1896 switch (ctx->error) {
1897 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1898 RERROR("issuer=%s", issuer);
1901 case X509_V_ERR_CERT_NOT_YET_VALID:
1902 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1903 RERROR("notBefore=");
1905 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1909 case X509_V_ERR_CERT_HAS_EXPIRED:
1910 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1911 RERROR("notAfter=");
1913 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1919 * If we're at the actual client cert, apply additional
1924 * If the conf tells us to, check cert issuer
1925 * against the specified value and fail
1926 * verification if they don't match.
1928 if (conf->check_cert_issuer &&
1929 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1930 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1935 * If the conf tells us to, check the CN in the
1936 * cert against xlat'ed value, but only if the
1937 * previous checks passed.
1939 if (my_ok && conf->check_cert_cn) {
1940 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1941 /* if this fails, fail the verification */
1944 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1945 if (strcmp(cn_str, common_name) != 0) {
1946 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1950 } /* check_cert_cn */
1952 #ifdef HAVE_OPENSSL_OCSP_H
1953 if (my_ok && conf->ocsp_enable){
1954 RDEBUG2("--> Starting OCSP Request");
1955 if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
1956 RERROR("Couldn't get issuer_cert for %s", common_name);
1958 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1963 while (conf->verify_client_cert_cmd) {
1968 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1969 conf->verify_tmp_dir, progname);
1970 fd = mkstemp(filename);
1972 RDEBUG("Failed creating file in %s: %s",
1973 conf->verify_tmp_dir, fr_syserror(errno));
1977 fp = fdopen(fd, "w");
1980 RDEBUG("Failed opening file %s: %s",
1981 filename, fr_syserror(errno));
1985 if (!PEM_write_X509(fp, client_cert)) {
1987 RDEBUG("Failed writing certificate to file");
1992 if (!pairmake_packet("TLS-Client-Cert-Filename",
1993 filename, T_OP_SET)) {
1994 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1999 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2000 if (radius_exec_program(NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2001 request->packet->vps,
2002 true, true, EXEC_TIMEOUT) != 0) {
2003 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
2006 RDEBUG("Client certificate CN %s passed external validation", common_name);
2017 if (debug_flag > 0) {
2018 RDEBUG2("chain-depth=%d, ", depth);
2019 RDEBUG2("error=%d", err);
2021 if (identity) RDEBUG2("--> User-Name = %s", *identity);
2022 RDEBUG2("--> BUF-Name = %s", common_name);
2023 RDEBUG2("--> subject = %s", subject);
2024 RDEBUG2("--> issuer = %s", issuer);
2025 RDEBUG2("--> verify return:%d", my_ok);
2031 #ifdef HAVE_OPENSSL_OCSP_H
2033 * Create Global X509 revocation store and use it to verify
2036 * - Load the trusted CAs
2037 * - Load the trusted issuer certificates
2039 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2041 X509_STORE *store = NULL;
2043 store = X509_STORE_new();
2045 /* Load the CAs we trust */
2046 if (conf->ca_file || conf->ca_path)
2047 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2048 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
2049 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2053 #ifdef X509_V_FLAG_CRL_CHECK
2054 if (conf->check_crl)
2055 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2059 #endif /* HAVE_OPENSSL_OCSP_H */
2061 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2062 #ifndef OPENSSL_NO_ECDH
2063 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
2068 if (!ecdh_curve || !*ecdh_curve) return 0;
2070 nid = OBJ_sn2nid(ecdh_curve);
2072 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
2076 ecdh = EC_KEY_new_by_curve_name(nid);
2078 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
2082 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2084 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2094 * DIE OPENSSL DIE DIE DIE
2096 * What a palaver, just to free some data attached the
2097 * session. We need to do this because the "remove" callback
2098 * is called when refcount > 0 sometimes, if another thread
2099 * is using the session
2101 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2102 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2103 UNUSED long argl, UNUSED void *argp)
2105 VALUE_PAIR *vp = data_ptr;
2108 DEBUG2(" Freeing cached session VPs");
2113 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2114 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2115 UNUSED long argl, UNUSED void *argp)
2117 VALUE_PAIR **certs = data_ptr;
2120 DEBUG2(" Freeing cached session Certificates");
2125 /** Add all the default ciphers and message digests reate our context.
2127 * This should be called exactly once from main, before reading the main config
2128 * or initialising any modules.
2130 void tls_global_init(void)
2132 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
2133 SSL_library_init(); /* initialize library */
2134 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2135 OPENSSL_config(NULL);
2138 * Initialize the index for the certificates.
2140 fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2143 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2144 /** Check for vulnerable versions of libssl
2146 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2147 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2149 int tls_global_version_check(char const *acknowledged)
2153 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2157 /* Check for bad versions */
2158 v = (uint64_t) SSLeay();
2160 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2161 libssl_defect_t *defect = &libssl_defects[i];
2163 if ((v >= defect->low) && (v <= defect->high)) {
2164 ERROR("Refusing to start with libssl version %s (in range %s)",
2165 ssl_version(), ssl_version_range(defect->low, defect->high));
2166 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2167 ERROR("%s", defect->comment);
2174 INFO("Once you have verified libssl has been correctly patched, "
2175 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2184 /** Free any memory alloced by libssl
2187 void tls_global_cleanup(void)
2189 ERR_remove_state(0);
2191 CONF_modules_unload(1);
2194 CRYPTO_cleanup_all_ex_data();
2197 /** Create SSL context
2199 * - Load the trusted CAs
2200 * - Load the Private key & the certificate
2201 * - Set the Context options & Verify options
2203 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2206 X509_STORE *certstore;
2207 int verify_mode = SSL_VERIFY_NONE;
2208 int ctx_options = 0;
2212 * SHA256 is in all versions of OpenSSL, but isn't
2213 * initialized by default. It's needed for WiMAX
2216 #ifdef HAVE_OPENSSL_EVP_SHA256
2217 EVP_add_digest(EVP_sha256());
2220 ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
2223 while ((err = ERR_get_error())) {
2224 DEBUG("Failed creating SSL context: %s",
2225 ERR_error_string(err, NULL));
2231 * Save the config on the context so that callbacks which
2232 * only get SSL_CTX* e.g. session persistence, can get it
2234 SSL_CTX_set_app_data(ctx, conf);
2237 * Identify the type of certificates that needs to be loaded
2239 if (conf->file_type) {
2240 type = SSL_FILETYPE_PEM;
2242 type = SSL_FILETYPE_ASN1;
2246 * Set the password to load private key
2248 if (conf->private_key_password) {
2251 * We don't want to put the private key password in eap.conf, so check
2252 * for our special string which indicates we should get the password
2255 char const* special_string = "Apple:UseCertAdmin";
2256 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2259 long const max_password_len = 128;
2260 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2261 conf->private_key_file);
2263 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2265 FILE* cmd_pipe = popen(cmd, "r");
2267 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2268 ERROR("Error reading private_key_file %s", conf->private_key_file);
2272 rad_const_free(conf->private_key_password);
2273 password = talloc_array(conf, char, max_password_len);
2275 ERROR("TLS: Can't allocate space for private_key_password");
2276 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2281 fgets(password, max_password_len, cmd_pipe);
2284 /* Get rid of newline at end of password. */
2285 password[strlen(password) - 1] = '\0';
2287 DEBUG3("tls: Password from command = \"%s\"", password);
2288 conf->private_key_password = password;
2295 memcpy(&password, &conf->private_key_password, sizeof(password));
2296 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2297 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2301 #ifdef PSK_MAX_IDENTITY_LEN
2304 * No dynamic query exists. There MUST be a
2305 * statically configured identity and password.
2307 if (conf->psk_query && !*conf->psk_query) {
2308 ERROR("Invalid PSK Configuration: psk_query cannot be empty");
2313 * Set the callback only if we can check things.
2315 if (conf->psk_identity || conf->psk_query) {
2316 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2319 } else if (conf->psk_query) {
2320 ERROR("Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2325 * Now check that if PSK is being used, the config is valid.
2327 if ((conf->psk_identity && !conf->psk_password) ||
2328 (!conf->psk_identity && conf->psk_password) ||
2329 (conf->psk_identity && !*conf->psk_identity) ||
2330 (conf->psk_password && !*conf->psk_password)) {
2331 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2335 if (conf->psk_identity) {
2336 size_t psk_len, hex_len;
2337 uint8_t buffer[PSK_MAX_PSK_LEN];
2339 if (conf->certificate_file ||
2340 conf->private_key_password || conf->private_key_file ||
2341 conf->ca_file || conf->ca_path) {
2342 ERROR("When PSKs are used, No certificate configuration is permitted");
2347 SSL_CTX_set_psk_client_callback(ctx,
2348 psk_client_callback);
2351 psk_len = strlen(conf->psk_password);
2352 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2353 ERROR("psk_hexphrase is too long (max %d)",
2359 * Check the password now, so that we don't have
2360 * errors at run-time.
2362 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2363 if (psk_len != (2 * hex_len)) {
2364 ERROR("psk_hexphrase is not all hex");
2371 (void) client; /* -Wunused */
2375 * Load our keys and certificates
2377 * If certificates are of type PEM then we can make use
2378 * of cert chain authentication using openssl api call
2379 * SSL_CTX_use_certificate_chain_file. Please see how
2380 * the cert chain needs to be given in PEM from
2383 if (!conf->certificate_file) goto load_ca;
2385 if (type == SSL_FILETYPE_PEM) {
2386 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2387 ERROR("Error reading certificate file %s:%s",
2388 conf->certificate_file,
2389 ERR_error_string(ERR_get_error(), NULL));
2393 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2394 ERROR("Error reading certificate file %s:%s",
2395 conf->certificate_file,
2396 ERR_error_string(ERR_get_error(), NULL));
2400 /* Load the CAs we trust */
2402 if (conf->ca_file || conf->ca_path) {
2403 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2404 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2405 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2409 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2411 if (conf->private_key_file) {
2412 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2413 ERROR("Failed reading private key file %s:%s",
2414 conf->private_key_file,
2415 ERR_error_string(ERR_get_error(), NULL));
2420 * Check if the loaded private key is the right one
2422 if (!SSL_CTX_check_private_key(ctx)) {
2423 ERROR("Private key does not match the certificate public key");
2428 #ifdef PSK_MAX_IDENTITY_LEN
2433 * We never want SSLv2 or SSLv3.
2435 ctx_options |= SSL_OP_NO_SSLv2;
2436 ctx_options |= SSL_OP_NO_SSLv3;
2439 * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2440 * Though they can be *globally* disabled if necessary.x
2442 #ifdef SSL_OP_NO_TLSv1_1
2443 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2445 #ifdef SSL_OP_NO_TLSv1_2
2446 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2449 #ifdef SSL_OP_NO_TICKET
2450 ctx_options |= SSL_OP_NO_TICKET;
2454 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2455 * small subgroup attacks and forward secrecy. Always
2458 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2459 * time needed during negotiation, but it is not very
2462 ctx_options |= SSL_OP_SINGLE_DH_USE;
2465 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2466 * in Windows Vista client.
2467 * http://www.openssl.org/~bodo/tls-cbc.txt
2468 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2470 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2472 SSL_CTX_set_options(ctx, ctx_options);
2475 * TODO: Set the RSA & DH
2476 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2477 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2481 * set the message callback to identify the type of
2482 * message. For every new session, there can be a
2483 * different callback argument.
2485 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2489 * Set eliptical curve crypto configuration.
2491 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2492 #ifndef OPENSSL_NO_ECDH
2493 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2499 /* Set Info callback */
2500 SSL_CTX_set_info_callback(ctx, cbtls_info);
2503 * Callbacks, etc. for session resumption.
2505 if (conf->session_cache_enable) {
2506 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2507 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2508 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2510 SSL_CTX_set_quiet_shutdown(ctx, 1);
2511 if (fr_tls_ex_index_vps < 0)
2512 fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2516 * Check the certificates for revocation.
2518 #ifdef X509_V_FLAG_CRL_CHECK
2519 if (conf->check_crl) {
2520 certstore = SSL_CTX_get_cert_store(ctx);
2521 if (certstore == NULL) {
2522 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2523 ERROR("tls: Error reading Certificate Store");
2526 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2532 * Always verify the peer certificate
2534 verify_mode |= SSL_VERIFY_PEER;
2535 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2536 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2537 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2539 if (conf->verify_depth) {
2540 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2543 /* Load randomness */
2544 if (conf->random_file) {
2545 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2546 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2547 ERROR("tls: Error loading randomness");
2553 * Set the cipher list if we were told to
2555 if (conf->cipher_list) {
2556 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2557 ERROR("tls: Error setting cipher list");
2563 * Setup session caching
2565 if (conf->session_cache_enable) {
2567 * Create a unique context Id per EAP-TLS configuration.
2569 if (conf->session_id_name) {
2570 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2571 "FR eap %s", conf->session_id_name);
2573 snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2578 * Cache it, and DON'T auto-clear it.
2580 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2582 SSL_CTX_set_session_id_context(ctx,
2583 (unsigned char *) conf->session_context_id,
2584 (unsigned int) strlen(conf->session_context_id));
2587 * Our timeout is in hours, this is in seconds.
2589 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2592 * Set the maximum number of entries in the
2595 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2598 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2606 * Free TLS client/server config
2607 * Should not be called outside this code, as a callback is
2608 * added to automatically free the data when the CONF_SECTION
2611 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2613 if (conf->ctx) SSL_CTX_free(conf->ctx);
2615 #ifdef HAVE_OPENSSL_OCSP_H
2616 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2617 conf->ocsp_store = NULL;
2621 memset(conf, 0, sizeof(*conf));
2626 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2628 fr_tls_server_conf_t *conf;
2630 conf = talloc_zero(ctx, fr_tls_server_conf_t);
2632 ERROR("Out of memory");
2636 talloc_set_destructor(conf, _tls_server_conf_free);
2641 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2643 fr_tls_server_conf_t *conf;
2646 * If cs has already been parsed there should be a cached copy
2647 * of conf already stored, so just return that.
2649 conf = cf_data_find(cs, "tls-conf");
2651 DEBUG("Using cached TLS configuration from previous invocation");
2655 conf = tls_server_conf_alloc(cs);
2657 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2664 * Save people from their own stupidity.
2666 if (conf->fragment_size < 100) conf->fragment_size = 100;
2668 if (!conf->private_key_file) {
2669 ERROR("TLS Server requires a private key file");
2673 if (!conf->certificate_file) {
2674 ERROR("TLS Server requires a certificate file");
2681 conf->ctx = tls_init_ctx(conf, 0);
2682 if (conf->ctx == NULL) {
2686 #ifdef HAVE_OPENSSL_OCSP_H
2688 * Initialize OCSP Revocation Store
2690 if (conf->ocsp_enable) {
2691 conf->ocsp_store = init_revocation_store(conf);
2692 if (conf->ocsp_store == NULL) goto error;
2694 #endif /*HAVE_OPENSSL_OCSP_H*/
2698 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2699 if (load_dh_params(conf->ctx, dh_file) < 0) {
2704 if (conf->verify_tmp_dir) {
2705 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2706 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2711 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2712 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2717 * Cache conf in cs in case we're asked to parse this again.
2719 cf_data_add(cs, "tls-conf", conf, NULL);
2724 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2726 fr_tls_server_conf_t *conf;
2728 conf = cf_data_find(cs, "tls-conf");
2730 DEBUG("Using cached TLS configuration from previous invocation");
2734 conf = tls_server_conf_alloc(cs);
2736 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2743 * Save people from their own stupidity.
2745 if (conf->fragment_size < 100) conf->fragment_size = 100;
2750 conf->ctx = tls_init_ctx(conf, 1);
2751 if (conf->ctx == NULL) {
2758 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2759 if (load_dh_params(conf->ctx, dh_file) < 0) {
2764 cf_data_add(cs, "tls-conf", conf, NULL);
2769 int tls_success(tls_session_t *ssn, REQUEST *request)
2771 VALUE_PAIR *vp, *vps = NULL;
2772 fr_tls_server_conf_t *conf;
2773 TALLOC_CTX *talloc_ctx;
2775 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2776 rad_assert(conf != NULL);
2778 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2781 * If there's no session resumption, delete the entry
2782 * from the cache. This means either it's disabled
2783 * globally for this SSL context, OR we were told to
2784 * disable it for this user.
2786 * This also means you can't turn it on just for one
2789 if ((!ssn->allow_session_resumption) ||
2790 (((vp = pairfind(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
2791 (vp->vp_integer == 0))) {
2792 SSL_CTX_remove_session(ssn->ctx,
2794 ssn->allow_session_resumption = false;
2797 * If we're in a resumed session and it's
2800 if (SSL_session_reused(ssn->ssl)) {
2801 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2805 * Else resumption IS allowed, so we store the
2806 * user data in the cache.
2808 } else if (!SSL_session_reused(ssn->ssl)) {
2811 char buffer[2 * MAX_SESSION_SIZE + 1];
2813 size = ssn->ssl->session->session_id_length;
2814 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2816 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2818 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2819 if (vp) pairadd(&vps, vp);
2821 vp = paircopy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2822 if (vp) pairadd(&vps, vp);
2824 vp = paircopy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
2825 if (vp) pairadd(&vps, vp);
2827 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2828 if (vp) pairadd(&vps, vp);
2830 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2831 if (vp) pairadd(&vps, vp);
2833 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
2836 * Hmm... the certs should probably be session data.
2840 * @todo: some go into reply, others into
2843 pairadd(&vps, paircopy(talloc_ctx, *certs));
2847 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2848 SSL_SESSION_set_ex_data(ssn->ssl->session, fr_tls_ex_index_vps, vps);
2849 if (conf->session_cache_path) {
2850 /* write the VPs to the cache file */
2851 char filename[256], buf[1024];
2854 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
2855 FR_DIR_SEP, buffer);
2856 vp_file = fopen(filename, "w");
2857 if (vp_file == NULL) {
2858 RDEBUG2("Could not write session VPs to persistent cache: %s",
2859 fr_syserror(errno));
2862 /* generate a dummy user-style entry which is easy to read back */
2863 fprintf(vp_file, "# SSL cached session\n");
2864 fprintf(vp_file, "%s\n", buffer);
2865 for (vp = fr_cursor_init(&cursor, &vps);
2867 vp = fr_cursor_next(&cursor)) {
2868 vp_prints(buf, sizeof(buf), vp);
2869 fprintf(vp_file, "\t%s,\n", buf);
2875 RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2876 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2880 * Else the session WAS allowed. Copy the cached reply.
2884 char buffer[2 * MAX_SESSION_SIZE + 1];
2886 size = ssn->ssl->session->session_id_length;
2887 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2889 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2891 vps = SSL_SESSION_get_ex_data(ssn->ssl->session, fr_tls_ex_index_vps);
2893 RWDEBUG("No information in cached session %s", buffer);
2898 RDEBUG("Adding cached attributes for session %s:", buffer);
2899 rdebug_pair_list(L_DBG_LVL_1, request, vps, NULL);
2900 for (vp = fr_cursor_init(&cursor, &vps);
2902 vp = fr_cursor_next(&cursor)) {
2904 * TLS-* attrs get added back to
2907 if ((vp->da->vendor == 0) &&
2908 (vp->da->attr >= PW_TLS_CERT_SERIAL) &&
2909 (vp->da->attr <= PW_TLS_CLIENT_CERT_SUBJECT_ALT_NAME_UPN)) {
2910 pairadd(&request->packet->vps, paircopyvp(request->packet, vp));
2912 pairadd(&request->reply->vps, paircopyvp(request->reply, vp));
2916 if (conf->session_cache_path) {
2917 /* "touch" the cached session/vp file */
2920 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2921 conf->session_cache_path, FR_DIR_SEP, buffer);
2922 utime(filename, NULL);
2923 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2924 conf->session_cache_path, FR_DIR_SEP, buffer);
2925 utime(filename, NULL);
2929 * Mark the request as resumed.
2931 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2939 void tls_fail(tls_session_t *ssn)
2942 * Force the session to NOT be cached.
2944 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2947 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2954 * Decrypt the complete record.
2956 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2957 ssn->dirty_in.used);
2958 if (err != (int) ssn->dirty_in.used) {
2959 record_init(&ssn->dirty_in);
2960 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used, err);
2965 * Clear the dirty buffer now that we are done with it
2966 * and init the clean_out buffer to store decrypted data
2968 record_init(&ssn->dirty_in);
2969 record_init(&ssn->clean_out);
2972 * Read (and decrypt) the tunneled data from the
2973 * SSL session, and put it into the decrypted
2976 err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
2980 RDEBUG("SSL_read Error");
2982 code = SSL_get_error(ssn->ssl, err);
2984 case SSL_ERROR_WANT_READ:
2985 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2986 return FR_TLS_MORE_FRAGMENTS;
2988 case SSL_ERROR_WANT_WRITE:
2989 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2993 DEBUG("Error in fragmentation logic: %s", ERR_error_string(code, NULL));
2996 * FIXME: Call int_ssl_check?
3003 if (err == 0) RWDEBUG("No data inside of the tunnel");
3006 * Passed all checks, successfully decrypted data
3008 ssn->clean_out.used = err;
3015 * Acknowledge received is for one of the following messages sent earlier
3016 * 1. Handshake completed Message, so now send, EAP-Success
3017 * 2. Alert Message, now send, EAP-Failure
3018 * 3. Fragment Message, now send, next Fragment
3020 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
3022 RDEBUG2("Received TLS ACK");
3025 RERROR("FAIL: Unexpected ACK received. Could not obtain session information");
3026 return FR_TLS_INVALID;
3028 if (ssn->info.initialized == 0) {
3029 RDEBUG("No SSL info available. Waiting for more SSL data");
3030 return FR_TLS_REQUEST;
3032 if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3033 RERROR("FAIL: ACK without earlier message");
3034 return FR_TLS_INVALID;
3037 switch (ssn->info.content_type) {
3039 RDEBUG2("ACK alert");
3043 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3044 RDEBUG2("ACK handshake is finished");
3047 * From now on all the content is
3048 * application data set it here as nobody else
3051 ssn->info.content_type = application_data;
3052 return FR_TLS_SUCCESS;
3053 } /* else more data to send */
3055 RDEBUG2("ACK handshake fragment handler");
3056 /* Fragmentation handler, send next fragment */
3057 return FR_TLS_REQUEST;
3059 case application_data:
3060 RDEBUG2("ACK handshake fragment handler in application data");
3061 return FR_TLS_REQUEST;
3064 * For the rest of the conditions, switch over
3065 * to the default section below.
3068 RERROR("Invalid ACK received: %d", ssn->info.content_type);
3070 return FR_TLS_INVALID;
3074 #endif /* WITH_TLS */