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 record_init(record_t *buf);
85 static void record_close(record_t *buf);
86 static unsigned int record_plus(record_t *buf, void const *ptr,
88 static unsigned int record_minus(record_t *buf, void *ptr,
91 #ifdef PSK_MAX_IDENTITY_LEN
92 static bool identity_is_safe(const char *identity)
96 if (!identity) return true;
98 while ((c = *(identity++)) != '\0') {
99 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
100 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
112 * When a client uses TLS-PSK to talk to a server, this callback
113 * is used by the server to determine the PSK to use.
115 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
117 unsigned int max_psk_len)
119 unsigned int psk_len = 0;
120 fr_tls_server_conf_t *conf;
123 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
124 FR_TLS_EX_INDEX_CONF);
127 request = (REQUEST *)SSL_get_ex_data(ssl,
128 FR_TLS_EX_INDEX_REQUEST);
129 if (request && conf->psk_query) {
132 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
135 * The passed identity is weird. Deny it.
137 if (!identity_is_safe(identity)) {
138 RWDEBUG("Invalid characters in PSK identity %s", identity);
142 vp = pairmake_packet("TLS-PSK-Identity", identity, T_OP_SET);
145 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
148 RWDEBUG("PSK expansion returned an empty string.");
153 * The returned key is truncated at MORE than
154 * OpenSSL can handle. That way we can detect
155 * the truncation, and complain about it.
157 if (hex_len > (2 * max_psk_len)) {
158 RWDEBUG("Returned PSK is too long (%u > %u)",
159 (unsigned int) hex_len, 2 * max_psk_len);
164 * Leave the TLS-PSK-Identity in the request, and
165 * convert the expansion from printable string
168 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
171 if (!conf->psk_identity) {
172 DEBUG("No static PSK identity set. Rejecting the user");
177 * No REQUEST, or no dynamic query. Just look for a
180 if (strcmp(identity, conf->psk_identity) != 0) {
181 ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
186 psk_len = strlen(conf->psk_password);
187 if (psk_len > (2 * max_psk_len)) return 0;
189 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
192 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
193 char *identity, unsigned int max_identity_len,
194 unsigned char *psk, unsigned int max_psk_len)
196 unsigned int psk_len;
197 fr_tls_server_conf_t *conf;
199 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
200 FR_TLS_EX_INDEX_CONF);
203 psk_len = strlen(conf->psk_password);
204 if (psk_len > (2 * max_psk_len)) return 0;
206 strlcpy(identity, conf->psk_identity, max_identity_len);
208 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
213 tls_session_t *tls_new_client_session(fr_tls_server_conf_t *conf, int fd)
216 tls_session_t *ssn = NULL;
219 ssn = talloc_zero(conf, tls_session_t);
220 if (!ssn) return NULL;
222 ssn->ctx = conf->ctx;
224 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
226 ssn->ssl = SSL_new(ssn->ctx);
232 request = request_alloc(ssn);
233 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
236 * Add the message callback to identify what type of
237 * message/handshake is passed
239 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
240 SSL_set_msg_callback_arg(ssn->ssl, ssn);
241 SSL_set_info_callback(ssn->ssl, cbtls_info);
244 * Always verify the peer certificate.
246 DEBUG2("Requiring Server certificate");
247 verify_mode = SSL_VERIFY_PEER;
248 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
249 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
251 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
252 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
253 SSL_set_fd(ssn->ssl, fd);
254 if (SSL_connect(ssn->ssl) <= 0) {
256 while ((err = ERR_get_error())) {
257 ERROR("tls: %s", ERR_error_string(err, NULL));
265 ssn->offset = conf->fragment_size;
270 static int _tls_session_free(tls_session_t *ssn)
273 * Free any opaque TTLS or PEAP data.
275 if ((ssn->opaque) && (ssn->free_opaque)) {
276 ssn->free_opaque(ssn->opaque);
285 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
287 tls_session_t *state = NULL;
292 rad_assert(request != NULL);
295 * Manually flush the sessions every so often. If HALF
296 * of the session lifetime has passed since we last
297 * flushed, then flush it again.
299 * FIXME: Also do it every N sessions?
301 if (conf->session_cache_enable &&
302 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
303 RDEBUG2("Flushing SSL sessions (of #%ld)",
304 SSL_CTX_sess_number(conf->ctx));
306 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
307 conf->session_last_flushed = request->timestamp;
310 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
311 ERROR("SSL: Error creating new SSL: %s",
312 ERR_error_string(ERR_get_error(), NULL));
316 /* We use the SSL's "app_data" to indicate a call-back */
317 SSL_set_app_data(new_tls, NULL);
319 if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
320 ERROR("SSL: Error allocating memory for SSL state");
324 talloc_set_destructor(state, _tls_session_free);
326 state->ctx = conf->ctx;
327 state->ssl = new_tls;
330 * Initialize callbacks
332 state->record_init = record_init;
333 state->record_close = record_close;
334 state->record_plus = record_plus;
335 state->record_minus = record_minus;
338 * Create & hook the BIOs to handle the dirty side of the
339 * SSL. This is *very important* as we want to handle
340 * the transmission part. Now the only IO interface
341 * that SSL is aware of, is our defined BIO buffers.
343 * This means that all SSL IO is done to/from memory,
344 * and we can update those BIOs from the packets we've
347 state->into_ssl = BIO_new(BIO_s_mem());
348 state->from_ssl = BIO_new(BIO_s_mem());
349 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
352 * Add the message callback to identify what type of
353 * message/handshake is passed
355 SSL_set_msg_callback(new_tls, cbtls_msg);
356 SSL_set_msg_callback_arg(new_tls, state);
357 SSL_set_info_callback(new_tls, cbtls_info);
360 * In Server mode we only accept.
362 SSL_set_accept_state(state->ssl);
365 * Verify the peer certificate, if asked.
368 RDEBUG2("Requiring client certificate");
369 verify_mode = SSL_VERIFY_PEER;
370 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
371 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
373 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
375 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
376 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
377 state->length_flag = conf->include_length;
380 * We use default fragment size, unless the Framed-MTU
381 * tells us it's too big. Note that we do NOT account
382 * for the EAP-TLS headers if conf->fragment_size is
383 * large, because that config item looks to be confusing.
385 * i.e. it should REALLY be called MTU, and the code here
386 * should figure out what that means for TLS fragment size.
387 * asking the administrator to know the internal details
388 * of EAP-TLS in order to calculate fragment sizes is
391 state->offset = conf->fragment_size;
392 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
393 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
394 state->offset = vp->vp_integer;
397 if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
405 * Print out some text describing the error.
407 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
412 if ((l = ERR_get_error()) != 0) {
413 char const *p = ERR_error_string(l, NULL);
415 if (request && p) REDEBUG("SSL says: %s", p);
417 e = SSL_get_error(s, ret);
421 * These seem to be harmless and already "dealt
422 * with" by our non-blocking environment. NB:
423 * "ZERO_RETURN" is the clean "error"
424 * indicating a successfully closed SSL
425 * tunnel. We let this happen because our IO
426 * loop should not appear to have broken on
427 * this condition - and outside the IO loop, the
428 * "shutdown" state is checked.
430 * Don't print anything if we ignore the error.
433 case SSL_ERROR_WANT_READ:
434 case SSL_ERROR_WANT_WRITE:
435 case SSL_ERROR_WANT_X509_LOOKUP:
436 case SSL_ERROR_ZERO_RETURN:
440 * These seem to be indications of a genuine
441 * error that should result in the SSL tunnel
442 * being regarded as "dead".
444 case SSL_ERROR_SYSCALL:
445 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
450 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
456 * For any other errors that (a) exist, and (b)
457 * crop up - we need to interpret what to do with
458 * them - so "politely inform" the caller that
459 * the code needs updating here.
461 ERROR("SSL: FATAL SSL error ..... %d\n", e);
469 * We are the server, we always get the dirty data
470 * (Handshake data is also considered as dirty data)
471 * During handshake, since SSL API handles itself,
472 * After clean-up, dirty_out will be filled with
473 * the data required for handshaking. So we check
474 * if dirty_out is empty then we simply send it back.
475 * As of now, if handshake is successful, then we keep going,
478 * Fill the Bio with the dirty data to clean it
479 * Get the cleaned data from SSL, if it is not Handshake data
481 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
485 if (ssn->invalid_hb_used) return 0;
487 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
488 if (err != (int) ssn->dirty_in.used) {
489 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
491 record_init(&ssn->dirty_in);
494 record_init(&ssn->dirty_in);
496 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
497 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
499 ssn->clean_out.used += err;
503 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
507 /* Some Extra STATE information for easy debugging */
508 if (SSL_is_init_finished(ssn->ssl)) {
509 DEBUG2("SSL Connection Established\n");
511 if (SSL_in_init(ssn->ssl)) {
512 DEBUG2("In SSL Handshake Phase\n");
514 if (SSL_in_before(ssn->ssl)) {
515 DEBUG2("Before SSL Handshake Phase\n");
517 if (SSL_in_accept_init(ssn->ssl)) {
518 DEBUG2("In SSL Accept mode \n");
520 if (SSL_in_connect_init(ssn->ssl)) {
521 DEBUG2("In SSL Connect mode \n");
524 err = BIO_ctrl_pending(ssn->from_ssl);
526 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
527 sizeof(ssn->dirty_out.data));
529 ssn->dirty_out.used = err;
531 } else if (BIO_should_retry(ssn->from_ssl)) {
532 record_init(&ssn->dirty_in);
533 DEBUG2(" tls: Asking for more data in tunnel");
537 int_ssl_check(request, ssn->ssl, err, "BIO_read");
538 record_init(&ssn->dirty_in);
542 DEBUG2("SSL Application Data");
543 /* Its clean application data, do whatever we want */
544 record_init(&ssn->clean_out);
547 /* We are done with dirty_in, reinitialize it */
548 record_init(&ssn->dirty_in);
553 * Take cleartext user data, and encrypt it into the output buffer,
554 * to send to the client at the other end of the SSL connection.
556 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
561 * If there's un-encrypted data in 'clean_in', then write
562 * that data to the SSL session, and then call the BIO function
563 * to get that encrypted data from the SSL session, into
564 * a buffer which we can then package into an EAP packet.
566 * Based on Server's logic this clean_in is expected to
567 * contain the data to send to the client.
569 if (ssn->clean_in.used > 0) {
572 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
573 record_minus(&ssn->clean_in, NULL, written);
575 /* Get the dirty data from Bio to send it */
576 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
577 sizeof(ssn->dirty_out.data));
579 ssn->dirty_out.used = err;
581 int_ssl_check(request, ssn->ssl, err, "handshake_send");
588 void session_init(tls_session_t *ssn)
591 ssn->into_ssl = ssn->from_ssl = NULL;
592 record_init(&ssn->clean_in);
593 record_init(&ssn->clean_out);
594 record_init(&ssn->dirty_in);
595 record_init(&ssn->dirty_out);
597 memset(&ssn->info, 0, sizeof(ssn->info));
601 ssn->tls_msg_len = 0;
602 ssn->length_flag = 0;
604 ssn->free_opaque = NULL;
607 void session_close(tls_session_t *ssn)
609 SSL_set_quiet_shutdown(ssn->ssl, 1);
610 SSL_shutdown(ssn->ssl);
617 record_close(&ssn->clean_in);
618 record_close(&ssn->clean_out);
619 record_close(&ssn->dirty_in);
620 record_close(&ssn->dirty_out);
624 static void record_init(record_t *rec)
629 static void record_close(record_t *rec)
636 * Copy data to the intermediate buffer, before we send
639 static unsigned int record_plus(record_t *rec, void const *ptr,
642 unsigned int added = MAX_RECORD_SIZE - rec->used;
648 memcpy(rec->data + rec->used, ptr, added);
654 * Take data from the buffer, and give it to the caller.
656 static unsigned int record_minus(record_t *rec, void *ptr,
659 unsigned int taken = rec->used;
666 memcpy(ptr, rec->data, taken);
670 * This is pretty bad...
673 memmove(rec->data, rec->data + taken, rec->used);
677 void tls_session_information(tls_session_t *tls_session)
679 char const *str_write_p, *str_version, *str_content_type = "";
680 char const *str_details1 = "", *str_details2= "";
684 * Don't print this out in the normal course of
687 if (debug_flag == 0) {
691 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
693 switch (tls_session->info.version) {
695 str_version = "SSL 2.0";
698 str_version = "SSL 3.0 ";
701 str_version = "TLS 1.0 ";
704 str_version = "Unknown TLS version";
708 if (tls_session->info.version == SSL3_VERSION ||
709 tls_session->info.version == TLS1_VERSION) {
710 switch (tls_session->info.content_type) {
711 case SSL3_RT_CHANGE_CIPHER_SPEC:
712 str_content_type = "ChangeCipherSpec";
716 str_content_type = "Alert";
719 case SSL3_RT_HANDSHAKE:
720 str_content_type = "Handshake";
723 case SSL3_RT_APPLICATION_DATA:
724 str_content_type = "ApplicationData";
728 str_content_type = "UnknownContentType";
732 if (tls_session->info.content_type == SSL3_RT_ALERT) {
733 str_details1 = ", ???";
735 if (tls_session->info.record_len == 2) {
737 switch (tls_session->info.alert_level) {
738 case SSL3_AL_WARNING:
739 str_details1 = ", warning";
742 str_details1 = ", fatal";
746 str_details2 = " ???";
747 switch (tls_session->info.alert_description) {
748 case SSL3_AD_CLOSE_NOTIFY:
749 str_details2 = " close_notify";
752 case SSL3_AD_UNEXPECTED_MESSAGE:
753 str_details2 = " unexpected_message";
756 case SSL3_AD_BAD_RECORD_MAC:
757 str_details2 = " bad_record_mac";
760 case TLS1_AD_DECRYPTION_FAILED:
761 str_details2 = " decryption_failed";
764 case TLS1_AD_RECORD_OVERFLOW:
765 str_details2 = " record_overflow";
768 case SSL3_AD_DECOMPRESSION_FAILURE:
769 str_details2 = " decompression_failure";
772 case SSL3_AD_HANDSHAKE_FAILURE:
773 str_details2 = " handshake_failure";
776 case SSL3_AD_BAD_CERTIFICATE:
777 str_details2 = " bad_certificate";
780 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
781 str_details2 = " unsupported_certificate";
784 case SSL3_AD_CERTIFICATE_REVOKED:
785 str_details2 = " certificate_revoked";
788 case SSL3_AD_CERTIFICATE_EXPIRED:
789 str_details2 = " certificate_expired";
792 case SSL3_AD_CERTIFICATE_UNKNOWN:
793 str_details2 = " certificate_unknown";
796 case SSL3_AD_ILLEGAL_PARAMETER:
797 str_details2 = " illegal_parameter";
800 case TLS1_AD_UNKNOWN_CA:
801 str_details2 = " unknown_ca";
804 case TLS1_AD_ACCESS_DENIED:
805 str_details2 = " access_denied";
808 case TLS1_AD_DECODE_ERROR:
809 str_details2 = " decode_error";
812 case TLS1_AD_DECRYPT_ERROR:
813 str_details2 = " decrypt_error";
816 case TLS1_AD_EXPORT_RESTRICTION:
817 str_details2 = " export_restriction";
820 case TLS1_AD_PROTOCOL_VERSION:
821 str_details2 = " protocol_version";
824 case TLS1_AD_INSUFFICIENT_SECURITY:
825 str_details2 = " insufficient_security";
828 case TLS1_AD_INTERNAL_ERROR:
829 str_details2 = " internal_error";
832 case TLS1_AD_USER_CANCELLED:
833 str_details2 = " user_canceled";
836 case TLS1_AD_NO_RENEGOTIATION:
837 str_details2 = " no_renegotiation";
843 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
844 str_details1 = "???";
846 if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
847 case SSL3_MT_HELLO_REQUEST:
848 str_details1 = ", HelloRequest";
851 case SSL3_MT_CLIENT_HELLO:
852 str_details1 = ", ClientHello";
855 case SSL3_MT_SERVER_HELLO:
856 str_details1 = ", ServerHello";
859 case SSL3_MT_CERTIFICATE:
860 str_details1 = ", Certificate";
863 case SSL3_MT_SERVER_KEY_EXCHANGE:
864 str_details1 = ", ServerKeyExchange";
867 case SSL3_MT_CERTIFICATE_REQUEST:
868 str_details1 = ", CertificateRequest";
871 case SSL3_MT_SERVER_DONE:
872 str_details1 = ", ServerHelloDone";
875 case SSL3_MT_CERTIFICATE_VERIFY:
876 str_details1 = ", CertificateVerify";
879 case SSL3_MT_CLIENT_KEY_EXCHANGE:
880 str_details1 = ", ClientKeyExchange";
883 case SSL3_MT_FINISHED:
884 str_details1 = ", Finished";
890 snprintf(tls_session->info.info_description,
891 sizeof(tls_session->info.info_description),
892 "%s %s%s [length %04lx]%s%s\n",
893 str_write_p, str_version, str_content_type,
894 (unsigned long)tls_session->info.record_len,
895 str_details1, str_details2);
897 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
899 RDEBUG2("%s", tls_session->info.info_description);
901 DEBUG2("%s", tls_session->info.info_description);
905 static CONF_PARSER cache_config[] = {
906 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
907 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
908 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
909 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
910 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
911 { NULL, -1, 0, NULL, NULL } /* end the list */
914 static CONF_PARSER verify_config[] = {
915 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
916 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
917 { NULL, -1, 0, NULL, NULL } /* end the list */
920 #ifdef HAVE_OPENSSL_OCSP_H
921 static CONF_PARSER ocsp_config[] = {
922 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
923 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
924 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
925 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
926 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
927 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
928 { NULL, -1, 0, NULL, NULL } /* end the list */
932 static CONF_PARSER tls_server_config[] = {
933 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
934 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
935 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
936 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
937 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
938 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
939 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
940 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
941 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
942 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
943 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
944 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
945 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
946 #ifdef PSK_MAX_IDENTITY_LEN
947 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
948 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
949 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
951 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
952 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
953 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
954 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
955 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
956 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
957 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
958 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
959 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
960 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
962 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
963 #ifndef OPENSSL_NO_ECDH
964 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
968 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
969 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
971 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
973 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
975 #ifdef HAVE_OPENSSL_OCSP_H
976 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
979 { NULL, -1, 0, NULL, NULL } /* end the list */
983 static CONF_PARSER tls_client_config[] = {
984 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
985 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
986 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
987 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
988 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
989 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
990 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
991 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
992 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
993 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
994 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
995 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
996 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
997 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
998 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
999 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1000 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1001 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1002 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1004 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1005 #ifndef OPENSSL_NO_ECDH
1006 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1010 #ifdef SSL_OP_NO_TLSv1_1
1011 { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1013 #ifdef SSL_OP_NO_TLSv1_2
1014 { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1017 { NULL, -1, 0, NULL, NULL } /* end the list */
1022 * TODO: Check for the type of key exchange * like conf->dh_key
1024 static int load_dh_params(SSL_CTX *ctx, char *file)
1029 if (!file) return 0;
1031 if ((bio = BIO_new_file(file, "r")) == NULL) {
1032 ERROR("tls: Unable to open DH file - %s", file);
1036 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1039 WARN("tls: Unable to set DH parameters. DH cipher suites may not work!");
1040 WARN("Fix this by running the OpenSSL command listed in eap.conf");
1044 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1045 ERROR("tls: Unable to set DH parameters");
1056 * Print debugging messages, and free data.
1058 * FIXME: Write sessions to some long-term storage, so that
1059 * session resumption can still occur after the server
1062 #define MAX_SESSION_SIZE (256)
1064 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1067 char buffer[2 * MAX_SESSION_SIZE + 1];
1068 fr_tls_server_conf_t *conf;
1070 size = sess->session_id_length;
1071 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1073 fr_bin2hex(buffer, sess->session_id, size);
1075 DEBUG2(" SSL: Removing session %s from the cache", buffer);
1076 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1077 if (conf && conf->session_cache_path) {
1081 /* remove session and any cached VPs */
1082 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1083 conf->session_cache_path, FR_DIR_SEP, buffer);
1084 rv = unlink(filename);
1086 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
1088 /* VPs might be absent; might not have been written to disk yet */
1089 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1090 conf->session_cache_path, FR_DIR_SEP, buffer);
1097 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1100 char buffer[2 * MAX_SESSION_SIZE + 1];
1101 fr_tls_server_conf_t *conf;
1102 unsigned char *sess_blob = NULL;
1104 size = sess->session_id_length;
1105 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1107 fr_bin2hex(buffer, sess->session_id, size);
1109 DEBUG2(" SSL: adding session %s to cache", buffer);
1111 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1112 if (conf && conf->session_cache_path) {
1113 int fd, rv, todo, blob_len;
1117 /* find out what length data we need */
1118 blob_len = i2d_SSL_SESSION(sess, NULL);
1120 /* something went wrong */
1121 DEBUG2(" SSL: could not find buffer length to persist session");
1126 /* Do not convert to TALLOC - Thread safety */
1127 /* alloc and convert to ASN.1 */
1128 sess_blob = malloc(blob_len);
1130 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1133 /* openssl mutates &p */
1135 rv = i2d_SSL_SESSION(sess, &p);
1136 if (rv != blob_len) {
1137 DEBUG2(" SSL: could not persist session");
1141 /* open output file */
1142 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1143 conf->session_cache_path, FR_DIR_SEP, buffer);
1144 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1146 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1153 rv = write(fd, p, todo);
1155 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1163 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1172 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1173 unsigned char *data, int len,
1177 char buffer[2 * MAX_SESSION_SIZE + 1];
1178 fr_tls_server_conf_t *conf;
1179 TALLOC_CTX *talloc_ctx;
1181 SSL_SESSION *sess = NULL;
1182 unsigned char *sess_data = NULL;
1183 PAIR_LIST *pairlist = NULL;
1186 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1188 fr_bin2hex(buffer, data, size);
1190 DEBUG2(" SSL: Client requested cached session %s", buffer);
1192 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1193 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1194 if (conf && conf->session_cache_path) {
1201 /* read in the cached VPs from the .vps file */
1202 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1203 conf->session_cache_path, FR_DIR_SEP, buffer);
1204 rv = pairlist_read(NULL, filename, &pairlist, 1);
1206 /* not safe to un-persist a session w/o VPs */
1207 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1211 /* load the actual SSL session */
1212 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1213 conf->session_cache_path, FR_DIR_SEP, buffer);
1214 fd = open(filename, O_RDONLY);
1216 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1220 rv = fstat(fd, &st);
1222 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1227 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1229 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1237 rv = read(fd, p, todo);
1239 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1248 /* openssl mutates &p */
1250 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1253 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1257 /* cache the VPs into the session */
1258 vp = paircopy(talloc_ctx, pairlist->reply);
1259 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vp);
1260 DEBUG2(" SSL: Successfully restored session %s", buffer);
1263 if (sess_data) talloc_free(sess_data);
1264 if (pairlist) pairlist_free(&pairlist);
1270 #ifdef HAVE_OPENSSL_OCSP_H
1272 * This function extracts the OCSP Responder URL
1273 * from an existing x509 certificate.
1275 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1276 char **ppath, int *pssl)
1280 AUTHORITY_INFO_ACCESS *aia;
1281 ACCESS_DESCRIPTION *ad;
1283 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1285 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1286 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1287 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1288 if (ad->location->type == GEN_URI) {
1289 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1290 phost, pport, ppath, pssl))
1299 * This function sends a OCSP request to a defined OCSP responder
1300 * and checks the OCSP response for correctness.
1303 /* Maximum leeway in validity period: default 5 minutes */
1304 #define MAX_VALIDITY_PERIOD (5 * 60)
1306 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1307 fr_tls_server_conf_t *conf)
1309 OCSP_CERTID *certid;
1311 OCSP_RESPONSE *resp = NULL;
1312 OCSP_BASICRESP *bresp = NULL;
1316 char hostheader[1024];
1318 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1319 BIO *cbio, *bio_out;
1322 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1324 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1328 struct timeval when;
1332 * Create OCSP Request
1334 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1335 req = OCSP_REQUEST_new();
1336 OCSP_request_add0_id(req, certid);
1337 if(conf->ocsp_use_nonce) {
1338 OCSP_request_add1_nonce(req, NULL, 8);
1342 * Send OCSP Request and get OCSP Response
1345 /* Get OCSP responder URL */
1346 if (conf->ocsp_override_url) {
1349 memcpy(&url, &conf->ocsp_url, sizeof(url));
1350 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1351 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1354 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1357 if (!host || !port || !path) {
1358 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP");
1363 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1365 /* Check host and port length are sane, then create Host: HTTP header */
1366 if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1367 ERROR("OCSP Host and port too long");
1370 snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1372 /* Setup BIO socket to OCSP responder */
1373 cbio = BIO_new_connect(host);
1377 if (default_log.dst == L_DST_STDOUT) {
1378 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1379 } else if (default_log.dst == L_DST_STDERR) {
1380 bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1384 BIO_set_conn_port(cbio, port);
1385 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1386 BIO_do_connect(cbio);
1388 /* Send OCSP request and wait for response */
1389 resp = OCSP_sendreq_bio(cbio, path, req);
1391 ERROR("Couldn't get OCSP response");
1396 if (conf->ocsp_timeout)
1397 BIO_set_nbio(cbio, 1);
1399 rc = BIO_do_connect(cbio);
1400 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1401 ERROR("Couldn't connect to OCSP responder");
1406 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1408 ERROR("Couldn't create OCSP request");
1413 if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1414 ERROR("Couldn't set Host header");
1419 if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1420 ERROR("Couldn't add data to OCSP request");
1425 gettimeofday(&when, NULL);
1426 when.tv_sec += conf->ocsp_timeout;
1429 rc = OCSP_sendreq_nbio(&resp, ctx);
1430 if (conf->ocsp_timeout) {
1431 gettimeofday(&now, NULL);
1432 if (!timercmp(&now, &when, <))
1435 } while ((rc == -1) && BIO_should_retry(cbio));
1437 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1438 ERROR("OCSP response timed out");
1443 OCSP_REQ_CTX_free(ctx);
1446 ERROR("Couldn't get OCSP response");
1452 /* Verify OCSP response status */
1453 status = OCSP_response_status(resp);
1454 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1455 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1456 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1459 bresp = OCSP_response_get1_basic(resp);
1460 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1461 ERROR("OCSP response has wrong nonce value");
1464 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1465 ERROR("Couldn't verify OCSP basic response");
1469 /* Verify OCSP cert status */
1470 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1471 &rev, &thisupd, &nextupd)) {
1472 ERROR("No Status found.\n");
1476 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1478 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1479 ERR_print_errors(bio_out);
1486 BIO_puts(bio_out, "\tThis Update: ");
1487 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1488 BIO_puts(bio_out, "\n");
1490 BIO_puts(bio_out, "\tNext Update: ");
1491 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1492 BIO_puts(bio_out, "\n");
1497 case V_OCSP_CERTSTATUS_GOOD:
1498 DEBUG2("[oscp] --> Cert status: good");
1503 /* REVOKED / UNKNOWN */
1504 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1506 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1509 BIO_puts(bio_out, "\tRevocation Time: ");
1510 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1511 BIO_puts(bio_out, "\n");
1517 /* Free OCSP Stuff */
1518 OCSP_REQUEST_free(req);
1519 OCSP_RESPONSE_free(resp);
1524 if (bio_out) BIO_free(bio_out);
1525 OCSP_BASICRESP_free(bresp);
1530 DEBUG2("[ocsp] --> Certificate is valid!");
1533 if (conf->ocsp_softfail) {
1534 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1535 DEBUG2("[ocsp] --> Warning! This may be insecure");
1538 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1543 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1549 #endif /* HAVE_OPENSSL_OCSP_H */
1552 * For creating certificate attributes.
1554 static char const *cert_attr_names[8][2] = {
1555 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1556 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1557 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1558 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1559 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1560 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1561 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1562 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1565 #define FR_TLS_SERIAL (0)
1566 #define FR_TLS_EXPIRATION (1)
1567 #define FR_TLS_SUBJECT (2)
1568 #define FR_TLS_ISSUER (3)
1569 #define FR_TLS_CN (4)
1570 #define FR_TLS_SAN_EMAIL (5)
1571 #define FR_TLS_SAN_DNS (6)
1572 #define FR_TLS_SAN_UPN (7)
1575 * Before trusting a certificate, you must make sure that the
1576 * certificate is 'valid'. There are several steps that your
1577 * application can take in determining if a certificate is
1578 * valid. Commonly used steps are:
1580 * 1.Verifying the certificate's signature, and verifying that
1581 * the certificate has been issued by a trusted Certificate
1584 * 2.Verifying that the certificate is valid for the present date
1585 * (i.e. it is being presented within its validity dates).
1587 * 3.Verifying that the certificate has not been revoked by its
1588 * issuing Certificate Authority, by checking with respect to a
1589 * Certificate Revocation List (CRL).
1591 * 4.Verifying that the credentials presented by the certificate
1592 * fulfill additional requirements specific to the application,
1593 * such as with respect to access control lists or with respect
1594 * to OCSP (Online Certificate Status Processing).
1596 * NOTE: This callback will be called multiple times based on the
1597 * depth of the root certificate chain
1599 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1601 char subject[1024]; /* Used for the subject name */
1602 char issuer[1024]; /* Used for the issuer name */
1603 char attribute[1024];
1605 char common_name[1024];
1609 X509_CINF *client_inf;
1610 STACK_OF(X509_EXTENSION) *ext_list;
1612 int err, depth, lookup, loc;
1613 fr_tls_server_conf_t *conf;
1616 ASN1_INTEGER *sn = NULL;
1617 ASN1_TIME *asn_time = NULL;
1620 #ifdef HAVE_OPENSSL_OCSP_H
1621 X509_STORE *ocsp_store = NULL;
1625 TALLOC_CTX *talloc_ctx;
1627 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1628 err = X509_STORE_CTX_get_error(ctx);
1629 depth = X509_STORE_CTX_get_error_depth(ctx);
1634 * Log client/issuing cert. If there's an error, log
1637 if ((lookup > 1) && !my_ok) lookup = 1;
1640 * Retrieve the pointer to the SSL of the connection currently treated
1641 * and the application specific data stored into the SSL object.
1643 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1644 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1645 if (!conf) return 1;
1647 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1648 rad_assert(request != NULL);
1649 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1651 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1652 #ifdef HAVE_OPENSSL_OCSP_H
1653 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1656 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1659 * Get the Serial Number
1662 sn = X509_get_serialNumber(client_cert);
1664 RDEBUG2("TLS Verify adding attributes");
1668 * For this next bit, we create the attributes *only* if
1669 * we're at the client or issuing certificate, AND we
1670 * have a user identity. i.e. we don't create the
1671 * attributes for RadSec connections.
1673 if (certs && identity &&
1674 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1678 for (i = 0; i < sn->length; i++) {
1679 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1682 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1683 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1688 * Get the Expiration Date
1691 asn_time = X509_get_notAfter(client_cert);
1692 if (certs && identity && (lookup <= 1) && asn_time &&
1693 (asn_time->length < (int) sizeof(buf))) {
1694 memcpy(buf, (char*) asn_time->data, asn_time->length);
1695 buf[asn_time->length] = '\0';
1696 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1697 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1701 * Get the Subject & Issuer
1703 subject[0] = issuer[0] = '\0';
1704 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1706 subject[sizeof(subject) - 1] = '\0';
1707 if (certs && identity && (lookup <= 1) && subject[0]) {
1708 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1709 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1712 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1714 issuer[sizeof(issuer) - 1] = '\0';
1715 if (certs && identity && (lookup <= 1) && issuer[0]) {
1716 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1717 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1721 * Get the Common Name, if there is a subject.
1723 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1724 NID_commonName, common_name, sizeof(common_name));
1725 common_name[sizeof(common_name) - 1] = '\0';
1726 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1727 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1728 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1732 * Get the RFC822 Subject Alternative Name
1734 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1735 if (certs && (lookup <= 1) && (loc >= 0)) {
1736 X509_EXTENSION *ext = NULL;
1737 GENERAL_NAMES *names = NULL;
1740 if ((ext = X509_get_ext(client_cert, loc)) &&
1741 (names = X509V3_EXT_d2i(ext))) {
1742 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1743 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1745 switch (name->type) {
1748 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1749 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1750 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1752 #endif /* GEN_EMAIL */
1755 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1756 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1757 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1759 #endif /* GEN_DNS */
1760 #ifdef GEN_OTHERNAME
1762 /* look for a MS UPN */
1763 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1764 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1765 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1766 vp = pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1767 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1768 rdebug_pair(L_DBG_LVL_2, request, vp, "&request:");
1771 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
1776 #endif /* GEN_OTHERNAME */
1778 /* XXX TODO handle other SAN types */
1784 sk_GENERAL_NAME_free(names);
1788 * If the CRL has expired, that might still be OK.
1791 (conf->allow_expired_crl) &&
1792 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1794 X509_STORE_CTX_set_error( ctx, 0 );
1798 char const *p = X509_verify_cert_error_string(err);
1799 RERROR("SSL says error %d : %s", err, p);
1805 client_inf = client_cert->cert_info;
1806 ext_list = client_inf->extensions;
1812 * Grab the X509 extensions, and create attributes out of them.
1813 * For laziness, we re-use the OpenSSL names
1815 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1820 out = BIO_new(BIO_s_mem());
1821 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1823 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1825 X509_EXTENSION *ext;
1827 ext = sk_X509_EXTENSION_value(ext_list, i);
1829 obj = X509_EXTENSION_get_object(ext);
1830 i2a_ASN1_OBJECT(out, obj);
1831 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1832 if (len <= 0) continue;
1834 attribute[16 + len] = '\0';
1836 X509V3_EXT_print(out, ext, 0, 0);
1837 len = BIO_read(out, value , sizeof(value) - 1);
1838 if (len <= 0) continue;
1843 * Mash the OpenSSL name to our name, and
1844 * create the attribute.
1846 for (p = value + 16; *p != '\0'; p++) {
1847 if (*p == ' ') *p = '-';
1850 vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1851 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
1859 switch (ctx->error) {
1860 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1861 RERROR("issuer=%s", issuer);
1864 case X509_V_ERR_CERT_NOT_YET_VALID:
1865 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1866 RERROR("notBefore=");
1868 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1872 case X509_V_ERR_CERT_HAS_EXPIRED:
1873 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1874 RERROR("notAfter=");
1876 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1882 * If we're at the actual client cert, apply additional
1887 * If the conf tells us to, check cert issuer
1888 * against the specified value and fail
1889 * verification if they don't match.
1891 if (conf->check_cert_issuer &&
1892 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1893 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1898 * If the conf tells us to, check the CN in the
1899 * cert against xlat'ed value, but only if the
1900 * previous checks passed.
1902 if (my_ok && conf->check_cert_cn) {
1903 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1904 /* if this fails, fail the verification */
1907 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1908 if (strcmp(cn_str, common_name) != 0) {
1909 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1913 } /* check_cert_cn */
1915 #ifdef HAVE_OPENSSL_OCSP_H
1916 if (my_ok && conf->ocsp_enable){
1917 RDEBUG2("--> Starting OCSP Request");
1918 if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
1919 RERROR("Couldn't get issuer_cert for %s", common_name);
1921 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1926 while (conf->verify_client_cert_cmd) {
1931 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1932 conf->verify_tmp_dir, progname);
1933 fd = mkstemp(filename);
1935 RDEBUG("Failed creating file in %s: %s",
1936 conf->verify_tmp_dir, fr_syserror(errno));
1940 fp = fdopen(fd, "w");
1943 RDEBUG("Failed opening file %s: %s",
1944 filename, fr_syserror(errno));
1948 if (!PEM_write_X509(fp, client_cert)) {
1950 RDEBUG("Failed writing certificate to file");
1955 if (!pairmake_packet("TLS-Client-Cert-Filename",
1956 filename, T_OP_SET)) {
1957 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1962 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1963 if (radius_exec_program(NULL, 0, NULL, request, conf->verify_client_cert_cmd,
1964 request->packet->vps,
1965 true, true, EXEC_TIMEOUT) != 0) {
1966 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1969 RDEBUG("Client certificate CN %s passed external validation", common_name);
1980 if (debug_flag > 0) {
1981 RDEBUG2("chain-depth=%d, ", depth);
1982 RDEBUG2("error=%d", err);
1984 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1985 RDEBUG2("--> BUF-Name = %s", common_name);
1986 RDEBUG2("--> subject = %s", subject);
1987 RDEBUG2("--> issuer = %s", issuer);
1988 RDEBUG2("--> verify return:%d", my_ok);
1994 #ifdef HAVE_OPENSSL_OCSP_H
1996 * Create Global X509 revocation store and use it to verify
1999 * - Load the trusted CAs
2000 * - Load the trusted issuer certificates
2002 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2004 X509_STORE *store = NULL;
2006 store = X509_STORE_new();
2008 /* Load the CAs we trust */
2009 if (conf->ca_file || conf->ca_path)
2010 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2011 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
2012 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2016 #ifdef X509_V_FLAG_CRL_CHECK
2017 if (conf->check_crl)
2018 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2022 #endif /* HAVE_OPENSSL_OCSP_H */
2024 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2025 #ifndef OPENSSL_NO_ECDH
2026 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
2031 if (!ecdh_curve || !*ecdh_curve) return 0;
2033 nid = OBJ_sn2nid(ecdh_curve);
2035 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
2039 ecdh = EC_KEY_new_by_curve_name(nid);
2041 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
2045 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2047 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2057 * DIE OPENSSL DIE DIE DIE
2059 * What a palaver, just to free some data attached the
2060 * session. We need to do this because the "remove" callback
2061 * is called when refcount > 0 sometimes, if another thread
2062 * is using the session
2064 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2065 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2066 UNUSED long argl, UNUSED void *argp)
2068 VALUE_PAIR *vp = data_ptr;
2071 DEBUG2(" Freeing cached session VPs");
2076 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2077 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2078 UNUSED long argl, UNUSED void *argp)
2080 VALUE_PAIR **certs = data_ptr;
2083 DEBUG2(" Freeing cached session Certificates");
2088 /** Add all the default ciphers and message digests reate our context.
2090 * This should be called exactly once from main, before reading the main config
2091 * or initialising any modules.
2093 void tls_global_init(void)
2095 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
2096 SSL_library_init(); /* initialize library */
2097 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2098 OPENSSL_config(NULL);
2101 * Initialize the index for the certificates.
2103 fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2106 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2107 /** Check for vulnerable versions of libssl
2109 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2110 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2112 int tls_global_version_check(char const *acknowledged)
2116 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2120 /* Check for bad versions */
2121 v = (uint64_t) SSLeay();
2123 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2124 libssl_defect_t *defect = &libssl_defects[i];
2126 if ((v >= defect->low) && (v <= defect->high)) {
2127 ERROR("Refusing to start with libssl version %s (in range %s)",
2128 ssl_version(), ssl_version_range(defect->low, defect->high));
2129 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2130 ERROR("%s", defect->comment);
2137 INFO("Once you have verified libssl has been correctly patched, "
2138 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2147 /** Free any memory alloced by libssl
2150 void tls_global_cleanup(void)
2152 ERR_remove_state(0);
2154 CONF_modules_unload(1);
2157 CRYPTO_cleanup_all_ex_data();
2161 * Create SSL context
2163 * - Load the trusted CAs
2164 * - Load the Private key & the certificate
2165 * - Set the Context options & Verify options
2167 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2170 X509_STORE *certstore;
2171 int verify_mode = SSL_VERIFY_NONE;
2172 int ctx_options = 0;
2176 * SHA256 is in all versions of OpenSSL, but isn't
2177 * initialized by default. It's needed for WiMAX
2180 #ifdef HAVE_OPENSSL_EVP_SHA256
2181 EVP_add_digest(EVP_sha256());
2184 ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
2187 while ((err = ERR_get_error())) {
2188 DEBUG("Failed creating SSL context: %s",
2189 ERR_error_string(err, NULL));
2195 * Save the config on the context so that callbacks which
2196 * only get SSL_CTX* e.g. session persistence, can get it
2198 SSL_CTX_set_app_data(ctx, conf);
2201 * Identify the type of certificates that needs to be loaded
2203 if (conf->file_type) {
2204 type = SSL_FILETYPE_PEM;
2206 type = SSL_FILETYPE_ASN1;
2210 * Set the password to load private key
2212 if (conf->private_key_password) {
2215 * We don't want to put the private key password in eap.conf, so check
2216 * for our special string which indicates we should get the password
2219 char const* special_string = "Apple:UseCertAdmin";
2220 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2223 long const max_password_len = 128;
2224 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2225 conf->private_key_file);
2227 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2229 FILE* cmd_pipe = popen(cmd, "r");
2231 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2232 ERROR("Error reading private_key_file %s", conf->private_key_file);
2236 rad_const_free(conf->private_key_password);
2237 password = talloc_array(conf, char, max_password_len);
2239 ERROR("TLS: Can't allocate space for private_key_password");
2240 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2245 fgets(password, max_password_len, cmd_pipe);
2248 /* Get rid of newline at end of password. */
2249 password[strlen(password) - 1] = '\0';
2251 DEBUG3("tls: Password from command = \"%s\"", password);
2252 conf->private_key_password = password;
2259 memcpy(&password, &conf->private_key_password, sizeof(password));
2260 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2261 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2265 #ifdef PSK_MAX_IDENTITY_LEN
2268 * No dynamic query exists. There MUST be a
2269 * statically configured identity and password.
2271 if (conf->psk_query && !*conf->psk_query) {
2272 ERROR("Invalid PSK Configuration: psk_query cannot be empty");
2277 * Set the callback only if we can check things.
2279 if (conf->psk_identity || conf->psk_query) {
2280 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2283 } else if (conf->psk_query) {
2284 ERROR("Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2289 * Now check that if PSK is being used, the config is valid.
2291 if ((conf->psk_identity && !conf->psk_password) ||
2292 (!conf->psk_identity && conf->psk_password) ||
2293 (conf->psk_identity && !*conf->psk_identity) ||
2294 (conf->psk_password && !*conf->psk_password)) {
2295 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2299 if (conf->psk_identity) {
2300 size_t psk_len, hex_len;
2301 uint8_t buffer[PSK_MAX_PSK_LEN];
2303 if (conf->certificate_file ||
2304 conf->private_key_password || conf->private_key_file ||
2305 conf->ca_file || conf->ca_path) {
2306 ERROR("When PSKs are used, No certificate configuration is permitted");
2311 SSL_CTX_set_psk_client_callback(ctx,
2312 psk_client_callback);
2315 psk_len = strlen(conf->psk_password);
2316 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2317 ERROR("psk_hexphrase is too long (max %d)",
2323 * Check the password now, so that we don't have
2324 * errors at run-time.
2326 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2327 if (psk_len != (2 * hex_len)) {
2328 ERROR("psk_hexphrase is not all hex");
2335 (void) client; /* -Wunused */
2339 * Load our keys and certificates
2341 * If certificates are of type PEM then we can make use
2342 * of cert chain authentication using openssl api call
2343 * SSL_CTX_use_certificate_chain_file. Please see how
2344 * the cert chain needs to be given in PEM from
2347 if (!conf->certificate_file) goto load_ca;
2349 if (type == SSL_FILETYPE_PEM) {
2350 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2351 ERROR("Error reading certificate file %s:%s",
2352 conf->certificate_file,
2353 ERR_error_string(ERR_get_error(), NULL));
2357 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2358 ERROR("Error reading certificate file %s:%s",
2359 conf->certificate_file,
2360 ERR_error_string(ERR_get_error(), NULL));
2364 /* Load the CAs we trust */
2366 if (conf->ca_file || conf->ca_path) {
2367 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2368 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2369 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2373 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2375 if (conf->private_key_file) {
2376 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2377 ERROR("Failed reading private key file %s:%s",
2378 conf->private_key_file,
2379 ERR_error_string(ERR_get_error(), NULL));
2384 * Check if the loaded private key is the right one
2386 if (!SSL_CTX_check_private_key(ctx)) {
2387 ERROR("Private key does not match the certificate public key");
2392 #ifdef PSK_MAX_IDENTITY_LEN
2397 * We never want SSLv2 or SSLv3.
2399 ctx_options |= SSL_OP_NO_SSLv2;
2400 ctx_options |= SSL_OP_NO_SSLv3;
2403 * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2404 * Though they can be *globally* disabled if necessary.x
2406 #ifdef SSL_OP_NO_TLSv1_1
2407 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2409 #ifdef SSL_OP_NO_TLSv1_2
2410 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2413 #ifdef SSL_OP_NO_TICKET
2414 ctx_options |= SSL_OP_NO_TICKET ;
2418 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2419 * small subgroup attacks and forward secrecy. Always
2422 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2423 * time needed during negotiation, but it is not very
2426 ctx_options |= SSL_OP_SINGLE_DH_USE;
2429 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2430 * in Windows Vista client.
2431 * http://www.openssl.org/~bodo/tls-cbc.txt
2432 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2434 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2436 SSL_CTX_set_options(ctx, ctx_options);
2439 * TODO: Set the RSA & DH
2440 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2441 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2445 * set the message callback to identify the type of
2446 * message. For every new session, there can be a
2447 * different callback argument.
2449 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2453 * Set eliptical curve crypto configuration.
2455 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2456 #ifndef OPENSSL_NO_ECDH
2457 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2463 /* Set Info callback */
2464 SSL_CTX_set_info_callback(ctx, cbtls_info);
2467 * Callbacks, etc. for session resumption.
2469 if (conf->session_cache_enable) {
2470 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2471 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2472 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2474 SSL_CTX_set_quiet_shutdown(ctx, 1);
2475 if (fr_tls_ex_index_vps < 0)
2476 fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2480 * Check the certificates for revocation.
2482 #ifdef X509_V_FLAG_CRL_CHECK
2483 if (conf->check_crl) {
2484 certstore = SSL_CTX_get_cert_store(ctx);
2485 if (certstore == NULL) {
2486 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2487 ERROR("tls: Error reading Certificate Store");
2490 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2496 * Always verify the peer certificate
2498 verify_mode |= SSL_VERIFY_PEER;
2499 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2500 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2501 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2503 if (conf->verify_depth) {
2504 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2507 /* Load randomness */
2508 if (conf->random_file) {
2509 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2510 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2511 ERROR("tls: Error loading randomness");
2517 * Set the cipher list if we were told to
2519 if (conf->cipher_list) {
2520 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2521 ERROR("tls: Error setting cipher list");
2527 * Setup session caching
2529 if (conf->session_cache_enable) {
2531 * Create a unique context Id per EAP-TLS configuration.
2533 if (conf->session_id_name) {
2534 snprintf(conf->session_context_id,
2535 sizeof(conf->session_context_id),
2537 conf->session_id_name);
2539 snprintf(conf->session_context_id,
2540 sizeof(conf->session_context_id),
2545 * Cache it, and DON'T auto-clear it.
2547 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2549 SSL_CTX_set_session_id_context(ctx,
2550 (unsigned char *) conf->session_context_id,
2551 (unsigned int) strlen(conf->session_context_id));
2554 * Our timeout is in hours, this is in seconds.
2556 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2559 * Set the maximum number of entries in the
2562 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2565 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2573 * Free TLS client/server config
2574 * Should not be called outside this code, as a callback is
2575 * added to automatically free the data when the CONF_SECTION
2578 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2580 if (conf->ctx) SSL_CTX_free(conf->ctx);
2582 #ifdef HAVE_OPENSSL_OCSP_H
2583 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2584 conf->ocsp_store = NULL;
2588 memset(conf, 0, sizeof(*conf));
2593 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2595 fr_tls_server_conf_t *conf;
2597 conf = talloc_zero(ctx, fr_tls_server_conf_t);
2599 ERROR("Out of memory");
2603 talloc_set_destructor(conf, _tls_server_conf_free);
2608 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2610 fr_tls_server_conf_t *conf;
2613 * If cs has already been parsed there should be a cached copy
2614 * of conf already stored, so just return that.
2616 conf = cf_data_find(cs, "tls-conf");
2618 DEBUG("Using cached TLS configuration from previous invocation");
2622 conf = tls_server_conf_alloc(cs);
2624 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2631 * Save people from their own stupidity.
2633 if (conf->fragment_size < 100) conf->fragment_size = 100;
2635 if (!conf->private_key_file) {
2636 ERROR("TLS Server requires a private key file");
2640 if (!conf->certificate_file) {
2641 ERROR("TLS Server requires a certificate file");
2648 conf->ctx = tls_init_ctx(conf, 0);
2649 if (conf->ctx == NULL) {
2653 #ifdef HAVE_OPENSSL_OCSP_H
2655 * Initialize OCSP Revocation Store
2657 if (conf->ocsp_enable) {
2658 conf->ocsp_store = init_revocation_store(conf);
2659 if (conf->ocsp_store == NULL) goto error;
2661 #endif /*HAVE_OPENSSL_OCSP_H*/
2665 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2666 if (load_dh_params(conf->ctx, dh_file) < 0) {
2671 if (conf->verify_tmp_dir) {
2672 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2673 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2678 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2679 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2684 * Cache conf in cs in case we're asked to parse this again.
2686 cf_data_add(cs, "tls-conf", conf, NULL);
2691 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2693 fr_tls_server_conf_t *conf;
2695 conf = cf_data_find(cs, "tls-conf");
2697 DEBUG("Using cached TLS configuration from previous invocation");
2701 conf = tls_server_conf_alloc(cs);
2703 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2710 * Save people from their own stupidity.
2712 if (conf->fragment_size < 100) conf->fragment_size = 100;
2717 conf->ctx = tls_init_ctx(conf, 1);
2718 if (conf->ctx == NULL) {
2725 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2726 if (load_dh_params(conf->ctx, dh_file) < 0) {
2731 cf_data_add(cs, "tls-conf", conf, NULL);
2736 int tls_success(tls_session_t *ssn, REQUEST *request)
2738 VALUE_PAIR *vp, *vps = NULL;
2739 fr_tls_server_conf_t *conf;
2740 TALLOC_CTX *talloc_ctx;
2742 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2743 rad_assert(conf != NULL);
2745 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2748 * If there's no session resumption, delete the entry
2749 * from the cache. This means either it's disabled
2750 * globally for this SSL context, OR we were told to
2751 * disable it for this user.
2753 * This also means you can't turn it on just for one
2756 if ((!ssn->allow_session_resumption) ||
2757 (((vp = pairfind(request->config_items, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
2758 (vp->vp_integer == 0))) {
2759 SSL_CTX_remove_session(ssn->ctx,
2761 ssn->allow_session_resumption = false;
2764 * If we're in a resumed session and it's
2767 if (SSL_session_reused(ssn->ssl)) {
2768 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2772 * Else resumption IS allowed, so we store the
2773 * user data in the cache.
2775 } else if (!SSL_session_reused(ssn->ssl)) {
2778 char buffer[2 * MAX_SESSION_SIZE + 1];
2780 size = ssn->ssl->session->session_id_length;
2781 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2783 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2785 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2786 if (vp) pairadd(&vps, vp);
2788 vp = paircopy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2789 if (vp) pairadd(&vps, vp);
2791 vp = paircopy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
2792 if (vp) pairadd(&vps, vp);
2794 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2795 if (vp) pairadd(&vps, vp);
2797 vp = paircopy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2798 if (vp) pairadd(&vps, vp);
2800 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
2803 * Hmm... the certs should probably be session data.
2807 * @todo: some go into reply, others into
2810 pairadd(&vps, paircopy(talloc_ctx, *certs));
2814 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2815 SSL_SESSION_set_ex_data(ssn->ssl->session, fr_tls_ex_index_vps, vps);
2816 if (conf->session_cache_path) {
2817 /* write the VPs to the cache file */
2818 char filename[256], buf[1024];
2821 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
2822 FR_DIR_SEP, buffer);
2823 vp_file = fopen(filename, "w");
2824 if (vp_file == NULL) {
2825 RDEBUG2("Could not write session VPs to persistent cache: %s",
2826 fr_syserror(errno));
2829 /* generate a dummy user-style entry which is easy to read back */
2830 fprintf(vp_file, "# SSL cached session\n");
2831 fprintf(vp_file, "%s\n", buffer);
2832 for (vp = fr_cursor_init(&cursor, &vps);
2834 vp = fr_cursor_next(&cursor)) {
2835 vp_prints(buf, sizeof(buf), vp);
2836 fprintf(vp_file, "\t%s,\n", buf);
2842 RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2843 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2847 * Else the session WAS allowed. Copy the cached reply.
2851 char buffer[2 * MAX_SESSION_SIZE + 1];
2853 size = ssn->ssl->session->session_id_length;
2854 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2856 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2858 vps = SSL_SESSION_get_ex_data(ssn->ssl->session, fr_tls_ex_index_vps);
2860 RWDEBUG("No information in cached session %s", buffer);
2865 RDEBUG("Adding cached attributes for session %s:", buffer);
2866 rdebug_pair_list(L_DBG_LVL_1, request, vps, NULL);
2867 for (vp = fr_cursor_init(&cursor, &vps);
2869 vp = fr_cursor_next(&cursor)) {
2871 * TLS-* attrs get added back to
2874 if ((vp->da->vendor == 0) &&
2875 (vp->da->attr >= PW_TLS_CERT_SERIAL) &&
2876 (vp->da->attr <= PW_TLS_CLIENT_CERT_SUBJECT_ALT_NAME_UPN)) {
2877 pairadd(&request->packet->vps, paircopyvp(request->packet, vp));
2879 pairadd(&request->reply->vps, paircopyvp(request->reply, vp));
2883 if (conf->session_cache_path) {
2884 /* "touch" the cached session/vp file */
2887 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2888 conf->session_cache_path, FR_DIR_SEP, buffer);
2889 utime(filename, NULL);
2890 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2891 conf->session_cache_path, FR_DIR_SEP, buffer);
2892 utime(filename, NULL);
2896 * Mark the request as resumed.
2898 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2906 void tls_fail(tls_session_t *ssn)
2909 * Force the session to NOT be cached.
2911 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2914 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2921 * Decrypt the complete record.
2923 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2924 ssn->dirty_in.used);
2925 if (err != (int) ssn->dirty_in.used) {
2926 record_init(&ssn->dirty_in);
2927 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used, err);
2932 * Clear the dirty buffer now that we are done with it
2933 * and init the clean_out buffer to store decrypted data
2935 record_init(&ssn->dirty_in);
2936 record_init(&ssn->clean_out);
2939 * Read (and decrypt) the tunneled data from the
2940 * SSL session, and put it into the decrypted
2943 err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
2947 RDEBUG("SSL_read Error");
2949 code = SSL_get_error(ssn->ssl, err);
2951 case SSL_ERROR_WANT_READ:
2952 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2953 return FR_TLS_MORE_FRAGMENTS;
2955 case SSL_ERROR_WANT_WRITE:
2956 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2960 DEBUG("Error in fragmentation logic: %s", ERR_error_string(code, NULL));
2963 * FIXME: Call int_ssl_check?
2970 if (err == 0) RWDEBUG("No data inside of the tunnel");
2973 * Passed all checks, successfully decrypted data
2975 ssn->clean_out.used = err;
2982 * Acknowledge received is for one of the following messages sent earlier
2983 * 1. Handshake completed Message, so now send, EAP-Success
2984 * 2. Alert Message, now send, EAP-Failure
2985 * 3. Fragment Message, now send, next Fragment
2987 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2989 RDEBUG2("Received TLS ACK");
2992 RERROR("FAIL: Unexpected ACK received. Could not obtain session information");
2993 return FR_TLS_INVALID;
2995 if (ssn->info.initialized == 0) {
2996 RDEBUG("No SSL info available. Waiting for more SSL data");
2997 return FR_TLS_REQUEST;
2999 if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3000 RERROR("FAIL: ACK without earlier message");
3001 return FR_TLS_INVALID;
3004 switch (ssn->info.content_type) {
3006 RDEBUG2("ACK alert");
3010 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3011 RDEBUG2("ACK handshake is finished");
3014 * From now on all the content is
3015 * application data set it here as nobody else
3018 ssn->info.content_type = application_data;
3019 return FR_TLS_SUCCESS;
3020 } /* else more data to send */
3022 RDEBUG2("ACK handshake fragment handler");
3023 /* Fragmentation handler, send next fragment */
3024 return FR_TLS_REQUEST;
3026 case application_data:
3027 RDEBUG2("ACK handshake fragment handler in application data");
3028 return FR_TLS_REQUEST;
3031 * For the rest of the conditions, switch over
3032 * to the default section below.
3035 RERROR("Invalid ACK received: %d", ssn->info.content_type);
3037 return FR_TLS_INVALID;
3041 #endif /* WITH_TLS */