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
25 #include <freeradius-devel/ident.h>
28 #include <freeradius-devel/autoconf.h>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/rad_assert.h>
33 #ifdef HAVE_SYS_STAT_H
38 #ifdef HAVE_OPENSSL_RAND_H
39 #include <openssl/rand.h>
42 #ifdef HAVE_OPENSSL_OCSP_H
43 #include <openssl/ocsp.h>
47 #define PTHREAD_MUTEX_LOCK pthread_mutex_lock
48 #define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
50 #define PTHREAD_MUTEX_LOCK(_x)
51 #define PTHREAD_MUTEX_UNLOCK(_x)
56 static void record_init(record_t *buf);
57 static void record_close(record_t *buf);
58 static unsigned int record_plus(record_t *buf, const void *ptr,
60 static unsigned int record_minus(record_t *buf, void *ptr,
63 #ifdef PSK_MAX_IDENTITY_LEN
64 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
65 unsigned char *psk, int max_psk_len)
68 fr_tls_server_conf_t *conf;
70 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
71 FR_TLS_EX_INDEX_CONF);
75 * FIXME: Look up the PSK password based on the identity!
77 if (strcmp(identity, conf->psk_identity) != 0) {
81 psk_len = strlen(conf->psk_password);
82 if (psk_len > (2 * max_psk_len)) return 0;
84 return fr_hex2bin(conf->psk_password, psk, psk_len);
87 static unsigned int psk_client_callback(SSL *ssl, UNUSED const char *hint,
88 char *identity, unsigned int max_identity_len,
89 unsigned char *psk, unsigned int max_psk_len)
92 fr_tls_server_conf_t *conf;
94 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
95 FR_TLS_EX_INDEX_CONF);
98 psk_len = strlen(conf->psk_password);
99 if (psk_len > (2 * max_psk_len)) return 0;
101 strlcpy(identity, conf->psk_identity, max_identity_len);
103 return fr_hex2bin(conf->psk_password, psk, psk_len);
108 tls_session_t *tls_new_client_session(fr_tls_server_conf_t *conf, int fd)
111 tls_session_t *ssn = NULL;
113 ssn = (tls_session_t *) malloc(sizeof(*ssn));
114 memset(ssn, 0, sizeof(*ssn));
116 ssn->ctx = conf->ctx;
117 ssn->ssl = SSL_new(ssn->ctx);
118 rad_assert(ssn->ssl != NULL);
121 * Add the message callback to identify what type of
122 * message/handshake is passed
124 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
125 SSL_set_msg_callback_arg(ssn->ssl, ssn);
126 SSL_set_info_callback(ssn->ssl, cbtls_info);
129 * Always verify the peer certificate.
131 DEBUG2("Requiring Server certificate");
132 verify_mode = SSL_VERIFY_PEER;
133 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
134 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
136 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
137 SSL_set_fd(ssn->ssl, fd);
138 if (SSL_connect(ssn->ssl) <= 0) {
140 while ((err = ERR_get_error())) {
141 DEBUG("OpenSSL Err says %s",
142 ERR_error_string(err, NULL));
151 tls_session_t *tls_new_session(fr_tls_server_conf_t *conf, REQUEST *request,
154 tls_session_t *state = NULL;
160 * Manually flush the sessions every so often. If HALF
161 * of the session lifetime has passed since we last
162 * flushed, then flush it again.
164 * FIXME: Also do it every N sessions?
166 if (conf->session_cache_enable &&
167 ((conf->session_last_flushed + (conf->session_timeout * 1800)) <= request->timestamp)){
168 RDEBUG2("Flushing SSL sessions (of #%ld)",
169 SSL_CTX_sess_number(conf->ctx));
171 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
172 conf->session_last_flushed = request->timestamp;
175 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
176 radlog(L_ERR, "SSL: Error creating new SSL: %s",
177 ERR_error_string(ERR_get_error(), NULL));
181 /* We use the SSL's "app_data" to indicate a call-back */
182 SSL_set_app_data(new_tls, NULL);
184 state = (tls_session_t *)malloc(sizeof(*state));
185 memset(state, 0, sizeof(*state));
188 state->ctx = conf->ctx;
189 state->ssl = new_tls;
192 * Initialize callbacks
194 state->record_init = record_init;
195 state->record_close = record_close;
196 state->record_plus = record_plus;
197 state->record_minus = record_minus;
200 * Create & hook the BIOs to handle the dirty side of the
201 * SSL. This is *very important* as we want to handle
202 * the transmission part. Now the only IO interface
203 * that SSL is aware of, is our defined BIO buffers.
205 * This means that all SSL IO is done to/from memory,
206 * and we can update those BIOs from the packets we've
209 state->into_ssl = BIO_new(BIO_s_mem());
210 state->from_ssl = BIO_new(BIO_s_mem());
211 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
214 * Add the message callback to identify what type of
215 * message/handshake is passed
217 SSL_set_msg_callback(new_tls, cbtls_msg);
218 SSL_set_msg_callback_arg(new_tls, state);
219 SSL_set_info_callback(new_tls, cbtls_info);
222 * In Server mode we only accept.
224 SSL_set_accept_state(state->ssl);
227 * Verify the peer certificate, if asked.
230 RDEBUG2("Requiring client certificate");
231 verify_mode = SSL_VERIFY_PEER;
232 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
233 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
235 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
237 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
238 state->length_flag = conf->include_length;
241 * We use default fragment size, unless the Framed-MTU
242 * tells us it's too big. Note that we do NOT account
243 * for the EAP-TLS headers if conf->fragment_size is
244 * large, because that config item looks to be confusing.
246 * i.e. it should REALLY be called MTU, and the code here
247 * should figure out what that means for TLS fragment size.
248 * asking the administrator to know the internal details
249 * of EAP-TLS in order to calculate fragment sizes is
252 state->offset = conf->fragment_size;
253 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0);
254 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
255 state->offset = vp->vp_integer;
258 if (conf->session_cache_enable) {
259 state->allow_session_resumption = 1; /* otherwise it's zero */
268 * Print out some text describing the error.
270 static int int_ssl_check(REQUEST *request, SSL *s, int ret, const char *text)
275 if ((l = ERR_get_error()) != 0) {
276 const char *p = ERR_error_string(l, NULL);
279 radlog(L_ERR, "SSL error %s", p);
282 vp = pairmake("Module-Failure-Message", p, T_OP_ADD);
283 if (vp) pairadd(&request->packet->vps, vp);
286 e = SSL_get_error(s, ret);
290 * These seem to be harmless and already "dealt
291 * with" by our non-blocking environment. NB:
292 * "ZERO_RETURN" is the clean "error"
293 * indicating a successfully closed SSL
294 * tunnel. We let this happen because our IO
295 * loop should not appear to have broken on
296 * this condition - and outside the IO loop, the
297 * "shutdown" state is checked.
299 * Don't print anything if we ignore the error.
302 case SSL_ERROR_WANT_READ:
303 case SSL_ERROR_WANT_WRITE:
304 case SSL_ERROR_WANT_X509_LOOKUP:
305 case SSL_ERROR_ZERO_RETURN:
309 * These seem to be indications of a genuine
310 * error that should result in the SSL tunnel
311 * being regarded as "dead".
313 case SSL_ERROR_SYSCALL:
314 radlog(L_ERR, "SSL: %s failed in a system call (%d), TLS session fails.",
319 radlog(L_ERR, "SSL: %s failed inside of TLS (%d), TLS session fails.",
325 * For any other errors that (a) exist, and (b)
326 * crop up - we need to interpret what to do with
327 * them - so "politely inform" the caller that
328 * the code needs updating here.
330 radlog(L_ERR, "SSL: FATAL SSL error ..... %d\n", e);
338 * We are the server, we always get the dirty data
339 * (Handshake data is also considered as dirty data)
340 * During handshake, since SSL API handles itself,
341 * After clean-up, dirty_out will be filled with
342 * the data required for handshaking. So we check
343 * if dirty_out is empty then we simply send it back.
344 * As of now, if handshake is successful, then we keep going,
347 * Fill the Bio with the dirty data to clean it
348 * Get the cleaned data from SSL, if it is not Handshake data
350 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
354 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
355 if (err != (int) ssn->dirty_in.used) {
356 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
358 record_init(&ssn->dirty_in);
361 record_init(&ssn->dirty_in);
363 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
364 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
366 ssn->clean_out.used += err;
370 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
374 /* Some Extra STATE information for easy debugging */
375 if (SSL_is_init_finished(ssn->ssl)) {
376 DEBUG2("SSL Connection Established\n");
378 if (SSL_in_init(ssn->ssl)) {
379 DEBUG2("In SSL Handshake Phase\n");
381 if (SSL_in_before(ssn->ssl)) {
382 DEBUG2("Before SSL Handshake Phase\n");
384 if (SSL_in_accept_init(ssn->ssl)) {
385 DEBUG2("In SSL Accept mode \n");
387 if (SSL_in_connect_init(ssn->ssl)) {
388 DEBUG2("In SSL Connect mode \n");
391 err = BIO_ctrl_pending(ssn->from_ssl);
393 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
394 sizeof(ssn->dirty_out.data));
396 ssn->dirty_out.used = err;
398 } else if (BIO_should_retry(ssn->from_ssl)) {
399 record_init(&ssn->dirty_in);
400 DEBUG2(" tls: Asking for more data in tunnel");
404 int_ssl_check(request, ssn->ssl, err, "BIO_read");
405 record_init(&ssn->dirty_in);
409 DEBUG2("SSL Application Data");
410 /* Its clean application data, do whatever we want */
411 record_init(&ssn->clean_out);
414 /* We are done with dirty_in, reinitialize it */
415 record_init(&ssn->dirty_in);
420 * Take clear-text user data, and encrypt it into the output buffer,
421 * to send to the client at the other end of the SSL connection.
423 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
428 * If there's un-encrypted data in 'clean_in', then write
429 * that data to the SSL session, and then call the BIO function
430 * to get that encrypted data from the SSL session, into
431 * a buffer which we can then package into an EAP packet.
433 * Based on Server's logic this clean_in is expected to
434 * contain the data to send to the client.
436 if (ssn->clean_in.used > 0) {
439 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
440 record_minus(&ssn->clean_in, NULL, written);
442 /* Get the dirty data from Bio to send it */
443 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
444 sizeof(ssn->dirty_out.data));
446 ssn->dirty_out.used = err;
448 int_ssl_check(request, ssn->ssl, err, "handshake_send");
455 void session_init(tls_session_t *ssn)
458 ssn->into_ssl = ssn->from_ssl = NULL;
459 record_init(&ssn->clean_in);
460 record_init(&ssn->clean_out);
461 record_init(&ssn->dirty_in);
462 record_init(&ssn->dirty_out);
464 memset(&ssn->info, 0, sizeof(ssn->info));
468 ssn->tls_msg_len = 0;
469 ssn->length_flag = 0;
471 ssn->free_opaque = NULL;
474 void session_close(tls_session_t *ssn)
476 SSL_set_quiet_shutdown(ssn->ssl, 1);
477 SSL_shutdown(ssn->ssl);
482 record_close(&ssn->clean_in);
483 record_close(&ssn->clean_out);
484 record_close(&ssn->dirty_in);
485 record_close(&ssn->dirty_out);
489 void session_free(void *ssn)
491 tls_session_t *sess = (tls_session_t *)ssn;
496 * Free any opaque TTLS or PEAP data.
498 if ((sess->opaque) && (sess->free_opaque)) {
499 sess->free_opaque(sess->opaque);
508 static void record_init(record_t *rec)
513 static void record_close(record_t *rec)
520 * Copy data to the intermediate buffer, before we send
523 static unsigned int record_plus(record_t *rec, const void *ptr,
526 unsigned int added = MAX_RECORD_SIZE - rec->used;
532 memcpy(rec->data + rec->used, ptr, added);
538 * Take data from the buffer, and give it to the caller.
540 static unsigned int record_minus(record_t *rec, void *ptr,
543 unsigned int taken = rec->used;
550 memcpy(ptr, rec->data, taken);
554 * This is pretty bad...
557 memmove(rec->data, rec->data + taken, rec->used);
561 void tls_session_information(tls_session_t *tls_session)
563 const char *str_write_p, *str_version, *str_content_type = "";
564 const char *str_details1 = "", *str_details2= "";
568 * Don't print this out in the normal course of
571 if (debug_flag == 0) {
575 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
577 switch (tls_session->info.version)
580 str_version = "SSL 2.0";
583 str_version = "SSL 3.0 ";
586 str_version = "TLS 1.0 ";
589 str_version = "Unknown TLS version";
593 if (tls_session->info.version == SSL3_VERSION ||
594 tls_session->info.version == TLS1_VERSION) {
595 switch (tls_session->info.content_type) {
596 case SSL3_RT_CHANGE_CIPHER_SPEC:
597 str_content_type = "ChangeCipherSpec";
600 str_content_type = "Alert";
602 case SSL3_RT_HANDSHAKE:
603 str_content_type = "Handshake";
605 case SSL3_RT_APPLICATION_DATA:
606 str_content_type = "ApplicationData";
609 str_content_type = "UnknownContentType";
613 if (tls_session->info.content_type == SSL3_RT_ALERT) {
614 str_details1 = ", ???";
616 if (tls_session->info.record_len == 2) {
618 switch (tls_session->info.alert_level) {
619 case SSL3_AL_WARNING:
620 str_details1 = ", warning";
623 str_details1 = ", fatal";
627 str_details2 = " ???";
628 switch (tls_session->info.alert_description) {
629 case SSL3_AD_CLOSE_NOTIFY:
630 str_details2 = " close_notify";
632 case SSL3_AD_UNEXPECTED_MESSAGE:
633 str_details2 = " unexpected_message";
635 case SSL3_AD_BAD_RECORD_MAC:
636 str_details2 = " bad_record_mac";
638 case TLS1_AD_DECRYPTION_FAILED:
639 str_details2 = " decryption_failed";
641 case TLS1_AD_RECORD_OVERFLOW:
642 str_details2 = " record_overflow";
644 case SSL3_AD_DECOMPRESSION_FAILURE:
645 str_details2 = " decompression_failure";
647 case SSL3_AD_HANDSHAKE_FAILURE:
648 str_details2 = " handshake_failure";
650 case SSL3_AD_BAD_CERTIFICATE:
651 str_details2 = " bad_certificate";
653 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
654 str_details2 = " unsupported_certificate";
656 case SSL3_AD_CERTIFICATE_REVOKED:
657 str_details2 = " certificate_revoked";
659 case SSL3_AD_CERTIFICATE_EXPIRED:
660 str_details2 = " certificate_expired";
662 case SSL3_AD_CERTIFICATE_UNKNOWN:
663 str_details2 = " certificate_unknown";
665 case SSL3_AD_ILLEGAL_PARAMETER:
666 str_details2 = " illegal_parameter";
668 case TLS1_AD_UNKNOWN_CA:
669 str_details2 = " unknown_ca";
671 case TLS1_AD_ACCESS_DENIED:
672 str_details2 = " access_denied";
674 case TLS1_AD_DECODE_ERROR:
675 str_details2 = " decode_error";
677 case TLS1_AD_DECRYPT_ERROR:
678 str_details2 = " decrypt_error";
680 case TLS1_AD_EXPORT_RESTRICTION:
681 str_details2 = " export_restriction";
683 case TLS1_AD_PROTOCOL_VERSION:
684 str_details2 = " protocol_version";
686 case TLS1_AD_INSUFFICIENT_SECURITY:
687 str_details2 = " insufficient_security";
689 case TLS1_AD_INTERNAL_ERROR:
690 str_details2 = " internal_error";
692 case TLS1_AD_USER_CANCELLED:
693 str_details2 = " user_canceled";
695 case TLS1_AD_NO_RENEGOTIATION:
696 str_details2 = " no_renegotiation";
702 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
703 str_details1 = "???";
705 if (tls_session->info.record_len > 0)
706 switch (tls_session->info.handshake_type)
708 case SSL3_MT_HELLO_REQUEST:
709 str_details1 = ", HelloRequest";
711 case SSL3_MT_CLIENT_HELLO:
712 str_details1 = ", ClientHello";
714 case SSL3_MT_SERVER_HELLO:
715 str_details1 = ", ServerHello";
717 case SSL3_MT_CERTIFICATE:
718 str_details1 = ", Certificate";
720 case SSL3_MT_SERVER_KEY_EXCHANGE:
721 str_details1 = ", ServerKeyExchange";
723 case SSL3_MT_CERTIFICATE_REQUEST:
724 str_details1 = ", CertificateRequest";
726 case SSL3_MT_SERVER_DONE:
727 str_details1 = ", ServerHelloDone";
729 case SSL3_MT_CERTIFICATE_VERIFY:
730 str_details1 = ", CertificateVerify";
732 case SSL3_MT_CLIENT_KEY_EXCHANGE:
733 str_details1 = ", ClientKeyExchange";
735 case SSL3_MT_FINISHED:
736 str_details1 = ", Finished";
742 snprintf(tls_session->info.info_description,
743 sizeof(tls_session->info.info_description),
744 "%s %s%s [length %04lx]%s%s\n",
745 str_write_p, str_version, str_content_type,
746 (unsigned long)tls_session->info.record_len,
747 str_details1, str_details2);
749 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
751 RDEBUG2("%s\n", tls_session->info.info_description);
754 static CONF_PARSER cache_config[] = {
755 { "enable", PW_TYPE_BOOLEAN,
756 offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
757 { "lifetime", PW_TYPE_INTEGER,
758 offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
759 { "max_entries", PW_TYPE_INTEGER,
760 offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
761 { "name", PW_TYPE_STRING_PTR,
762 offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
763 { NULL, -1, 0, NULL, NULL } /* end the list */
766 static CONF_PARSER verify_config[] = {
767 { "tmpdir", PW_TYPE_STRING_PTR,
768 offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
769 { "client", PW_TYPE_STRING_PTR,
770 offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
771 { NULL, -1, 0, NULL, NULL } /* end the list */
774 #ifdef HAVE_OPENSSL_OCSP_H
775 static CONF_PARSER ocsp_config[] = {
776 { "enable", PW_TYPE_BOOLEAN,
777 offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
778 { "override_cert_url", PW_TYPE_BOOLEAN,
779 offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
780 { "url", PW_TYPE_STRING_PTR,
781 offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
782 { "use_nonce", PW_TYPE_BOOLEAN,
783 offsetof(fr_tls_server_conf_t, ocsp_use_nonce), NULL, "yes"},
784 { "timeout", PW_TYPE_INTEGER,
785 offsetof(fr_tls_server_conf_t, ocsp_timeout), NULL, "yes"},
786 { "softfail", PW_TYPE_BOOLEAN,
787 offsetof(fr_tls_server_conf_t, ocsp_softfail), NULL, "yes"},
788 { NULL, -1, 0, NULL, NULL } /* end the list */
792 static CONF_PARSER tls_server_config[] = {
793 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
794 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
795 { "dh_key_exchange", PW_TYPE_BOOLEAN,
796 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
797 { "rsa_key_length", PW_TYPE_INTEGER,
798 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
799 { "dh_key_length", PW_TYPE_INTEGER,
800 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
801 { "verify_depth", PW_TYPE_INTEGER,
802 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
803 { "CA_path", PW_TYPE_FILENAME,
804 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
805 { "pem_file_type", PW_TYPE_BOOLEAN,
806 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
807 { "private_key_file", PW_TYPE_FILENAME,
808 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
809 { "certificate_file", PW_TYPE_FILENAME,
810 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
811 { "CA_file", PW_TYPE_FILENAME,
812 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
813 { "private_key_password", PW_TYPE_STRING_PTR,
814 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
815 #ifdef PSK_MAX_IDENTITY_LEN
816 { "psk_identity", PW_TYPE_STRING_PTR,
817 offsetof(fr_tls_server_conf_t, psk_identity), NULL, NULL },
818 { "psk_hexphrase", PW_TYPE_STRING_PTR,
819 offsetof(fr_tls_server_conf_t, psk_password), NULL, NULL },
821 { "dh_file", PW_TYPE_STRING_PTR,
822 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
823 { "random_file", PW_TYPE_STRING_PTR,
824 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
825 { "fragment_size", PW_TYPE_INTEGER,
826 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
827 { "include_length", PW_TYPE_BOOLEAN,
828 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
829 { "check_crl", PW_TYPE_BOOLEAN,
830 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
831 { "allow_expired_crl", PW_TYPE_BOOLEAN,
832 offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
833 { "check_cert_cn", PW_TYPE_STRING_PTR,
834 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
835 { "cipher_list", PW_TYPE_STRING_PTR,
836 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
837 { "check_cert_issuer", PW_TYPE_STRING_PTR,
838 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
839 { "make_cert_command", PW_TYPE_STRING_PTR,
840 offsetof(fr_tls_server_conf_t, make_cert_command), NULL, NULL},
841 { "require_client_cert", PW_TYPE_BOOLEAN,
842 offsetof(fr_tls_server_conf_t, require_client_cert), NULL, NULL },
844 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
845 #ifndef OPENSSL_NO_ECDH
846 { "ecdh_curve", PW_TYPE_STRING_PTR,
847 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
851 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
853 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
855 #ifdef HAVE_OPENSSL_OCSP_H
856 { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
859 { NULL, -1, 0, NULL, NULL } /* end the list */
863 static CONF_PARSER tls_client_config[] = {
864 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
865 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
866 { "dh_key_exchange", PW_TYPE_BOOLEAN,
867 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
868 { "rsa_key_length", PW_TYPE_INTEGER,
869 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
870 { "dh_key_length", PW_TYPE_INTEGER,
871 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
872 { "verify_depth", PW_TYPE_INTEGER,
873 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
874 { "CA_path", PW_TYPE_FILENAME,
875 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
876 { "pem_file_type", PW_TYPE_BOOLEAN,
877 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
878 { "private_key_file", PW_TYPE_FILENAME,
879 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
880 { "certificate_file", PW_TYPE_FILENAME,
881 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
882 { "CA_file", PW_TYPE_FILENAME,
883 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
884 { "private_key_password", PW_TYPE_STRING_PTR,
885 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
886 { "dh_file", PW_TYPE_STRING_PTR,
887 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
888 { "random_file", PW_TYPE_STRING_PTR,
889 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
890 { "fragment_size", PW_TYPE_INTEGER,
891 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
892 { "include_length", PW_TYPE_BOOLEAN,
893 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
894 { "check_crl", PW_TYPE_BOOLEAN,
895 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
896 { "check_cert_cn", PW_TYPE_STRING_PTR,
897 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
898 { "cipher_list", PW_TYPE_STRING_PTR,
899 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
900 { "check_cert_issuer", PW_TYPE_STRING_PTR,
901 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
903 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
904 #ifndef OPENSSL_NO_ECDH
905 { "ecdh_curve", PW_TYPE_STRING_PTR,
906 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
910 { NULL, -1, 0, NULL, NULL } /* end the list */
915 * TODO: Check for the type of key exchange * like conf->dh_key
917 static int load_dh_params(SSL_CTX *ctx, char *file)
922 if ((bio = BIO_new_file(file, "r")) == NULL) {
923 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
927 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
930 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters. DH cipher suites may not work!");
931 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
935 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
936 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
947 * Generate ephemeral RSA keys.
949 static int generate_eph_rsa_key(SSL_CTX *ctx)
953 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
955 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
956 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
966 * Print debugging messages, and free data.
968 * FIXME: Write sessions to some long-term storage, so that
969 * session resumption can still occur after the server
972 #define MAX_SESSION_SIZE (256)
974 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
977 char buffer[2 * MAX_SESSION_SIZE + 1];
979 size = sess->session_id_length;
980 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
982 fr_bin2hex(sess->session_id, buffer, size);
984 DEBUG2(" SSL: Removing session %s from the cache", buffer);
989 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
992 char buffer[2 * MAX_SESSION_SIZE + 1];
994 size = sess->session_id_length;
995 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
997 fr_bin2hex(sess->session_id, buffer, size);
999 DEBUG2(" SSL: adding session %s to cache", buffer);
1004 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
1005 unsigned char *data, int len,
1009 char buffer[2 * MAX_SESSION_SIZE + 1];
1012 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1014 fr_bin2hex(data, buffer, size);
1016 DEBUG2(" SSL: Client requested nonexistent cached session %s",
1023 #ifdef HAVE_OPENSSL_OCSP_H
1025 * This function extracts the OCSP Responder URL
1026 * from an existing x509 certificate.
1028 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1029 char **ppath, int *pssl)
1033 AUTHORITY_INFO_ACCESS *aia;
1034 ACCESS_DESCRIPTION *ad;
1036 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1038 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1039 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1040 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1041 if (ad->location->type == GEN_URI) {
1042 if(OCSP_parse_url(ad->location->d.ia5->data,
1043 phost, pport, ppath, pssl))
1052 * This function sends a OCSP request to a defined OCSP responder
1053 * and checks the OCSP response for correctness.
1056 /* Maximum leeway in validity period: default 5 minutes */
1057 #define MAX_VALIDITY_PERIOD (5 * 60)
1059 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1060 fr_tls_server_conf_t *conf)
1062 OCSP_CERTID *certid;
1064 OCSP_RESPONSE *resp = NULL;
1065 OCSP_BASICRESP *bresp = NULL;
1070 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1071 BIO *cbio, *bio_out;
1074 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1079 struct timeval when;
1082 * Create OCSP Request
1084 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1085 req = OCSP_REQUEST_new();
1086 OCSP_request_add0_id(req, certid);
1087 if(conf->ocsp_use_nonce) {
1088 OCSP_request_add1_nonce(req, NULL, 8);
1092 * Send OCSP Request and get OCSP Response
1095 /* Get OCSP responder URL */
1096 if(conf->ocsp_override_url) {
1097 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
1100 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1103 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1105 /* Setup BIO socket to OCSP responder */
1106 cbio = BIO_new_connect(host);
1108 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1110 BIO_set_conn_port(cbio, port);
1112 if (conf->ocsp_timeout)
1113 BIO_set_nbio(cbio, 1);
1115 rc = BIO_do_connect(cbio);
1116 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1117 radlog(L_ERR, "Error: Couldn't connect to OCSP responder");
1122 ctx = OCSP_sendreq_new(cbio, path, req, -1);
1124 radlog(L_ERR, "Error: Couldn't send OCSP request");
1129 gettimeofday(&when, NULL);
1130 when.tv_sec += conf->ocsp_timeout;
1133 rc = OCSP_sendreq_nbio(&resp, ctx);
1134 if (conf->ocsp_timeout) {
1135 gettimeofday(&now, NULL);
1136 if (!timercmp(&now, &when, <))
1139 } while ((rc == -1) && BIO_should_retry(cbio));
1141 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1142 radlog(L_ERR, "Error: OCSP response timed out");
1147 OCSP_REQ_CTX_free(ctx);
1150 radlog(L_ERR, "Error: Couldn't get OCSP response");
1155 /* Verify OCSP response status */
1156 status = OCSP_response_status(resp);
1157 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1158 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1159 radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status));
1162 bresp = OCSP_response_get1_basic(resp);
1163 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1164 radlog(L_ERR, "Error: OCSP response has wrong nonce value");
1167 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1168 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
1172 /* Verify OCSP cert status */
1173 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1174 &rev, &thisupd, &nextupd)) {
1175 radlog(L_ERR, "ERROR: No Status found.\n");
1179 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1180 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1181 ERR_print_errors(bio_out);
1184 BIO_puts(bio_out, "\tThis Update: ");
1185 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1186 BIO_puts(bio_out, "\n");
1187 BIO_puts(bio_out, "\tNext Update: ");
1188 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1189 BIO_puts(bio_out, "\n");
1192 case V_OCSP_CERTSTATUS_GOOD:
1193 DEBUG2("[oscp] --> Cert status: good");
1198 /* REVOKED / UNKNOWN */
1199 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1201 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1202 BIO_puts(bio_out, "\tRevocation Time: ");
1203 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1204 BIO_puts(bio_out, "\n");
1209 /* Free OCSP Stuff */
1210 OCSP_REQUEST_free(req);
1211 OCSP_RESPONSE_free(resp);
1216 OCSP_BASICRESP_free(bresp);
1220 DEBUG2("[ocsp] --> Certificate is valid!");
1223 if (conf->ocsp_softfail) {
1224 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid.");
1225 DEBUG2("[ocsp] --> Warning! This may be insecure.");
1228 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1233 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1239 #endif /* HAVE_OPENSSL_OCSP_H */
1242 * For creating certificate attributes.
1244 static const char *cert_attr_names[6][2] = {
1245 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1246 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1247 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1248 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1249 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
1250 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" }
1253 #define FR_TLS_SERIAL (0)
1254 #define FR_TLS_EXPIRATION (1)
1255 #define FR_TLS_SUBJECT (2)
1256 #define FR_TLS_ISSUER (3)
1257 #define FR_TLS_CN (4)
1258 #define FR_TLS_SAN_EMAIL (5)
1261 * Before trusting a certificate, you must make sure that the
1262 * certificate is 'valid'. There are several steps that your
1263 * application can take in determining if a certificate is
1264 * valid. Commonly used steps are:
1266 * 1.Verifying the certificate's signature, and verifying that
1267 * the certificate has been issued by a trusted Certificate
1270 * 2.Verifying that the certificate is valid for the present date
1271 * (i.e. it is being presented within its validity dates).
1273 * 3.Verifying that the certificate has not been revoked by its
1274 * issuing Certificate Authority, by checking with respect to a
1275 * Certificate Revocation List (CRL).
1277 * 4.Verifying that the credentials presented by the certificate
1278 * fulfill additional requirements specific to the application,
1279 * such as with respect to access control lists or with respect
1280 * to OCSP (Online Certificate Status Processing).
1282 * NOTE: This callback will be called multiple times based on the
1283 * depth of the root certificate chain
1285 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1287 char subject[1024]; /* Used for the subject name */
1288 char issuer[1024]; /* Used for the issuer name */
1289 char common_name[1024];
1294 int err, depth, lookup, loc;
1295 fr_tls_server_conf_t *conf;
1298 ASN1_INTEGER *sn = NULL;
1299 ASN1_TIME *asn_time = NULL;
1302 #ifdef HAVE_OPENSSL_OCSP_H
1303 X509_STORE *ocsp_store = NULL;
1307 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1308 err = X509_STORE_CTX_get_error(ctx);
1309 depth = X509_STORE_CTX_get_error_depth(ctx);
1314 * Log client/issuing cert. If there's an error, log
1317 if ((lookup > 1) && !my_ok) lookup = 1;
1320 * Retrieve the pointer to the SSL of the connection currently treated
1321 * and the application specific data stored into the SSL object.
1323 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1324 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1325 if (!conf) return 1;
1327 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1329 if (!request) return 1; /* FIXME: outbound TLS */
1331 rad_assert(request != NULL);
1332 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1333 rad_assert(certs != NULL);
1334 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1335 #ifdef HAVE_OPENSSL_OCSP_H
1336 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1341 * Get the Serial Number
1344 sn = X509_get_serialNumber(client_cert);
1347 * For this next bit, we create the attributes *only* if
1348 * we're at the client or issuing certificate, AND we
1349 * have a user identity. i.e. we don't create the
1350 * attributes for RadSec connections.
1353 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1357 for (i = 0; i < sn->length; i++) {
1358 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1362 pairmake(cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET));
1367 * Get the Expiration Date
1370 asn_time = X509_get_notAfter(client_cert);
1371 if (identity && (lookup <= 1) && asn_time &&
1372 (asn_time->length < MAX_STRING_LEN)) {
1373 memcpy(buf, (char*) asn_time->data, asn_time->length);
1374 buf[asn_time->length] = '\0';
1376 pairmake(cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET));
1380 * Get the Subject & Issuer
1382 subject[0] = issuer[0] = '\0';
1383 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1385 subject[sizeof(subject) - 1] = '\0';
1386 if (identity && (lookup <= 1) && subject[0] &&
1387 (strlen(subject) < MAX_STRING_LEN)) {
1389 pairmake(cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET));
1392 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1394 issuer[sizeof(issuer) - 1] = '\0';
1395 if (identity && (lookup <= 1) && issuer[0] &&
1396 (strlen(issuer) < MAX_STRING_LEN)) {
1398 pairmake(cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET));
1402 * Get the Common Name
1404 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1405 NID_commonName, common_name, sizeof(common_name));
1406 common_name[sizeof(common_name) - 1] = '\0';
1407 if (identity && (lookup <= 1) && common_name[0] &&
1408 (strlen(common_name) < MAX_STRING_LEN)) {
1410 pairmake(cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET));
1415 * Get the RFC822 Subject Alternative Name
1417 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1418 if (lookup <= 1 && loc >= 0) {
1419 X509_EXTENSION *ext = NULL;
1420 GENERAL_NAMES *names = NULL;
1423 if ((ext = X509_get_ext(client_cert, loc)) &&
1424 (names = X509V3_EXT_d2i(ext))) {
1425 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1426 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1428 switch (name->type) {
1430 if (ASN1_STRING_length(name->d.rfc822Name) >= MAX_STRING_LEN)
1434 pairmake(cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1435 ASN1_STRING_data(name->d.rfc822Name), T_OP_SET));
1438 /* XXX TODO handle other SAN types */
1444 sk_GENERAL_NAME_free(names);
1446 #endif /* GEN_EMAIL */
1449 * If the CRL has expired, that might still be OK.
1452 (conf->allow_expired_crl) &&
1453 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1455 X509_STORE_CTX_set_error( ctx, 0 );
1459 const char *p = X509_verify_cert_error_string(err);
1460 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
1461 radius_pairmake(request, &request->packet->vps,
1462 "Module-Failure-Message", p, T_OP_SET);
1466 switch (ctx->error) {
1468 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1469 radlog(L_ERR, "issuer= %s\n", issuer);
1471 case X509_V_ERR_CERT_NOT_YET_VALID:
1472 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1473 radlog(L_ERR, "notBefore=");
1475 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1478 case X509_V_ERR_CERT_HAS_EXPIRED:
1479 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1480 radlog(L_ERR, "notAfter=");
1482 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1488 * If we're at the actual client cert, apply additional
1493 * If the conf tells us to, check cert issuer
1494 * against the specified value and fail
1495 * verification if they don't match.
1497 if (conf->check_cert_issuer &&
1498 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1499 radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1504 * If the conf tells us to, check the CN in the
1505 * cert against xlat'ed value, but only if the
1506 * previous checks passed.
1508 if (my_ok && conf->check_cert_cn) {
1509 if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, request, NULL)) {
1510 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
1511 conf->check_cert_cn);
1512 /* if this fails, fail the verification */
1515 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1516 if (strcmp(cn_str, common_name) != 0) {
1517 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1521 } /* check_cert_cn */
1523 #ifdef HAVE_OPENSSL_OCSP_H
1524 if (my_ok && conf->ocsp_enable){
1525 RDEBUG2("--> Starting OCSP Request");
1526 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1527 radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
1529 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1533 while (conf->verify_client_cert_cmd) {
1538 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1539 conf->verify_tmp_dir, progname);
1540 fd = mkstemp(filename);
1542 RDEBUG("Failed creating file in %s: %s",
1543 conf->verify_tmp_dir, strerror(errno));
1547 fp = fdopen(fd, "w");
1549 RDEBUG("Failed opening file %s: %s",
1550 filename, strerror(errno));
1554 if (!PEM_write_X509(fp, client_cert)) {
1556 RDEBUG("Failed writing certificate to file");
1561 if (!radius_pairmake(request, &request->packet->vps,
1562 "TLS-Client-Cert-Filename",
1563 filename, T_OP_SET)) {
1564 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1569 RDEBUG("Verifying client certificate: %s",
1570 conf->verify_client_cert_cmd);
1571 if (radius_exec_program(conf->verify_client_cert_cmd,
1572 request, 1, NULL, 0,
1573 request->packet->vps,
1575 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
1578 RDEBUG("Client certificate CN %s passed external validation", common_name);
1589 if (debug_flag > 0) {
1590 RDEBUG2("chain-depth=%d, ", depth);
1591 RDEBUG2("error=%d", err);
1593 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1594 RDEBUG2("--> BUF-Name = %s", common_name);
1595 RDEBUG2("--> subject = %s", subject);
1596 RDEBUG2("--> issuer = %s", issuer);
1597 RDEBUG2("--> verify return:%d", my_ok);
1603 #ifdef HAVE_OPENSSL_OCSP_H
1605 * Create Global X509 revocation store and use it to verify
1608 * - Load the trusted CAs
1609 * - Load the trusted issuer certificates
1611 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1613 X509_STORE *store = NULL;
1615 store = X509_STORE_new();
1617 /* Load the CAs we trust */
1618 if (conf->ca_file || conf->ca_path)
1619 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1620 radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1621 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1625 #ifdef X509_V_FLAG_CRL_CHECK
1626 if (conf->check_crl)
1627 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1631 #endif /* HAVE_OPENSSL_OCSP_H */
1633 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1634 #ifndef OPENSSL_NO_ECDH
1635 static int set_ecdh_curve(SSL_CTX *ctx, const char *ecdh_curve)
1640 if (!ecdh_curve || !*ecdh_curve) return 0;
1642 nid = OBJ_sn2nid(ecdh_curve);
1644 radlog(L_ERR, "Unknown ecdh_curve \"%s\"", ecdh_curve);
1648 ecdh = EC_KEY_new_by_curve_name(nid);
1650 radlog(L_ERR, "Unable to create new curve \"%s\"", ecdh_curve);
1654 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1656 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1665 /* index we use to store cached session VPs
1666 * needs to be dynamic so we can supply a "free" function
1668 static int FR_TLS_EX_INDEX_VPS = -1;
1671 * DIE OPENSSL DIE DIE DIE
1673 * What a palaver, just to free some data attached the
1674 * session. We need to do this because the "remove" callback
1675 * is called when refcount > 0 sometimes, if another thread
1676 * is using the session
1678 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1679 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1680 UNUSED long argl, UNUSED void *argp)
1682 VALUE_PAIR *vp = data_ptr;
1685 DEBUG2(" Freeing cached session VPs %p", vp);
1692 * Create Global context SSL and use it in every new session
1694 * - Load the trusted CAs
1695 * - Load the Private key & the certificate
1696 * - Set the Context options & Verify options
1698 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
1700 const SSL_METHOD *meth;
1702 X509_STORE *certstore;
1703 int verify_mode = SSL_VERIFY_NONE;
1704 int ctx_options = 0;
1708 * Add all the default ciphers and message digests
1709 * Create our context.
1712 SSL_load_error_strings();
1715 * SHA256 is in all versions of OpenSSL, but isn't
1716 * initialized by default. It's needed for WiMAX
1719 #ifdef HAVE_OPENSSL_EVP_SHA256
1720 EVP_add_digest(EVP_sha256());
1723 meth = TLSv1_method();
1724 ctx = SSL_CTX_new(meth);
1727 * Identify the type of certificates that needs to be loaded
1729 if (conf->file_type) {
1730 type = SSL_FILETYPE_PEM;
1732 type = SSL_FILETYPE_ASN1;
1736 * Set the password to load private key
1738 if (conf->private_key_password) {
1741 * We don't want to put the private key password in eap.conf, so check
1742 * for our special string which indicates we should get the password
1745 const char* special_string = "Apple:UseCertAdmin";
1746 if (strncmp(conf->private_key_password,
1748 strlen(special_string)) == 0)
1751 const long max_password_len = 128;
1752 snprintf(cmd, sizeof(cmd) - 1,
1753 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
1754 conf->private_key_file);
1756 DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
1758 FILE* cmd_pipe = popen(cmd, "r");
1760 radlog(L_ERR, "rlm_eap: %s command failed. Unable to get private_key_password", cmd);
1761 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1765 free(conf->private_key_password);
1766 conf->private_key_password = malloc(max_password_len * sizeof(char));
1767 if (!conf->private_key_password) {
1768 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
1769 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1774 fgets(conf->private_key_password, max_password_len, cmd_pipe);
1777 /* Get rid of newline at end of password. */
1778 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
1779 DEBUG2("rlm_eap: Password from command = \"%s\"", conf->private_key_password);
1782 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
1783 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
1786 #ifdef PSK_MAX_IDENTITY_LEN
1787 if ((conf->psk_identity && !conf->psk_password) ||
1788 (!conf->psk_identity && conf->psk_password) ||
1789 (conf->psk_identity && !*conf->psk_identity) ||
1790 (conf->psk_password && !*conf->psk_password)) {
1791 radlog(L_ERR, "Invalid PSK Configuration: psk_identity or psk_password are empty");
1795 if (conf->psk_identity) {
1796 size_t psk_len, hex_len;
1797 char buffer[PSK_MAX_PSK_LEN];
1799 if (conf->certificate_file ||
1800 conf->private_key_password || conf->private_key_file ||
1801 conf->ca_file || conf->ca_path) {
1802 radlog(L_ERR, "When PSKs are used, No certificate configuration is permitted");
1807 SSL_CTX_set_psk_client_callback(ctx,
1808 psk_client_callback);
1810 SSL_CTX_set_psk_server_callback(ctx,
1811 psk_server_callback);
1814 psk_len = strlen(conf->psk_password);
1815 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
1816 radlog(L_ERR, "psk_hexphrase is too long (max %d)",
1821 hex_len = fr_hex2bin(conf->psk_password, buffer, psk_len);
1822 if (psk_len != (2 * hex_len)) {
1823 radlog(L_ERR, "psk_hexphrase is not all hex");
1832 * Load our keys and certificates
1834 * If certificates are of type PEM then we can make use
1835 * of cert chain authentication using openssl api call
1836 * SSL_CTX_use_certificate_chain_file. Please see how
1837 * the cert chain needs to be given in PEM from
1840 if (!conf->certificate_file) goto load_ca;
1842 if (type == SSL_FILETYPE_PEM) {
1843 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
1844 radlog(L_ERR, "Error reading certificate file %s:%s",
1845 conf->certificate_file,
1846 ERR_error_string(ERR_get_error(), NULL));
1850 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
1851 radlog(L_ERR, "Error reading certificate file %s:%s",
1852 conf->certificate_file,
1853 ERR_error_string(ERR_get_error(), NULL));
1857 /* Load the CAs we trust */
1859 if (conf->ca_file || conf->ca_path) {
1860 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
1861 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1862 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1866 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
1868 if (conf->private_key_file) {
1869 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
1870 radlog(L_ERR, "Failed reading private key file %s:%s",
1871 conf->private_key_file,
1872 ERR_error_string(ERR_get_error(), NULL));
1877 * Check if the loaded private key is the right one
1879 if (!SSL_CTX_check_private_key(ctx)) {
1880 radlog(L_ERR, "Private key does not match the certificate public key");
1885 #ifdef PSK_MAX_IDENTITY_LEN
1892 ctx_options |= SSL_OP_NO_SSLv2;
1893 ctx_options |= SSL_OP_NO_SSLv3;
1894 #ifdef SSL_OP_NO_TICKET
1895 ctx_options |= SSL_OP_NO_TICKET ;
1899 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
1900 * small subgroup attacks and forward secrecy. Always
1903 * SSL_OP_SINGLE_DH_USE has an impact on the computer
1904 * time needed during negotiation, but it is not very
1907 ctx_options |= SSL_OP_SINGLE_DH_USE;
1910 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
1911 * in Windows Vista client.
1912 * http://www.openssl.org/~bodo/tls-cbc.txt
1913 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
1915 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1917 SSL_CTX_set_options(ctx, ctx_options);
1920 * TODO: Set the RSA & DH
1921 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
1922 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
1926 * set the message callback to identify the type of
1927 * message. For every new session, there can be a
1928 * different callback argument.
1930 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
1934 * Set eliptical curve crypto configuration.
1936 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1937 #ifndef OPENSSL_NO_ECDH
1938 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
1944 /* Set Info callback */
1945 SSL_CTX_set_info_callback(ctx, cbtls_info);
1948 * Callbacks, etc. for session resumption.
1950 if (conf->session_cache_enable) {
1951 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
1952 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
1953 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
1955 SSL_CTX_set_quiet_shutdown(ctx, 1);
1956 if (FR_TLS_EX_INDEX_VPS < 0)
1957 FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
1961 * Check the certificates for revocation.
1963 #ifdef X509_V_FLAG_CRL_CHECK
1964 if (conf->check_crl) {
1965 certstore = SSL_CTX_get_cert_store(ctx);
1966 if (certstore == NULL) {
1967 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1968 radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
1971 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
1977 * Always verify the peer certificate
1979 verify_mode |= SSL_VERIFY_PEER;
1980 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1981 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1982 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
1984 if (conf->verify_depth) {
1985 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
1988 /* Load randomness */
1989 if (!(RAND_load_file(conf->random_file, 1024*1024))) {
1990 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1991 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
1996 * Set the cipher list if we were told to
1998 if (conf->cipher_list) {
1999 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2000 radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
2006 * Setup session caching
2008 if (conf->session_cache_enable) {
2010 * Create a unique context Id per EAP-TLS configuration.
2012 if (conf->session_id_name) {
2013 snprintf(conf->session_context_id,
2014 sizeof(conf->session_context_id),
2016 conf->session_id_name);
2018 snprintf(conf->session_context_id,
2019 sizeof(conf->session_context_id),
2024 * Cache it, and DON'T auto-clear it.
2026 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2028 SSL_CTX_set_session_id_context(ctx,
2029 (unsigned char *) conf->session_context_id,
2030 (unsigned int) strlen(conf->session_context_id));
2033 * Our timeout is in hours, this is in seconds.
2035 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2038 * Set the maximum number of entries in the
2041 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2044 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2051 void tls_server_conf_free(fr_tls_server_conf_t *conf)
2055 if (conf->cs) cf_section_parse_free(conf->cs, conf);
2057 if (conf->ctx) SSL_CTX_free(conf->ctx);
2059 #ifdef HAVE_OPENSSL_OCSP_H
2060 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2061 conf->ocsp_store = NULL;
2064 memset(conf, 0, sizeof(*conf));
2069 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2071 fr_tls_server_conf_t *conf;
2073 conf = malloc(sizeof(*conf));
2075 radlog(L_ERR, "Out of memory");
2078 memset(conf, 0, sizeof(*conf));
2080 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2082 tls_server_conf_free(conf);
2087 * Save people from their own stupidity.
2089 if (conf->fragment_size < 100) conf->fragment_size = 100;
2092 * This magic makes the administrators life HUGELY easier
2093 * on initial deployments.
2095 * If the server starts up in debugging mode, AND the
2096 * bootstrap command is configured, AND it exists, AND
2097 * there is no server certificate
2099 if (conf->make_cert_command && (debug_flag >= 2)) {
2102 if ((stat(conf->make_cert_command, &buf) == 0) &&
2103 (stat(conf->certificate_file, &buf) < 0) &&
2104 (errno == ENOENT) &&
2105 (radius_exec_program(conf->make_cert_command, NULL, 1,
2106 NULL, 0, NULL, NULL, 0) != 0)) {
2111 if (!conf->private_key_file) {
2112 radlog(L_ERR, "TLS Server requires a private key file");
2116 if (!conf->certificate_file) {
2117 radlog(L_ERR, "TLS Server requires a certificate file");
2124 conf->ctx = init_tls_ctx(conf, 0);
2125 if (conf->ctx == NULL) {
2129 #ifdef HAVE_OPENSSL_OCSP_H
2131 * Initialize OCSP Revocation Store
2133 if (conf->ocsp_enable) {
2134 conf->ocsp_store = init_revocation_store(conf);
2135 if (conf->ocsp_store == NULL) goto error;
2137 #endif /*HAVE_OPENSSL_OCSP_H*/
2139 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2143 if (generate_eph_rsa_key(conf->ctx) < 0) {
2147 if (conf->verify_tmp_dir) {
2148 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2149 radlog(L_ERR, "Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
2154 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2155 radlog(L_ERR, "You MUST set the verify directory in order to use verify_client_cmd");
2162 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2164 fr_tls_server_conf_t *conf;
2166 conf = malloc(sizeof(*conf));
2168 radlog(L_ERR, "Out of memory");
2171 memset(conf, 0, sizeof(*conf));
2173 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2175 tls_server_conf_free(conf);
2180 * Save people from their own stupidity.
2182 if (conf->fragment_size < 100) conf->fragment_size = 100;
2187 conf->ctx = init_tls_ctx(conf, 1);
2188 if (conf->ctx == NULL) {
2192 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2196 if (generate_eph_rsa_key(conf->ctx) < 0) {
2203 int tls_success(tls_session_t *ssn, REQUEST *request)
2205 VALUE_PAIR *vp, *vps = NULL;
2206 fr_tls_server_conf_t *conf;
2208 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2209 rad_assert(conf != NULL);
2212 * If there's no session resumption, delete the entry
2213 * from the cache. This means either it's disabled
2214 * globally for this SSL context, OR we were told to
2215 * disable it for this user.
2217 * This also means you can't turn it on just for one
2220 if ((!ssn->allow_session_resumption) ||
2221 (((vp = pairfind(request->config_items, 1127, 0)) != NULL) &&
2222 (vp->vp_integer == 0))) {
2223 SSL_CTX_remove_session(ssn->ctx,
2225 ssn->allow_session_resumption = 0;
2228 * If we're in a resumed session and it's
2231 if (SSL_session_reused(ssn->ssl)) {
2232 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed.");
2237 * Else resumption IS allowed, so we store the
2238 * user data in the cache.
2240 } else if (!SSL_session_reused(ssn->ssl)) {
2242 char buffer[2 * MAX_SESSION_SIZE + 1];
2244 size = ssn->ssl->session->session_id_length;
2245 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2247 fr_bin2hex(ssn->ssl->session->session_id, buffer, size);
2250 vp = paircopy2(request->reply->vps, PW_USER_NAME, 0);
2251 if (vp) pairadd(&vps, vp);
2253 vp = paircopy2(request->packet->vps, PW_STRIPPED_USER_NAME, 0);
2254 if (vp) pairadd(&vps, vp);
2256 vp = paircopy2(request->reply->vps, PW_CACHED_SESSION_POLICY, 0);
2257 if (vp) pairadd(&vps, vp);
2260 RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2261 SSL_SESSION_set_ex_data(ssn->ssl->session,
2262 FR_TLS_EX_INDEX_VPS, vps);
2264 RDEBUG2("WARNING: No information to cache: session caching will be disabled for session %s", buffer);
2265 SSL_CTX_remove_session(ssn->ctx,
2270 * Else the session WAS allowed. Copy the cached
2275 char buffer[2 * MAX_SESSION_SIZE + 1];
2277 size = ssn->ssl->session->session_id_length;
2278 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2280 fr_bin2hex(ssn->ssl->session->session_id, buffer, size);
2283 vp = SSL_SESSION_get_ex_data(ssn->ssl->session,
2284 FR_TLS_EX_INDEX_VPS);
2286 RDEBUG("WARNING: No information in cached session %s", buffer);
2290 RDEBUG("Adding cached attributes for session %s vps %p to the reply:", buffer, vp);
2291 debug_pair_list(vp);
2292 pairadd(&request->reply->vps, paircopy(vp));
2295 * Mark the request as resumed.
2297 vp = pairmake("EAP-Session-Resumed", "1", T_OP_SET);
2298 if (vp) pairadd(&request->packet->vps, vp);
2306 void tls_fail(tls_session_t *ssn)
2309 * Force the session to NOT be cached.
2311 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2314 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2321 * Decrypt the complete record.
2323 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2324 ssn->dirty_in.used);
2325 if (err != (int) ssn->dirty_in.used) {
2326 record_init(&ssn->dirty_in);
2327 RDEBUG("Failed writing %d to SSL BIO: %d",
2328 ssn->dirty_in.used, err);
2333 * Clear the dirty buffer now that we are done with it
2334 * and init the clean_out buffer to store decrypted data
2336 record_init(&ssn->dirty_in);
2337 record_init(&ssn->clean_out);
2340 * Read (and decrypt) the tunneled data from the
2341 * SSL session, and put it into the decrypted
2344 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2345 sizeof(ssn->clean_out.data));
2350 RDEBUG("SSL_read Error");
2352 code = SSL_get_error(ssn->ssl, err);
2354 case SSL_ERROR_WANT_READ:
2355 return FR_TLS_MORE_FRAGMENTS;
2356 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2359 case SSL_ERROR_WANT_WRITE:
2360 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2364 DEBUG("Error in fragmentation logic: ?");
2367 * FIXME: Call int_ssl_check?
2375 RDEBUG("WARNING: No data inside of the tunnel.");
2379 * Passed all checks, successfully decrypted data
2381 ssn->clean_out.used = err;
2388 * Acknowledge received is for one of the following messages sent earlier
2389 * 1. Handshake completed Message, so now send, EAP-Success
2390 * 2. Alert Message, now send, EAP-Failure
2391 * 3. Fragment Message, now send, next Fragment
2393 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2395 RDEBUG2("Received TLS ACK");
2398 radlog_request(L_ERR, 0, request, "FAIL: Unexpected ACK received. Could not obtain session information.");
2399 return FR_TLS_INVALID;
2401 if (ssn->info.initialized == 0) {
2402 RDEBUG("No SSL info available. Waiting for more SSL data.");
2403 return FR_TLS_REQUEST;
2405 if ((ssn->info.content_type == handshake) &&
2406 (ssn->info.origin == 0)) {
2407 radlog_request(L_ERR, 0, request, "FAIL: ACK without earlier message.");
2408 return FR_TLS_INVALID;
2411 switch (ssn->info.content_type) {
2413 RDEBUG2("ACK alert");
2417 if ((ssn->info.handshake_type == finished) &&
2418 (ssn->dirty_out.used == 0)) {
2419 RDEBUG2("ACK handshake is finished");
2422 * From now on all the content is
2423 * application data set it here as nobody else
2426 ssn->info.content_type = application_data;
2427 return FR_TLS_SUCCESS;
2428 } /* else more data to send */
2430 RDEBUG2("ACK handshake fragment handler");
2431 /* Fragmentation handler, send next fragment */
2432 return FR_TLS_REQUEST;
2434 case application_data:
2435 RDEBUG2("ACK handshake fragment handler in application data");
2436 return FR_TLS_REQUEST;
2439 * For the rest of the conditions, switch over
2440 * to the default section below.
2443 RDEBUG2("ACK default");
2444 radlog_request(L_ERR, 0, request, "Invalid ACK received: %d",
2445 ssn->info.content_type);
2446 return FR_TLS_INVALID;
2450 static void dump_hex(const char *msg, const uint8_t *data, size_t data_len)
2454 if (debug_flag < 3) return;
2456 printf("%s %d\n", msg, (int) data_len);
2457 if (data_len > 256) data_len = 256;
2459 for (i = 0; i < data_len; i++) {
2460 if ((i & 0x0f) == 0x00) printf ("%02x: ", (unsigned int) i);
2461 printf("%02x ", data[i]);
2462 if ((i & 0x0f) == 0x0f) printf ("\n");
2468 static void tls_socket_close(rad_listen_t *listener)
2470 listen_socket_t *sock = listener->data;
2472 listener->status = RAD_LISTEN_STATUS_REMOVE_FD;
2473 listener->tls = NULL; /* parent owns this! */
2477 * Decrement the number of connections.
2479 if (sock->parent->num_connections > 0) {
2480 sock->parent->num_connections--;
2482 if (sock->client->num_connections > 0) {
2483 sock->client->num_connections--;
2488 * Tell the event handler that an FD has disappeared.
2490 DEBUG("Client has closed connection");
2491 event_new_fd(listener);
2494 * Do NOT free the listener here. It's in use by
2495 * a request, and will need to hang around until
2496 * all of the requests are done.
2498 * It is instead free'd in remove_from_request_hash()
2502 static int tls_socket_write(rad_listen_t *listener, REQUEST *request)
2506 listen_socket_t *sock = listener->data;
2508 p = sock->ssn->dirty_out.data;
2510 while (p < (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used)) {
2511 RDEBUG3("Writing to socket %d", request->packet->sockfd);
2512 rcode = write(request->packet->sockfd, p,
2513 (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used) - p);
2515 RDEBUG("Error writing to TLS socket: %s", strerror(errno));
2517 tls_socket_close(listener);
2523 sock->ssn->dirty_out.used = 0;
2529 static int tls_socket_recv(rad_listen_t *listener)
2531 int doing_init = FALSE;
2533 RADIUS_PACKET *packet;
2535 listen_socket_t *sock = listener->data;
2536 fr_tls_status_t status;
2537 RADCLIENT *client = sock->client;
2539 if (!sock->packet) {
2540 sock->packet = rad_alloc(0);
2541 if (!sock->packet) return 0;
2543 sock->packet->sockfd = listener->fd;
2544 sock->packet->src_ipaddr = sock->other_ipaddr;
2545 sock->packet->src_port = sock->other_port;
2546 sock->packet->dst_ipaddr = sock->my_ipaddr;
2547 sock->packet->dst_port = sock->my_port;
2549 if (sock->request) sock->request->packet = sock->packet;
2553 * Allocate a REQUEST for debugging.
2555 if (!sock->request) {
2556 sock->request = request = request_alloc();
2557 if (!sock->request) {
2558 radlog(L_ERR, "Out of memory");
2562 rad_assert(request->packet == NULL);
2563 rad_assert(sock->packet != NULL);
2564 request->packet = sock->packet;
2566 request->component = "<core>";
2567 request->component = "<tls-connect>";
2570 * Not sure if we should do this on every packet...
2572 request->reply = rad_alloc(0);
2573 if (!request->reply) return 0;
2575 request->options = RAD_REQUEST_OPTION_DEBUG2;
2577 rad_assert(sock->ssn == NULL);
2579 sock->ssn = tls_new_session(listener->tls, sock->request,
2580 listener->tls->require_client_cert);
2582 request_free(&sock->request);
2583 sock->packet = NULL;
2587 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
2588 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_CERTS, (void *)&request->packet->vps);
2593 rad_assert(sock->request != NULL);
2594 rad_assert(sock->request->packet != NULL);
2595 rad_assert(sock->packet != NULL);
2596 rad_assert(sock->ssn != NULL);
2598 request = sock->request;
2600 RDEBUG3("Reading from socket %d", request->packet->sockfd);
2601 PTHREAD_MUTEX_LOCK(&sock->mutex);
2602 rcode = read(request->packet->sockfd,
2603 sock->ssn->dirty_in.data,
2604 sizeof(sock->ssn->dirty_in.data));
2605 if ((rcode < 0) && (errno == ECONNRESET)) {
2607 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2608 tls_socket_close(listener);
2613 RDEBUG("Error reading TLS socket: %s", strerror(errno));
2618 * Normal socket close.
2620 if (rcode == 0) goto do_close;
2622 sock->ssn->dirty_in.used = rcode;
2623 memset(sock->ssn->dirty_in.data + sock->ssn->dirty_in.used,
2626 dump_hex("READ FROM SSL", sock->ssn->dirty_in.data, sock->ssn->dirty_in.used);
2629 * Catch attempts to use non-SSL.
2631 if (doing_init && (sock->ssn->dirty_in.data[0] != handshake)) {
2632 RDEBUG("Non-TLS data sent to TLS socket: closing");
2637 * Skip ahead to reading application data.
2639 if (SSL_is_init_finished(sock->ssn->ssl)) goto app;
2641 if (!tls_handshake_recv(request, sock->ssn)) {
2642 RDEBUG("FAILED in TLS handshake receive");
2646 if (sock->ssn->dirty_out.used > 0) {
2647 tls_socket_write(listener, request);
2648 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2654 * FIXME: Run the packet through a virtual server in
2655 * order to see if we like the certificate presented by
2659 status = tls_application_data(sock->ssn, request);
2660 RDEBUG("Application data status %d", status);
2662 if (status == FR_TLS_MORE_FRAGMENTS) {
2663 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2667 if (sock->ssn->clean_out.used == 0) {
2668 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2672 dump_hex("TUNNELED DATA", sock->ssn->clean_out.data, sock->ssn->clean_out.used);
2675 * If the packet is a complete RADIUS packet, return it to
2676 * the caller. Otherwise...
2678 if ((sock->ssn->clean_out.used < 20) ||
2679 (((sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]) != (int) sock->ssn->clean_out.used)) {
2680 RDEBUG("Received bad packet: Length %d contents %d",
2681 sock->ssn->clean_out.used,
2682 (sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]);
2686 packet = sock->packet;
2687 packet->data = rad_malloc(sock->ssn->clean_out.used);
2688 packet->data_len = sock->ssn->clean_out.used;
2689 record_minus(&sock->ssn->clean_out, packet->data, packet->data_len);
2691 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2693 if (!rad_packet_ok(packet, 0)) {
2694 RDEBUG("Received bad packet: %s", fr_strerror());
2695 tls_socket_close(listener);
2696 return 0; /* do_close unlocks the mutex */
2700 * Copied from src/lib/radius.c, rad_recv();
2702 if (fr_debug_flag) {
2703 char host_ipaddr[128];
2705 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2706 RDEBUG("tls_recv: %s packet from host %s port %d, id=%d, length=%d",
2707 fr_packet_codes[packet->code],
2708 inet_ntop(packet->src_ipaddr.af,
2709 &packet->src_ipaddr.ipaddr,
2710 host_ipaddr, sizeof(host_ipaddr)),
2712 packet->id, (int) packet->data_len);
2714 RDEBUG("tls_recv: Packet from host %s port %d code=%d, id=%d, length=%d",
2715 inet_ntop(packet->src_ipaddr.af,
2716 &packet->src_ipaddr.ipaddr,
2717 host_ipaddr, sizeof(host_ipaddr)),
2720 packet->id, (int) packet->data_len);
2724 FR_STATS_INC(auth, total_requests);
2730 int dual_tls_recv(rad_listen_t *listener)
2732 RADIUS_PACKET *packet;
2734 RAD_REQUEST_FUNP fun = NULL;
2735 listen_socket_t *sock = listener->data;
2736 RADCLIENT *client = sock->client;
2738 if (!tls_socket_recv(listener)) {
2742 rad_assert(sock->request != NULL);
2743 rad_assert(sock->request->packet != NULL);
2744 rad_assert(sock->packet != NULL);
2745 rad_assert(sock->ssn != NULL);
2747 request = sock->request;
2748 packet = sock->packet;
2751 * Some sanity checks, based on the packet code.
2753 switch(packet->code) {
2754 case PW_AUTHENTICATION_REQUEST:
2755 if (listener->type != RAD_LISTEN_AUTH) goto bad_packet;
2756 FR_STATS_INC(auth, total_requests);
2757 fun = rad_authenticate;
2760 case PW_ACCOUNTING_REQUEST:
2761 if (listener->type != RAD_LISTEN_ACCT) goto bad_packet;
2762 FR_STATS_INC(acct, total_requests);
2763 fun = rad_accounting;
2766 case PW_STATUS_SERVER:
2767 if (!mainconfig.status_server) {
2768 FR_STATS_INC(auth, total_unknown_types);
2769 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
2770 rad_free(&sock->packet);
2771 request->packet = NULL;
2774 fun = rad_status_server;
2779 FR_STATS_INC(auth, total_unknown_types);
2781 DEBUG("Invalid packet code %d sent from client %s port %d : IGNORED",
2782 packet->code, client->shortname, packet->src_port);
2783 rad_free(&sock->packet);
2784 request->packet = NULL;
2786 } /* switch over packet types */
2788 if (!request_receive(listener, packet, client, fun)) {
2789 FR_STATS_INC(auth, total_packets_dropped);
2790 rad_free(&sock->packet);
2791 request->packet = NULL;
2795 sock->packet = NULL; /* we have no need for more partial reads */
2796 request->packet = NULL;
2803 * Send a response packet
2805 int dual_tls_send(rad_listen_t *listener, REQUEST *request)
2807 listen_socket_t *sock = listener->data;
2809 rad_assert(request->listener == listener);
2810 rad_assert(listener->send == dual_tls_send);
2813 * Accounting reject's are silently dropped.
2815 * We do it here to avoid polluting the rest of the
2816 * code with this knowledge
2818 if (request->reply->code == 0) return 0;
2823 if (rad_encode(request->reply, request->packet,
2824 request->client->secret) < 0) {
2825 RDEBUG("Failed encoding packet: %s", fr_strerror());
2832 if (rad_sign(request->reply, request->packet,
2833 request->client->secret) < 0) {
2834 RDEBUG("Failed signing packet: %s", fr_strerror());
2838 PTHREAD_MUTEX_LOCK(&sock->mutex);
2840 * Write the packet to the SSL buffers.
2842 record_plus(&sock->ssn->clean_in,
2843 request->reply->data, request->reply->data_len);
2846 * Do SSL magic to get encrypted data.
2848 tls_handshake_send(request, sock->ssn);
2851 * And finally write the data to the socket.
2853 if (sock->ssn->dirty_out.used > 0) {
2854 dump_hex("WRITE TO SSL", sock->ssn->dirty_out.data, sock->ssn->dirty_out.used);
2856 tls_socket_write(listener, request);
2858 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2864 int proxy_tls_recv(rad_listen_t *listener)
2868 listen_socket_t *sock = listener->data;
2871 RADIUS_PACKET *packet;
2872 RAD_REQUEST_FUNP fun = NULL;
2874 DEBUG3("Proxy SSL socket has data to read");
2875 PTHREAD_MUTEX_LOCK(&sock->mutex);
2877 rcode = SSL_read(sock->ssn->ssl, data, 4);
2879 int err = SSL_get_error(sock->ssn->ssl, rcode);
2881 case SSL_ERROR_WANT_READ:
2882 case SSL_ERROR_WANT_WRITE:
2885 case SSL_ERROR_ZERO_RETURN:
2886 /* remote end sent close_notify, send one back */
2887 SSL_shutdown(sock->ssn->ssl);
2889 case SSL_ERROR_SYSCALL:
2891 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2892 tls_socket_close(listener);
2896 while ((err = ERR_get_error())) {
2897 DEBUG("proxy recv says %s",
2898 ERR_error_string(err, NULL));
2905 length = (data[2] << 8) | data[3];
2906 DEBUG3("Proxy received header saying we have a packet of %u bytes",
2907 (unsigned int) length);
2909 if (length > sizeof(data)) {
2910 DEBUG("Received packet will be too large! (%u)",
2911 (data[2] << 8) | data[3]);
2915 rcode = SSL_read(sock->ssn->ssl, data + 4, length);
2917 switch (SSL_get_error(sock->ssn->ssl, rcode)) {
2918 case SSL_ERROR_WANT_READ:
2919 case SSL_ERROR_WANT_WRITE:
2923 case SSL_ERROR_ZERO_RETURN:
2924 /* remote end sent close_notify, send one back */
2925 SSL_shutdown(sock->ssn->ssl);
2931 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2933 packet = rad_alloc(0);
2934 packet->sockfd = listener->fd;
2935 packet->src_ipaddr = sock->other_ipaddr;
2936 packet->src_port = sock->other_port;
2937 packet->dst_ipaddr = sock->my_ipaddr;
2938 packet->dst_port = sock->my_port;
2939 packet->code = data[0];
2940 packet->id = data[1];
2941 packet->data_len = length;
2942 packet->data = rad_malloc(packet->data_len);
2943 memcpy(packet->data, data, packet->data_len);
2944 memcpy(packet->vector, packet->data + 4, 16);
2947 * FIXME: Client MIB updates?
2949 switch(packet->code) {
2950 case PW_AUTHENTICATION_ACK:
2951 case PW_ACCESS_CHALLENGE:
2952 case PW_AUTHENTICATION_REJECT:
2953 fun = rad_authenticate;
2956 #ifdef WITH_ACCOUNTING
2957 case PW_ACCOUNTING_RESPONSE:
2958 fun = rad_accounting;
2964 * FIXME: Update MIB for packet types?
2966 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
2967 "from home server %s port %d - ID %d : IGNORED",
2969 ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
2970 packet->src_port, packet->id);
2975 if (!request_proxy_reply(packet)) {
2983 int proxy_tls_send(rad_listen_t *listener, REQUEST *request)
2986 listen_socket_t *sock = listener->data;
2989 * Normal proxying calls us with the data already
2990 * encoded. The "ping home server" code does not. So,
2991 * if there's no packet, encode it here.
2993 if (!request->proxy->data) {
2994 request->proxy_listener->encode(request->proxy_listener,
2998 DEBUG3("Proxy is writing %u bytes to SSL",
2999 (unsigned int) request->proxy->data_len);
3000 PTHREAD_MUTEX_LOCK(&sock->mutex);
3001 while ((rcode = SSL_write(sock->ssn->ssl, request->proxy->data,
3002 request->proxy->data_len)) < 0) {
3004 while ((err = ERR_get_error())) {
3005 DEBUG("proxy SSL_write says %s",
3006 ERR_error_string(err, NULL));
3008 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
3009 tls_socket_close(listener);
3012 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
3017 #endif /* WITH_TLS */