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 typedef struct libssl_defect {
63 /* Record critical defects in libssl here (newest first)*/
64 static libssl_defect_t libssl_defects[] =
67 .low = 0x010001000, /* 1.0.1 */
68 .high = 0x01000106f, /* 1.0.1f */
69 .id = "CVE-2014-0160",
71 .comment = "For more information see http://heartbleed.com"
76 static void record_init(record_t *buf);
77 static void record_close(record_t *buf);
78 static unsigned int record_plus(record_t *buf, void const *ptr,
80 static unsigned int record_minus(record_t *buf, void *ptr,
83 #ifdef PSK_MAX_IDENTITY_LEN
84 static bool identity_is_safe(const char *identity)
88 if (!identity) return true;
90 while ((c = *(identity++)) != '\0') {
91 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
92 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
104 * When a client uses TLS-PSK to talk to a server, this callback
105 * is used by the server to determine the PSK to use.
107 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
109 unsigned int max_psk_len)
111 unsigned int psk_len = 0;
112 fr_tls_server_conf_t *conf;
115 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
116 FR_TLS_EX_INDEX_CONF);
119 request = (REQUEST *)SSL_get_ex_data(ssl,
120 FR_TLS_EX_INDEX_REQUEST);
121 if (request && conf->psk_query) {
124 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
127 * The passed identity is weird. Deny it.
129 if (!identity_is_safe(identity)) {
130 RWDEBUG("Invalid characters in PSK identity %s", identity);
134 vp = pairmake_packet("TLS-PSK-Identity", identity, T_OP_SET);
137 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
140 RWDEBUG("PSK expansion returned an empty string.");
145 * The returned key is truncated at MORE than
146 * OpenSSL can handle. That way we can detect
147 * the truncation, and complain about it.
149 if (hex_len > (2 * max_psk_len)) {
150 RWDEBUG("Returned PSK is too long (%u > %u)",
151 (unsigned int) hex_len, 2 * max_psk_len);
156 * Leave the TLS-PSK-Identity in the request, and
157 * convert the expansion from printable string
160 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
164 * No REQUEST, or no dynamic query. Just look for a
167 if (strcmp(identity, conf->psk_identity) != 0) {
168 ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
173 psk_len = strlen(conf->psk_password);
174 if (psk_len > (2 * max_psk_len)) return 0;
176 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
179 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
180 char *identity, unsigned int max_identity_len,
181 unsigned char *psk, unsigned int max_psk_len)
183 unsigned int psk_len;
184 fr_tls_server_conf_t *conf;
186 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
187 FR_TLS_EX_INDEX_CONF);
190 psk_len = strlen(conf->psk_password);
191 if (psk_len > (2 * max_psk_len)) return 0;
193 strlcpy(identity, conf->psk_identity, max_identity_len);
195 return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
200 tls_session_t *tls_new_client_session(fr_tls_server_conf_t *conf, int fd)
203 tls_session_t *ssn = NULL;
206 ssn = talloc_zero(conf, tls_session_t);
207 if (!ssn) return NULL;
209 ssn->ctx = conf->ctx;
211 SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
213 ssn->ssl = SSL_new(ssn->ctx);
219 request = request_alloc(ssn);
220 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
223 * Add the message callback to identify what type of
224 * message/handshake is passed
226 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
227 SSL_set_msg_callback_arg(ssn->ssl, ssn);
228 SSL_set_info_callback(ssn->ssl, cbtls_info);
231 * Always verify the peer certificate.
233 DEBUG2("Requiring Server certificate");
234 verify_mode = SSL_VERIFY_PEER;
235 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
236 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
238 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
239 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
240 SSL_set_fd(ssn->ssl, fd);
241 if (SSL_connect(ssn->ssl) <= 0) {
243 while ((err = ERR_get_error())) {
244 ERROR("tls: %s", ERR_error_string(err, NULL));
252 ssn->offset = conf->fragment_size;
257 static int _tls_session_free(tls_session_t *ssn)
260 * Free any opaque TTLS or PEAP data.
262 if ((ssn->opaque) && (ssn->free_opaque)) {
263 ssn->free_opaque(ssn->opaque);
272 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
274 tls_session_t *state = NULL;
279 rad_assert(request != NULL);
282 * Manually flush the sessions every so often. If HALF
283 * of the session lifetime has passed since we last
284 * flushed, then flush it again.
286 * FIXME: Also do it every N sessions?
288 if (conf->session_cache_enable &&
289 ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
290 RDEBUG2("Flushing SSL sessions (of #%ld)",
291 SSL_CTX_sess_number(conf->ctx));
293 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
294 conf->session_last_flushed = request->timestamp;
297 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
298 ERROR("SSL: Error creating new SSL: %s",
299 ERR_error_string(ERR_get_error(), NULL));
303 /* We use the SSL's "app_data" to indicate a call-back */
304 SSL_set_app_data(new_tls, NULL);
306 state = talloc_zero(ctx, tls_session_t);
308 talloc_set_destructor(state, _tls_session_free);
310 state->ctx = conf->ctx;
311 state->ssl = new_tls;
314 * Initialize callbacks
316 state->record_init = record_init;
317 state->record_close = record_close;
318 state->record_plus = record_plus;
319 state->record_minus = record_minus;
322 * Create & hook the BIOs to handle the dirty side of the
323 * SSL. This is *very important* as we want to handle
324 * the transmission part. Now the only IO interface
325 * that SSL is aware of, is our defined BIO buffers.
327 * This means that all SSL IO is done to/from memory,
328 * and we can update those BIOs from the packets we've
331 state->into_ssl = BIO_new(BIO_s_mem());
332 state->from_ssl = BIO_new(BIO_s_mem());
333 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
336 * Add the message callback to identify what type of
337 * message/handshake is passed
339 SSL_set_msg_callback(new_tls, cbtls_msg);
340 SSL_set_msg_callback_arg(new_tls, state);
341 SSL_set_info_callback(new_tls, cbtls_info);
344 * In Server mode we only accept.
346 SSL_set_accept_state(state->ssl);
349 * Verify the peer certificate, if asked.
352 RDEBUG2("Requiring client certificate");
353 verify_mode = SSL_VERIFY_PEER;
354 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
355 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
357 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
359 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
360 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
361 state->length_flag = conf->include_length;
364 * We use default fragment size, unless the Framed-MTU
365 * tells us it's too big. Note that we do NOT account
366 * for the EAP-TLS headers if conf->fragment_size is
367 * large, because that config item looks to be confusing.
369 * i.e. it should REALLY be called MTU, and the code here
370 * should figure out what that means for TLS fragment size.
371 * asking the administrator to know the internal details
372 * of EAP-TLS in order to calculate fragment sizes is
375 state->offset = conf->fragment_size;
376 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
377 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
378 state->offset = vp->vp_integer;
381 if (conf->session_cache_enable) {
382 state->allow_session_resumption = 1; /* otherwise it's zero */
391 * Print out some text describing the error.
393 static int int_ssl_check(REQUEST *request, SSL *s, int ret, char const *text)
398 if ((l = ERR_get_error()) != 0) {
399 char const *p = ERR_error_string(l, NULL);
401 if (request && p) REDEBUG("SSL says: %s", p);
403 e = SSL_get_error(s, ret);
407 * These seem to be harmless and already "dealt
408 * with" by our non-blocking environment. NB:
409 * "ZERO_RETURN" is the clean "error"
410 * indicating a successfully closed SSL
411 * tunnel. We let this happen because our IO
412 * loop should not appear to have broken on
413 * this condition - and outside the IO loop, the
414 * "shutdown" state is checked.
416 * Don't print anything if we ignore the error.
419 case SSL_ERROR_WANT_READ:
420 case SSL_ERROR_WANT_WRITE:
421 case SSL_ERROR_WANT_X509_LOOKUP:
422 case SSL_ERROR_ZERO_RETURN:
426 * These seem to be indications of a genuine
427 * error that should result in the SSL tunnel
428 * being regarded as "dead".
430 case SSL_ERROR_SYSCALL:
431 ERROR("SSL: %s failed in a system call (%d), TLS session fails.",
436 ERROR("SSL: %s failed inside of TLS (%d), TLS session fails.",
442 * For any other errors that (a) exist, and (b)
443 * crop up - we need to interpret what to do with
444 * them - so "politely inform" the caller that
445 * the code needs updating here.
447 ERROR("SSL: FATAL SSL error ..... %d\n", e);
455 * We are the server, we always get the dirty data
456 * (Handshake data is also considered as dirty data)
457 * During handshake, since SSL API handles itself,
458 * After clean-up, dirty_out will be filled with
459 * the data required for handshaking. So we check
460 * if dirty_out is empty then we simply send it back.
461 * As of now, if handshake is successful, then we keep going,
464 * Fill the Bio with the dirty data to clean it
465 * Get the cleaned data from SSL, if it is not Handshake data
467 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
471 if (ssn->invalid_hb_used) return 0;
473 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
474 if (err != (int) ssn->dirty_in.used) {
475 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
477 record_init(&ssn->dirty_in);
480 record_init(&ssn->dirty_in);
482 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
483 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
485 ssn->clean_out.used += err;
489 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
493 /* Some Extra STATE information for easy debugging */
494 if (SSL_is_init_finished(ssn->ssl)) {
495 DEBUG2("SSL Connection Established\n");
497 if (SSL_in_init(ssn->ssl)) {
498 DEBUG2("In SSL Handshake Phase\n");
500 if (SSL_in_before(ssn->ssl)) {
501 DEBUG2("Before SSL Handshake Phase\n");
503 if (SSL_in_accept_init(ssn->ssl)) {
504 DEBUG2("In SSL Accept mode \n");
506 if (SSL_in_connect_init(ssn->ssl)) {
507 DEBUG2("In SSL Connect mode \n");
510 err = BIO_ctrl_pending(ssn->from_ssl);
512 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
513 sizeof(ssn->dirty_out.data));
515 ssn->dirty_out.used = err;
517 } else if (BIO_should_retry(ssn->from_ssl)) {
518 record_init(&ssn->dirty_in);
519 DEBUG2(" tls: Asking for more data in tunnel");
523 int_ssl_check(request, ssn->ssl, err, "BIO_read");
524 record_init(&ssn->dirty_in);
528 DEBUG2("SSL Application Data");
529 /* Its clean application data, do whatever we want */
530 record_init(&ssn->clean_out);
533 /* We are done with dirty_in, reinitialize it */
534 record_init(&ssn->dirty_in);
539 * Take cleartext user data, and encrypt it into the output buffer,
540 * to send to the client at the other end of the SSL connection.
542 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
547 * If there's un-encrypted data in 'clean_in', then write
548 * that data to the SSL session, and then call the BIO function
549 * to get that encrypted data from the SSL session, into
550 * a buffer which we can then package into an EAP packet.
552 * Based on Server's logic this clean_in is expected to
553 * contain the data to send to the client.
555 if (ssn->clean_in.used > 0) {
558 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
559 record_minus(&ssn->clean_in, NULL, written);
561 /* Get the dirty data from Bio to send it */
562 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
563 sizeof(ssn->dirty_out.data));
565 ssn->dirty_out.used = err;
567 int_ssl_check(request, ssn->ssl, err, "handshake_send");
574 void session_init(tls_session_t *ssn)
577 ssn->into_ssl = ssn->from_ssl = NULL;
578 record_init(&ssn->clean_in);
579 record_init(&ssn->clean_out);
580 record_init(&ssn->dirty_in);
581 record_init(&ssn->dirty_out);
583 memset(&ssn->info, 0, sizeof(ssn->info));
587 ssn->tls_msg_len = 0;
588 ssn->length_flag = 0;
590 ssn->free_opaque = NULL;
593 void session_close(tls_session_t *ssn)
595 SSL_set_quiet_shutdown(ssn->ssl, 1);
596 SSL_shutdown(ssn->ssl);
603 record_close(&ssn->clean_in);
604 record_close(&ssn->clean_out);
605 record_close(&ssn->dirty_in);
606 record_close(&ssn->dirty_out);
610 static void record_init(record_t *rec)
615 static void record_close(record_t *rec)
622 * Copy data to the intermediate buffer, before we send
625 static unsigned int record_plus(record_t *rec, void const *ptr,
628 unsigned int added = MAX_RECORD_SIZE - rec->used;
634 memcpy(rec->data + rec->used, ptr, added);
640 * Take data from the buffer, and give it to the caller.
642 static unsigned int record_minus(record_t *rec, void *ptr,
645 unsigned int taken = rec->used;
652 memcpy(ptr, rec->data, taken);
656 * This is pretty bad...
659 memmove(rec->data, rec->data + taken, rec->used);
663 void tls_session_information(tls_session_t *tls_session)
665 char const *str_write_p, *str_version, *str_content_type = "";
666 char const *str_details1 = "", *str_details2= "";
670 * Don't print this out in the normal course of
673 if (debug_flag == 0) {
677 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
679 switch (tls_session->info.version) {
681 str_version = "SSL 2.0";
684 str_version = "SSL 3.0 ";
687 str_version = "TLS 1.0 ";
690 str_version = "Unknown TLS version";
694 if (tls_session->info.version == SSL3_VERSION ||
695 tls_session->info.version == TLS1_VERSION) {
696 switch (tls_session->info.content_type) {
697 case SSL3_RT_CHANGE_CIPHER_SPEC:
698 str_content_type = "ChangeCipherSpec";
701 str_content_type = "Alert";
703 case SSL3_RT_HANDSHAKE:
704 str_content_type = "Handshake";
706 case SSL3_RT_APPLICATION_DATA:
707 str_content_type = "ApplicationData";
710 str_content_type = "UnknownContentType";
714 if (tls_session->info.content_type == SSL3_RT_ALERT) {
715 str_details1 = ", ???";
717 if (tls_session->info.record_len == 2) {
719 switch (tls_session->info.alert_level) {
720 case SSL3_AL_WARNING:
721 str_details1 = ", warning";
724 str_details1 = ", fatal";
728 str_details2 = " ???";
729 switch (tls_session->info.alert_description) {
730 case SSL3_AD_CLOSE_NOTIFY:
731 str_details2 = " close_notify";
733 case SSL3_AD_UNEXPECTED_MESSAGE:
734 str_details2 = " unexpected_message";
736 case SSL3_AD_BAD_RECORD_MAC:
737 str_details2 = " bad_record_mac";
739 case TLS1_AD_DECRYPTION_FAILED:
740 str_details2 = " decryption_failed";
742 case TLS1_AD_RECORD_OVERFLOW:
743 str_details2 = " record_overflow";
745 case SSL3_AD_DECOMPRESSION_FAILURE:
746 str_details2 = " decompression_failure";
748 case SSL3_AD_HANDSHAKE_FAILURE:
749 str_details2 = " handshake_failure";
751 case SSL3_AD_BAD_CERTIFICATE:
752 str_details2 = " bad_certificate";
754 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
755 str_details2 = " unsupported_certificate";
757 case SSL3_AD_CERTIFICATE_REVOKED:
758 str_details2 = " certificate_revoked";
760 case SSL3_AD_CERTIFICATE_EXPIRED:
761 str_details2 = " certificate_expired";
763 case SSL3_AD_CERTIFICATE_UNKNOWN:
764 str_details2 = " certificate_unknown";
766 case SSL3_AD_ILLEGAL_PARAMETER:
767 str_details2 = " illegal_parameter";
769 case TLS1_AD_UNKNOWN_CA:
770 str_details2 = " unknown_ca";
772 case TLS1_AD_ACCESS_DENIED:
773 str_details2 = " access_denied";
775 case TLS1_AD_DECODE_ERROR:
776 str_details2 = " decode_error";
778 case TLS1_AD_DECRYPT_ERROR:
779 str_details2 = " decrypt_error";
781 case TLS1_AD_EXPORT_RESTRICTION:
782 str_details2 = " export_restriction";
784 case TLS1_AD_PROTOCOL_VERSION:
785 str_details2 = " protocol_version";
787 case TLS1_AD_INSUFFICIENT_SECURITY:
788 str_details2 = " insufficient_security";
790 case TLS1_AD_INTERNAL_ERROR:
791 str_details2 = " internal_error";
793 case TLS1_AD_USER_CANCELLED:
794 str_details2 = " user_canceled";
796 case TLS1_AD_NO_RENEGOTIATION:
797 str_details2 = " no_renegotiation";
803 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
804 str_details1 = "???";
806 if (tls_session->info.record_len > 0)
807 switch (tls_session->info.handshake_type) {
808 case SSL3_MT_HELLO_REQUEST:
809 str_details1 = ", HelloRequest";
811 case SSL3_MT_CLIENT_HELLO:
812 str_details1 = ", ClientHello";
814 case SSL3_MT_SERVER_HELLO:
815 str_details1 = ", ServerHello";
817 case SSL3_MT_CERTIFICATE:
818 str_details1 = ", Certificate";
820 case SSL3_MT_SERVER_KEY_EXCHANGE:
821 str_details1 = ", ServerKeyExchange";
823 case SSL3_MT_CERTIFICATE_REQUEST:
824 str_details1 = ", CertificateRequest";
826 case SSL3_MT_SERVER_DONE:
827 str_details1 = ", ServerHelloDone";
829 case SSL3_MT_CERTIFICATE_VERIFY:
830 str_details1 = ", CertificateVerify";
832 case SSL3_MT_CLIENT_KEY_EXCHANGE:
833 str_details1 = ", ClientKeyExchange";
835 case SSL3_MT_FINISHED:
836 str_details1 = ", Finished";
842 snprintf(tls_session->info.info_description,
843 sizeof(tls_session->info.info_description),
844 "%s %s%s [length %04lx]%s%s\n",
845 str_write_p, str_version, str_content_type,
846 (unsigned long)tls_session->info.record_len,
847 str_details1, str_details2);
849 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
851 RDEBUG2("%s", tls_session->info.info_description);
853 DEBUG2("%s", tls_session->info.info_description);
857 static CONF_PARSER cache_config[] = {
858 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
859 { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
860 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
861 { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
862 { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
863 { NULL, -1, 0, NULL, NULL } /* end the list */
866 static CONF_PARSER verify_config[] = {
867 { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
868 { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
869 { NULL, -1, 0, NULL, NULL } /* end the list */
872 #ifdef HAVE_OPENSSL_OCSP_H
873 static CONF_PARSER ocsp_config[] = {
874 { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
875 { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
876 { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
877 { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
878 { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
879 { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "yes" },
880 { NULL, -1, 0, NULL, NULL } /* end the list */
884 static CONF_PARSER tls_server_config[] = {
885 { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
886 { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
887 { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
888 { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
889 { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
890 { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
891 { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
892 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
893 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
894 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
895 { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
896 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
897 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
898 #ifdef PSK_MAX_IDENTITY_LEN
899 { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
900 { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
901 { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
903 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
904 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
905 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
906 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
907 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
908 { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
909 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
910 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
911 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
912 { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
914 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
915 #ifndef OPENSSL_NO_ECDH
916 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
920 { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
922 { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
924 #ifdef HAVE_OPENSSL_OCSP_H
925 { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
928 { NULL, -1, 0, NULL, NULL } /* end the list */
932 static CONF_PARSER tls_client_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, fr_tls_server_conf_t, ca_path), NULL },
939 { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
940 { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
941 { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
942 { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
943 { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
944 { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
945 { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
946 { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
947 { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
948 { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
949 { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
950 { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
951 { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
953 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
954 #ifndef OPENSSL_NO_ECDH
955 { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
959 { NULL, -1, 0, NULL, NULL } /* end the list */
964 * TODO: Check for the type of key exchange * like conf->dh_key
966 static int load_dh_params(SSL_CTX *ctx, char *file)
973 if ((bio = BIO_new_file(file, "r")) == NULL) {
974 ERROR("tls: Unable to open DH file - %s", file);
978 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
981 WARN("tls: Unable to set DH parameters. DH cipher suites may not work!");
982 WARN("Fix this by running the OpenSSL command listed in eap.conf");
986 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
987 ERROR("tls: Unable to set DH parameters");
998 * Generate ephemeral RSA keys.
1000 static int generate_eph_rsa_key(SSL_CTX *ctx)
1004 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
1006 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
1007 ERROR("tls: Couldn't set ephemeral RSA key");
1015 /* index we use to store cached session VPs
1016 * needs to be dynamic so we can supply a "free" function
1018 static int FR_TLS_EX_INDEX_VPS = -1;
1019 int FR_TLS_EX_INDEX_CERTS = -1;
1022 * Print debugging messages, and free data.
1024 * FIXME: Write sessions to some long-term storage, so that
1025 * session resumption can still occur after the server
1028 #define MAX_SESSION_SIZE (256)
1030 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1033 char buffer[2 * MAX_SESSION_SIZE + 1];
1034 fr_tls_server_conf_t *conf;
1036 size = sess->session_id_length;
1037 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1039 fr_bin2hex(buffer, sess->session_id, size);
1041 DEBUG2(" SSL: Removing session %s from the cache", buffer);
1042 conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1043 if (conf && conf->session_cache_path) {
1047 /* remove session and any cached VPs */
1048 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1049 conf->session_cache_path, FR_DIR_SEP, buffer);
1050 rv = unlink(filename);
1052 DEBUG2(" SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
1054 /* VPs might be absent; might not have been written to disk yet */
1055 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1056 conf->session_cache_path, FR_DIR_SEP, buffer);
1063 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1066 char buffer[2 * MAX_SESSION_SIZE + 1];
1067 fr_tls_server_conf_t *conf;
1068 unsigned char *sess_blob = NULL;
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: adding session %s to cache", buffer);
1077 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1078 if (conf && conf->session_cache_path) {
1079 int fd, rv, todo, blob_len;
1083 /* find out what length data we need */
1084 blob_len = i2d_SSL_SESSION(sess, NULL);
1086 /* something went wrong */
1087 DEBUG2(" SSL: could not find buffer length to persist session");
1092 /* Do not convert to TALLOC - Thread safety */
1093 /* alloc and convert to ASN.1 */
1094 sess_blob = malloc(blob_len);
1096 DEBUG2(" SSL: could not allocate buffer len=%d to persist session", blob_len);
1099 /* openssl mutates &p */
1101 rv = i2d_SSL_SESSION(sess, &p);
1102 if (rv != blob_len) {
1103 DEBUG2(" SSL: could not persist session");
1107 /* open output file */
1108 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1109 conf->session_cache_path, FR_DIR_SEP, buffer);
1110 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1112 DEBUG2(" SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1119 rv = write(fd, p, todo);
1121 DEBUG2(" SSL: failed writing session: %s", fr_syserror(errno));
1129 DEBUG2(" SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1138 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1139 unsigned char *data, int len,
1143 char buffer[2 * MAX_SESSION_SIZE + 1];
1144 fr_tls_server_conf_t *conf;
1145 TALLOC_CTX *talloc_ctx;
1147 SSL_SESSION *sess = NULL;
1148 unsigned char *sess_data = NULL;
1149 PAIR_LIST *pairlist = NULL;
1152 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1154 fr_bin2hex(buffer, data, size);
1156 DEBUG2(" SSL: Client requested cached session %s", buffer);
1158 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1159 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1160 if (conf && conf->session_cache_path) {
1167 /* read in the cached VPs from the .vps file */
1168 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1169 conf->session_cache_path, FR_DIR_SEP, buffer);
1170 rv = pairlist_read(NULL, filename, &pairlist, 1);
1172 /* not safe to un-persist a session w/o VPs */
1173 DEBUG2(" SSL: could not load persisted VPs for session %s", buffer);
1177 /* load the actual SSL session */
1178 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1179 conf->session_cache_path, FR_DIR_SEP, buffer);
1180 fd = open(filename, O_RDONLY);
1182 DEBUG2(" SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1186 rv = fstat(fd, &st);
1188 DEBUG2(" SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1193 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1195 DEBUG2(" SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1203 rv = read(fd, p, todo);
1205 DEBUG2(" SSL: could not read from persisted session: %s", fr_syserror(errno));
1214 /* openssl mutates &p */
1216 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1219 DEBUG2(" SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1223 /* cache the VPs into the session */
1224 vp = paircopy(talloc_ctx, pairlist->reply);
1225 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1226 DEBUG2(" SSL: Successfully restored session %s", buffer);
1229 if (sess_data) talloc_free(sess_data);
1230 if (pairlist) pairlist_free(&pairlist);
1236 #ifdef HAVE_OPENSSL_OCSP_H
1238 * This function extracts the OCSP Responder URL
1239 * from an existing x509 certificate.
1241 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1242 char **ppath, int *pssl)
1246 AUTHORITY_INFO_ACCESS *aia;
1247 ACCESS_DESCRIPTION *ad;
1249 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1251 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1252 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1253 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1254 if (ad->location->type == GEN_URI) {
1255 if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1256 phost, pport, ppath, pssl))
1265 * This function sends a OCSP request to a defined OCSP responder
1266 * and checks the OCSP response for correctness.
1269 /* Maximum leeway in validity period: default 5 minutes */
1270 #define MAX_VALIDITY_PERIOD (5 * 60)
1272 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1273 fr_tls_server_conf_t *conf)
1275 OCSP_CERTID *certid;
1277 OCSP_RESPONSE *resp = NULL;
1278 OCSP_BASICRESP *bresp = NULL;
1283 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1284 BIO *cbio, *bio_out;
1287 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1289 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1293 struct timeval when;
1297 * Create OCSP Request
1299 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1300 req = OCSP_REQUEST_new();
1301 OCSP_request_add0_id(req, certid);
1302 if(conf->ocsp_use_nonce) {
1303 OCSP_request_add1_nonce(req, NULL, 8);
1307 * Send OCSP Request and get OCSP Response
1310 /* Get OCSP responder URL */
1311 if (conf->ocsp_override_url) {
1314 memcpy(&url, &conf->ocsp_url, sizeof(url));
1315 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1316 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1319 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1322 if (!host || !port || !path) {
1323 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP");
1328 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1330 /* Setup BIO socket to OCSP responder */
1331 cbio = BIO_new_connect(host);
1333 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1335 BIO_set_conn_port(cbio, port);
1336 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1337 BIO_do_connect(cbio);
1339 /* Send OCSP request and wait for response */
1340 resp = OCSP_sendreq_bio(cbio, path, req);
1342 ERROR("Couldn't get OCSP response");
1347 if (conf->ocsp_timeout)
1348 BIO_set_nbio(cbio, 1);
1350 rc = BIO_do_connect(cbio);
1351 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1352 ERROR("Couldn't connect to OCSP responder");
1357 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1359 ERROR("Couldn't send OCSP request");
1364 gettimeofday(&when, NULL);
1365 when.tv_sec += conf->ocsp_timeout;
1368 rc = OCSP_sendreq_nbio(&resp, ctx);
1369 if (conf->ocsp_timeout) {
1370 gettimeofday(&now, NULL);
1371 if (!timercmp(&now, &when, <))
1374 } while ((rc == -1) && BIO_should_retry(cbio));
1376 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1377 ERROR("OCSP response timed out");
1382 OCSP_REQ_CTX_free(ctx);
1385 ERROR("Couldn't get OCSP response");
1391 /* Verify OCSP response status */
1392 status = OCSP_response_status(resp);
1393 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1394 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1395 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1398 bresp = OCSP_response_get1_basic(resp);
1399 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1400 ERROR("OCSP response has wrong nonce value");
1403 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1404 ERROR("Couldn't verify OCSP basic response");
1408 /* Verify OCSP cert status */
1409 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1410 &rev, &thisupd, &nextupd)) {
1411 ERROR("No Status found.\n");
1415 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1416 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1417 ERR_print_errors(bio_out);
1420 BIO_puts(bio_out, "\tThis Update: ");
1421 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1422 BIO_puts(bio_out, "\n");
1424 BIO_puts(bio_out, "\tNext Update: ");
1425 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1426 BIO_puts(bio_out, "\n");
1430 case V_OCSP_CERTSTATUS_GOOD:
1431 DEBUG2("[oscp] --> Cert status: good");
1436 /* REVOKED / UNKNOWN */
1437 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1439 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1440 BIO_puts(bio_out, "\tRevocation Time: ");
1441 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1442 BIO_puts(bio_out, "\n");
1447 /* Free OCSP Stuff */
1448 OCSP_REQUEST_free(req);
1449 OCSP_RESPONSE_free(resp);
1454 OCSP_BASICRESP_free(bresp);
1459 DEBUG2("[ocsp] --> Certificate is valid!");
1462 if (conf->ocsp_softfail) {
1463 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1464 DEBUG2("[ocsp] --> Warning! This may be insecure");
1467 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1472 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1478 #endif /* HAVE_OPENSSL_OCSP_H */
1481 * For creating certificate attributes.
1483 static char const *cert_attr_names[8][2] = {
1484 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1485 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1486 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1487 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1488 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1489 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
1490 { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
1491 { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
1494 #define FR_TLS_SERIAL (0)
1495 #define FR_TLS_EXPIRATION (1)
1496 #define FR_TLS_SUBJECT (2)
1497 #define FR_TLS_ISSUER (3)
1498 #define FR_TLS_CN (4)
1499 #define FR_TLS_SAN_EMAIL (5)
1500 #define FR_TLS_SAN_DNS (6)
1501 #define FR_TLS_SAN_UPN (7)
1504 * Before trusting a certificate, you must make sure that the
1505 * certificate is 'valid'. There are several steps that your
1506 * application can take in determining if a certificate is
1507 * valid. Commonly used steps are:
1509 * 1.Verifying the certificate's signature, and verifying that
1510 * the certificate has been issued by a trusted Certificate
1513 * 2.Verifying that the certificate is valid for the present date
1514 * (i.e. it is being presented within its validity dates).
1516 * 3.Verifying that the certificate has not been revoked by its
1517 * issuing Certificate Authority, by checking with respect to a
1518 * Certificate Revocation List (CRL).
1520 * 4.Verifying that the credentials presented by the certificate
1521 * fulfill additional requirements specific to the application,
1522 * such as with respect to access control lists or with respect
1523 * to OCSP (Online Certificate Status Processing).
1525 * NOTE: This callback will be called multiple times based on the
1526 * depth of the root certificate chain
1528 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1530 char subject[1024]; /* Used for the subject name */
1531 char issuer[1024]; /* Used for the issuer name */
1532 char attribute[1024];
1534 char common_name[1024];
1538 X509_CINF *client_inf;
1539 STACK_OF(X509_EXTENSION) *ext_list;
1541 int err, depth, lookup, loc;
1542 fr_tls_server_conf_t *conf;
1545 ASN1_INTEGER *sn = NULL;
1546 ASN1_TIME *asn_time = NULL;
1549 #ifdef HAVE_OPENSSL_OCSP_H
1550 X509_STORE *ocsp_store = NULL;
1553 TALLOC_CTX *talloc_ctx;
1555 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1556 err = X509_STORE_CTX_get_error(ctx);
1557 depth = X509_STORE_CTX_get_error_depth(ctx);
1562 * Log client/issuing cert. If there's an error, log
1565 if ((lookup > 1) && !my_ok) lookup = 1;
1568 * Retrieve the pointer to the SSL of the connection currently treated
1569 * and the application specific data stored into the SSL object.
1571 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1572 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1573 if (!conf) return 1;
1575 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1576 rad_assert(request != NULL);
1577 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1579 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1580 #ifdef HAVE_OPENSSL_OCSP_H
1581 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1584 talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1587 * Get the Serial Number
1590 sn = X509_get_serialNumber(client_cert);
1593 * For this next bit, we create the attributes *only* if
1594 * we're at the client or issuing certificate, AND we
1595 * have a user identity. i.e. we don't create the
1596 * attributes for RadSec connections.
1598 if (certs && identity &&
1599 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1603 for (i = 0; i < sn->length; i++) {
1604 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1607 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1612 * Get the Expiration Date
1615 asn_time = X509_get_notAfter(client_cert);
1616 if (certs && identity && (lookup <= 1) && asn_time &&
1617 (asn_time->length < (int) sizeof(buf))) {
1618 memcpy(buf, (char*) asn_time->data, asn_time->length);
1619 buf[asn_time->length] = '\0';
1620 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1624 * Get the Subject & Issuer
1626 subject[0] = issuer[0] = '\0';
1627 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1629 subject[sizeof(subject) - 1] = '\0';
1630 if (certs && identity && (lookup <= 1) && subject[0]) {
1631 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1634 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1636 issuer[sizeof(issuer) - 1] = '\0';
1637 if (certs && identity && (lookup <= 1) && issuer[0]) {
1638 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1642 * Get the Common Name, if there is a subject.
1644 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1645 NID_commonName, common_name, sizeof(common_name));
1646 common_name[sizeof(common_name) - 1] = '\0';
1647 if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1648 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1652 * Get the RFC822 Subject Alternative Name
1654 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1655 if (certs && (lookup <= 1) && (loc >= 0)) {
1656 X509_EXTENSION *ext = NULL;
1657 GENERAL_NAMES *names = NULL;
1660 if ((ext = X509_get_ext(client_cert, loc)) &&
1661 (names = X509V3_EXT_d2i(ext))) {
1662 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1663 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1665 switch (name->type) {
1668 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1669 (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1671 #endif /* GEN_EMAIL */
1674 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1675 (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1677 #endif /* GEN_DNS */
1678 #ifdef GEN_OTHERNAME
1680 /* look for a MS UPN */
1681 if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1682 /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1683 if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1684 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1685 (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1688 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)\n");
1693 #endif /* GEN_OTHERNAME */
1695 /* XXX TODO handle other SAN types */
1701 sk_GENERAL_NAME_free(names);
1705 * If the CRL has expired, that might still be OK.
1708 (conf->allow_expired_crl) &&
1709 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1711 X509_STORE_CTX_set_error( ctx, 0 );
1715 char const *p = X509_verify_cert_error_string(err);
1716 ERROR("--> verify error:num=%d:%s\n",err, p);
1717 REDEBUG("SSL says error %d : %s", err, p);
1722 client_inf = client_cert->cert_info;
1723 ext_list = client_inf->extensions;
1729 * Grab the X509 extensions, and create attributes out of them.
1730 * For laziness, we re-use the OpenSSL names
1732 if (sk_X509_EXTENSION_num(ext_list) > 0) {
1737 out = BIO_new(BIO_s_mem());
1738 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1740 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1742 X509_EXTENSION *ext;
1745 ext = sk_X509_EXTENSION_value(ext_list, i);
1747 obj = X509_EXTENSION_get_object(ext);
1748 i2a_ASN1_OBJECT(out, obj);
1749 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1750 if (len <= 0) continue;
1752 attribute[16 + len] = '\0';
1754 X509V3_EXT_print(out, ext, 0, 0);
1755 len = BIO_read(out, value , sizeof(value) - 1);
1756 if (len <= 0) continue;
1761 * Mash the OpenSSL name to our name, and
1762 * create the attribute.
1764 for (p = value + 16; *p != '\0'; p++) {
1765 if (*p == ' ') *p = '-';
1768 vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1769 if (vp) debug_pair_list(vp);
1775 switch (ctx->error) {
1777 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1778 ERROR("issuer= %s\n", issuer);
1780 case X509_V_ERR_CERT_NOT_YET_VALID:
1781 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1782 ERROR("notBefore=");
1784 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1787 case X509_V_ERR_CERT_HAS_EXPIRED:
1788 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1791 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1797 * If we're at the actual client cert, apply additional
1802 * If the conf tells us to, check cert issuer
1803 * against the specified value and fail
1804 * verification if they don't match.
1806 if (conf->check_cert_issuer &&
1807 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1808 AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1813 * If the conf tells us to, check the CN in the
1814 * cert against xlat'ed value, but only if the
1815 * previous checks passed.
1817 if (my_ok && conf->check_cert_cn) {
1818 if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1819 /* if this fails, fail the verification */
1822 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1823 if (strcmp(cn_str, common_name) != 0) {
1824 AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1828 } /* check_cert_cn */
1830 #ifdef HAVE_OPENSSL_OCSP_H
1831 if (my_ok && conf->ocsp_enable){
1832 RDEBUG2("--> Starting OCSP Request");
1833 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1834 ERROR("Couldn't get issuer_cert for %s", common_name);
1836 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1840 while (conf->verify_client_cert_cmd) {
1845 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1846 conf->verify_tmp_dir, progname);
1847 fd = mkstemp(filename);
1849 RDEBUG("Failed creating file in %s: %s",
1850 conf->verify_tmp_dir, fr_syserror(errno));
1854 fp = fdopen(fd, "w");
1857 RDEBUG("Failed opening file %s: %s",
1858 filename, fr_syserror(errno));
1862 if (!PEM_write_X509(fp, client_cert)) {
1864 RDEBUG("Failed writing certificate to file");
1869 if (!pairmake_packet("TLS-Client-Cert-Filename",
1870 filename, T_OP_SET)) {
1871 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1876 RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1877 if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1878 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1879 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1882 RDEBUG("Client certificate CN %s passed external validation", common_name);
1893 if (debug_flag > 0) {
1894 RDEBUG2("chain-depth=%d, ", depth);
1895 RDEBUG2("error=%d", err);
1897 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1898 RDEBUG2("--> BUF-Name = %s", common_name);
1899 RDEBUG2("--> subject = %s", subject);
1900 RDEBUG2("--> issuer = %s", issuer);
1901 RDEBUG2("--> verify return:%d", my_ok);
1907 #ifdef HAVE_OPENSSL_OCSP_H
1909 * Create Global X509 revocation store and use it to verify
1912 * - Load the trusted CAs
1913 * - Load the trusted issuer certificates
1915 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1917 X509_STORE *store = NULL;
1919 store = X509_STORE_new();
1921 /* Load the CAs we trust */
1922 if (conf->ca_file || conf->ca_path)
1923 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1924 ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1925 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1929 #ifdef X509_V_FLAG_CRL_CHECK
1930 if (conf->check_crl)
1931 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1935 #endif /* HAVE_OPENSSL_OCSP_H */
1937 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1938 #ifndef OPENSSL_NO_ECDH
1939 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1944 if (!ecdh_curve || !*ecdh_curve) return 0;
1946 nid = OBJ_sn2nid(ecdh_curve);
1948 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1952 ecdh = EC_KEY_new_by_curve_name(nid);
1954 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1958 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1960 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1970 * DIE OPENSSL DIE DIE DIE
1972 * What a palaver, just to free some data attached the
1973 * session. We need to do this because the "remove" callback
1974 * is called when refcount > 0 sometimes, if another thread
1975 * is using the session
1977 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1978 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1979 UNUSED long argl, UNUSED void *argp)
1981 VALUE_PAIR *vp = data_ptr;
1984 DEBUG2(" Freeing cached session VPs");;
1989 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
1990 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1991 UNUSED long argl, UNUSED void *argp)
1993 VALUE_PAIR **certs = data_ptr;
1996 DEBUG2(" Freeing cached session Certificates");
2001 /** Add all the default ciphers and message digests reate our context.
2003 * This should be called exactly once from main, before reading the main config
2004 * or initialising any modules.
2006 void tls_global_init(void)
2008 SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
2009 SSL_library_init(); /* initialize library */
2010 OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2011 OPENSSL_config(NULL);
2014 /** Check for vulnerable versions of libssl
2016 * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2017 * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2019 int tls_global_version_check(char const *acknowledged)
2023 if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2027 /* Check for bad versions */
2028 v = (uint64_t) SSLeay();
2030 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2031 libssl_defect_t *defect = &libssl_defects[i];
2033 if ((v >= defect->low) && (v <= defect->high)) {
2034 ERROR("Refusing to start with libssl version %s (in range %s)",
2035 ssl_version(), ssl_version_range(defect->low, defect->high));
2036 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2037 ERROR("%s", defect->comment);
2044 INFO("Once you have verified libssl has been correctly patched, "
2045 "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2053 /** Free any memory alloced by libssl
2056 void tls_global_cleanup(void)
2058 ERR_remove_state(0);
2060 CONF_modules_unload(1);
2063 CRYPTO_cleanup_all_ex_data();
2067 * Create Global context SSL and use it in every new session
2069 * - Load the trusted CAs
2070 * - Load the Private key & the certificate
2071 * - Set the Context options & Verify options
2073 static SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2076 X509_STORE *certstore;
2077 int verify_mode = SSL_VERIFY_NONE;
2078 int ctx_options = 0;
2082 * SHA256 is in all versions of OpenSSL, but isn't
2083 * initialized by default. It's needed for WiMAX
2086 #ifdef HAVE_OPENSSL_EVP_SHA256
2087 EVP_add_digest(EVP_sha256());
2090 ctx = SSL_CTX_new(TLSv1_method());
2093 while ((err = ERR_get_error())) {
2094 DEBUG("Failed creating SSL context: %s",
2095 ERR_error_string(err, NULL));
2101 * Save the config on the context so that callbacks which
2102 * only get SSL_CTX* e.g. session persistence, can get it
2104 SSL_CTX_set_app_data(ctx, conf);
2107 * Identify the type of certificates that needs to be loaded
2109 if (conf->file_type) {
2110 type = SSL_FILETYPE_PEM;
2112 type = SSL_FILETYPE_ASN1;
2116 * Set the password to load private key
2118 if (conf->private_key_password) {
2121 * We don't want to put the private key password in eap.conf, so check
2122 * for our special string which indicates we should get the password
2125 char const* special_string = "Apple:UseCertAdmin";
2126 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2129 long const max_password_len = 128;
2130 snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2131 conf->private_key_file);
2133 DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2135 FILE* cmd_pipe = popen(cmd, "r");
2137 ERROR("TLS: %s command failed. Unable to get private_key_password", cmd);
2138 ERROR("Error reading private_key_file %s", conf->private_key_file);
2142 rad_const_free(conf->private_key_password);
2143 password = talloc_array(conf, char, max_password_len);
2145 ERROR("TLS: Can't allocate space for private_key_password");
2146 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2151 fgets(password, max_password_len, cmd_pipe);
2154 /* Get rid of newline at end of password. */
2155 password[strlen(password) - 1] = '\0';
2157 DEBUG3("tls: Password from command = \"%s\"", password);
2158 conf->private_key_password = password;
2165 memcpy(&password, &conf->private_key_password, sizeof(password));
2166 SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2167 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2171 #ifdef PSK_MAX_IDENTITY_LEN
2174 * No dynamic query exists. There MUST be a
2175 * statically configured identity and password.
2177 if (conf->psk_query && !*conf->psk_query) {
2178 ERROR("Invalid PSK Configuration: psk_query cannot be empty");
2182 SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2184 } else if (conf->psk_query) {
2185 ERROR("Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2190 * Now check that if PSK is being used, the config is valid.
2192 if ((conf->psk_identity && !conf->psk_password) ||
2193 (!conf->psk_identity && conf->psk_password) ||
2194 (conf->psk_identity && !*conf->psk_identity) ||
2195 (conf->psk_password && !*conf->psk_password)) {
2196 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2200 if (conf->psk_identity) {
2201 size_t psk_len, hex_len;
2202 uint8_t buffer[PSK_MAX_PSK_LEN];
2204 if (conf->certificate_file ||
2205 conf->private_key_password || conf->private_key_file ||
2206 conf->ca_file || conf->ca_path) {
2207 ERROR("When PSKs are used, No certificate configuration is permitted");
2212 SSL_CTX_set_psk_client_callback(ctx,
2213 psk_client_callback);
2216 psk_len = strlen(conf->psk_password);
2217 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2218 ERROR("psk_hexphrase is too long (max %d)",
2224 * Check the password now, so that we don't have
2225 * errors at run-time.
2227 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2228 if (psk_len != (2 * hex_len)) {
2229 ERROR("psk_hexphrase is not all hex");
2236 (void) client; /* -Wunused */
2240 * Load our keys and certificates
2242 * If certificates are of type PEM then we can make use
2243 * of cert chain authentication using openssl api call
2244 * SSL_CTX_use_certificate_chain_file. Please see how
2245 * the cert chain needs to be given in PEM from
2248 if (!conf->certificate_file) goto load_ca;
2250 if (type == SSL_FILETYPE_PEM) {
2251 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2252 ERROR("Error reading certificate file %s:%s",
2253 conf->certificate_file,
2254 ERR_error_string(ERR_get_error(), NULL));
2258 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2259 ERROR("Error reading certificate file %s:%s",
2260 conf->certificate_file,
2261 ERR_error_string(ERR_get_error(), NULL));
2265 /* Load the CAs we trust */
2267 if (conf->ca_file || conf->ca_path) {
2268 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2269 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2270 ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2274 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2276 if (conf->private_key_file) {
2277 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2278 ERROR("Failed reading private key file %s:%s",
2279 conf->private_key_file,
2280 ERR_error_string(ERR_get_error(), NULL));
2285 * Check if the loaded private key is the right one
2287 if (!SSL_CTX_check_private_key(ctx)) {
2288 ERROR("Private key does not match the certificate public key");
2293 #ifdef PSK_MAX_IDENTITY_LEN
2300 ctx_options |= SSL_OP_NO_SSLv2;
2301 ctx_options |= SSL_OP_NO_SSLv3;
2302 #ifdef SSL_OP_NO_TICKET
2303 ctx_options |= SSL_OP_NO_TICKET ;
2307 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
2308 * small subgroup attacks and forward secrecy. Always
2311 * SSL_OP_SINGLE_DH_USE has an impact on the computer
2312 * time needed during negotiation, but it is not very
2315 ctx_options |= SSL_OP_SINGLE_DH_USE;
2318 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2319 * in Windows Vista client.
2320 * http://www.openssl.org/~bodo/tls-cbc.txt
2321 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2323 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2325 SSL_CTX_set_options(ctx, ctx_options);
2328 * TODO: Set the RSA & DH
2329 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2330 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2334 * set the message callback to identify the type of
2335 * message. For every new session, there can be a
2336 * different callback argument.
2338 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2342 * Set eliptical curve crypto configuration.
2344 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2345 #ifndef OPENSSL_NO_ECDH
2346 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2352 /* Set Info callback */
2353 SSL_CTX_set_info_callback(ctx, cbtls_info);
2356 * Callbacks, etc. for session resumption.
2358 if (conf->session_cache_enable) {
2359 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2360 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2361 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2363 SSL_CTX_set_quiet_shutdown(ctx, 1);
2364 if (FR_TLS_EX_INDEX_VPS < 0)
2365 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2366 if (FR_TLS_EX_INDEX_CERTS < 0)
2367 FR_TLS_EX_INDEX_CERTS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2371 * Check the certificates for revocation.
2373 #ifdef X509_V_FLAG_CRL_CHECK
2374 if (conf->check_crl) {
2375 certstore = SSL_CTX_get_cert_store(ctx);
2376 if (certstore == NULL) {
2377 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2378 ERROR("tls: Error reading Certificate Store");
2381 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2387 * Always verify the peer certificate
2389 verify_mode |= SSL_VERIFY_PEER;
2390 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2391 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2392 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2394 if (conf->verify_depth) {
2395 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2398 /* Load randomness */
2399 if (conf->random_file) {
2400 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2401 ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2402 ERROR("tls: Error loading randomness");
2408 * Set the cipher list if we were told to
2410 if (conf->cipher_list) {
2411 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2412 ERROR("tls: Error setting cipher list");
2418 * Setup session caching
2420 if (conf->session_cache_enable) {
2422 * Create a unique context Id per EAP-TLS configuration.
2424 if (conf->session_id_name) {
2425 snprintf(conf->session_context_id,
2426 sizeof(conf->session_context_id),
2428 conf->session_id_name);
2430 snprintf(conf->session_context_id,
2431 sizeof(conf->session_context_id),
2436 * Cache it, and DON'T auto-clear it.
2438 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2440 SSL_CTX_set_session_id_context(ctx,
2441 (unsigned char *) conf->session_context_id,
2442 (unsigned int) strlen(conf->session_context_id));
2445 * Our timeout is in hours, this is in seconds.
2447 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2450 * Set the maximum number of entries in the
2453 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2456 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2464 * Free TLS client/server config
2465 * Should not be called outside this code, as a callback is
2466 * added to automatically free the data when the CONF_SECTION
2469 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2471 if (conf->ctx) SSL_CTX_free(conf->ctx);
2473 #ifdef HAVE_OPENSSL_OCSP_H
2474 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2475 conf->ocsp_store = NULL;
2479 memset(conf, 0, sizeof(*conf));
2484 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2486 fr_tls_server_conf_t *conf;
2488 conf = talloc_zero(ctx, fr_tls_server_conf_t);
2490 ERROR("Out of memory");
2494 talloc_set_destructor(conf, _tls_server_conf_free);
2500 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2502 fr_tls_server_conf_t *conf;
2505 * If cs has already been parsed there should be a cached copy
2506 * of conf already stored, so just return that.
2508 conf = cf_data_find(cs, "tls-conf");
2510 DEBUG("Using cached TLS configuration from previous invocation");
2514 conf = tls_server_conf_alloc(cs);
2516 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2523 * Save people from their own stupidity.
2525 if (conf->fragment_size < 100) conf->fragment_size = 100;
2527 if (!conf->private_key_file) {
2528 ERROR("TLS Server requires a private key file");
2532 if (!conf->certificate_file) {
2533 ERROR("TLS Server requires a certificate file");
2540 conf->ctx = tls_init_ctx(conf, 0);
2541 if (conf->ctx == NULL) {
2545 #ifdef HAVE_OPENSSL_OCSP_H
2547 * Initialize OCSP Revocation Store
2549 if (conf->ocsp_enable) {
2550 conf->ocsp_store = init_revocation_store(conf);
2551 if (conf->ocsp_store == NULL) goto error;
2553 #endif /*HAVE_OPENSSL_OCSP_H*/
2557 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2558 if (load_dh_params(conf->ctx, dh_file) < 0) {
2563 if (generate_eph_rsa_key(conf->ctx) < 0) {
2567 if (conf->verify_tmp_dir) {
2568 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2569 ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2574 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2575 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2580 * Cache conf in cs in case we're asked to parse this again.
2582 cf_data_add(cs, "tls-conf", conf, NULL);
2587 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2589 fr_tls_server_conf_t *conf;
2591 conf = cf_data_find(cs, "tls-conf");
2593 DEBUG("Using cached TLS configuration from previous invocation");
2597 conf = tls_server_conf_alloc(cs);
2599 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2606 * Save people from their own stupidity.
2608 if (conf->fragment_size < 100) conf->fragment_size = 100;
2613 conf->ctx = tls_init_ctx(conf, 1);
2614 if (conf->ctx == NULL) {
2621 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2622 if (load_dh_params(conf->ctx, dh_file) < 0) {
2627 if (generate_eph_rsa_key(conf->ctx) < 0) {
2631 cf_data_add(cs, "tls-conf", conf, NULL);
2636 int tls_success(tls_session_t *ssn, REQUEST *request)
2638 VALUE_PAIR *vp, *vps = NULL;
2639 fr_tls_server_conf_t *conf;
2640 TALLOC_CTX *talloc_ctx;
2642 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2643 rad_assert(conf != NULL);
2645 talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2648 * If there's no session resumption, delete the entry
2649 * from the cache. This means either it's disabled
2650 * globally for this SSL context, OR we were told to
2651 * disable it for this user.
2653 * This also means you can't turn it on just for one
2656 if ((!ssn->allow_session_resumption) ||
2657 (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2658 (vp->vp_integer == 0))) {
2659 SSL_CTX_remove_session(ssn->ctx,
2661 ssn->allow_session_resumption = 0;
2664 * If we're in a resumed session and it's
2667 if (SSL_session_reused(ssn->ssl)) {
2668 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2673 * Else resumption IS allowed, so we store the
2674 * user data in the cache.
2676 } else if (!SSL_session_reused(ssn->ssl)) {
2679 char buffer[2 * MAX_SESSION_SIZE + 1];
2681 size = ssn->ssl->session->session_id_length;
2682 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2684 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2686 vp = paircopy2(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2687 if (vp) pairadd(&vps, vp);
2689 vp = paircopy2(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2690 if (vp) pairadd(&vps, vp);
2692 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2693 if (vp) pairadd(&vps, vp);
2695 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2696 if (vp) pairadd(&vps, vp);
2698 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2701 * Hmm... the certs should probably be session data.
2705 * @todo: some go into reply, others into
2708 pairadd(&vps, paircopy(talloc_ctx, *certs));
2712 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2713 SSL_SESSION_set_ex_data(ssn->ssl->session,
2714 FR_TLS_EX_INDEX_VPS, vps);
2715 if (conf->session_cache_path) {
2716 /* write the VPs to the cache file */
2717 char filename[256], buf[1024];
2720 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2721 conf->session_cache_path, FR_DIR_SEP, buffer
2723 vp_file = fopen(filename, "w");
2724 if (vp_file == NULL) {
2725 RDEBUG2("Could not write session VPs to persistent cache: %s", fr_syserror(errno));
2728 /* generate a dummy user-style entry which is easy to read back */
2729 fprintf(vp_file, "# SSL cached session\n");
2730 fprintf(vp_file, "%s\n", buffer);
2731 for (vp = fr_cursor_init(&cursor, &vps);
2733 vp = fr_cursor_next(&cursor)) {
2734 vp_prints(buf, sizeof(buf), vp);
2735 fprintf(vp_file, "\t%s,\n", buf);
2741 RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2742 SSL_CTX_remove_session(ssn->ctx,
2747 * Else the session WAS allowed. Copy the cached
2752 char buffer[2 * MAX_SESSION_SIZE + 1];
2754 size = ssn->ssl->session->session_id_length;
2755 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2757 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2759 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2760 FR_TLS_EX_INDEX_VPS);
2762 RWDEBUG("No information in cached session %s", buffer);
2768 RDEBUG("Adding cached attributes for session %s:", buffer);
2769 debug_pair_list(vps);
2771 for (vp = fr_cursor_init(&cursor, &vps);
2773 vp = fr_cursor_next(&cursor)) {
2775 * TLS-* attrs get added back to
2778 if ((vp->da->vendor == 0) &&
2779 (vp->da->attr >= 1910) &&
2780 (vp->da->attr < 1929)) {
2781 pairadd(&request->packet->vps,
2782 paircopyvp(request->packet, vp));
2784 pairadd(&request->reply->vps,
2785 paircopyvp(request->reply, vp));
2789 if (conf->session_cache_path) {
2790 /* "touch" the cached session/vp file */
2793 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2794 conf->session_cache_path, FR_DIR_SEP, buffer
2796 utime(filename, NULL);
2797 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2798 conf->session_cache_path, FR_DIR_SEP, buffer
2800 utime(filename, NULL);
2804 * Mark the request as resumed.
2806 pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2814 void tls_fail(tls_session_t *ssn)
2817 * Force the session to NOT be cached.
2819 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2822 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2829 * Decrypt the complete record.
2831 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2832 ssn->dirty_in.used);
2833 if (err != (int) ssn->dirty_in.used) {
2834 record_init(&ssn->dirty_in);
2835 RDEBUG("Failed writing %d to SSL BIO: %d",
2836 ssn->dirty_in.used, err);
2841 * Clear the dirty buffer now that we are done with it
2842 * and init the clean_out buffer to store decrypted data
2844 record_init(&ssn->dirty_in);
2845 record_init(&ssn->clean_out);
2848 * Read (and decrypt) the tunneled data from the
2849 * SSL session, and put it into the decrypted
2852 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2853 sizeof(ssn->clean_out.data));
2858 RDEBUG("SSL_read Error");
2860 code = SSL_get_error(ssn->ssl, err);
2862 case SSL_ERROR_WANT_READ:
2863 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2864 return FR_TLS_MORE_FRAGMENTS;
2866 case SSL_ERROR_WANT_WRITE:
2867 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2871 DEBUG("Error in fragmentation logic: %s",
2872 ERR_error_string(code, NULL));
2875 * FIXME: Call int_ssl_check?
2883 RWDEBUG("No data inside of the tunnel");
2887 * Passed all checks, successfully decrypted data
2889 ssn->clean_out.used = err;
2896 * Acknowledge received is for one of the following messages sent earlier
2897 * 1. Handshake completed Message, so now send, EAP-Success
2898 * 2. Alert Message, now send, EAP-Failure
2899 * 3. Fragment Message, now send, next Fragment
2901 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2903 RDEBUG2("Received TLS ACK");
2906 RERROR("FAIL: Unexpected ACK received. Could not obtain session information");
2907 return FR_TLS_INVALID;
2909 if (ssn->info.initialized == 0) {
2910 RDEBUG("No SSL info available. Waiting for more SSL data");
2911 return FR_TLS_REQUEST;
2913 if ((ssn->info.content_type == handshake) &&
2914 (ssn->info.origin == 0)) {
2915 RERROR("FAIL: ACK without earlier message");
2916 return FR_TLS_INVALID;
2919 switch (ssn->info.content_type) {
2921 RDEBUG2("ACK alert");
2925 if ((ssn->info.handshake_type == finished) &&
2926 (ssn->dirty_out.used == 0)) {
2927 RDEBUG2("ACK handshake is finished");
2930 * From now on all the content is
2931 * application data set it here as nobody else
2934 ssn->info.content_type = application_data;
2935 return FR_TLS_SUCCESS;
2936 } /* else more data to send */
2938 RDEBUG2("ACK handshake fragment handler");
2939 /* Fragmentation handler, send next fragment */
2940 return FR_TLS_REQUEST;
2942 case application_data:
2943 RDEBUG2("ACK handshake fragment handler in application data");
2944 return FR_TLS_REQUEST;
2947 * For the rest of the conditions, switch over
2948 * to the default section below.
2951 RDEBUG2("ACK default");
2952 RERROR("Invalid ACK received: %d",
2953 ssn->info.content_type);
2954 return FR_TLS_INVALID;
2958 #endif /* WITH_TLS */