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 tls_session_t *tls_new_client_session(fr_tls_server_conf_t *conf, int fd)
66 tls_session_t *ssn = NULL;
68 ssn = (tls_session_t *) malloc(sizeof(*ssn));
69 memset(ssn, 0, sizeof(*ssn));
72 ssn->ssl = SSL_new(ssn->ctx);
73 rad_assert(ssn->ssl != NULL);
76 * Add the message callback to identify what type of
77 * message/handshake is passed
79 SSL_set_msg_callback(ssn->ssl, cbtls_msg);
80 SSL_set_msg_callback_arg(ssn->ssl, ssn);
81 SSL_set_info_callback(ssn->ssl, cbtls_info);
84 * Always verify the peer certificate.
86 DEBUG2("Requiring Server certificate");
87 verify_mode = SSL_VERIFY_PEER;
88 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
89 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
91 SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
92 SSL_set_fd(ssn->ssl, fd);
93 if (SSL_connect(ssn->ssl) <= 0) {
95 while ((err = ERR_get_error())) {
96 DEBUG("OpenSSL Err says %s",
97 ERR_error_string(err, NULL));
106 tls_session_t *tls_new_session(fr_tls_server_conf_t *conf, REQUEST *request,
109 tls_session_t *state = NULL;
115 * Manually flush the sessions every so often. If HALF
116 * of the session lifetime has passed since we last
117 * flushed, then flush it again.
119 * FIXME: Also do it every N sessions?
121 if (conf->session_cache_enable &&
122 ((conf->session_last_flushed + (conf->session_timeout * 1800)) <= request->timestamp)){
123 RDEBUG2("Flushing SSL sessions (of #%ld)",
124 SSL_CTX_sess_number(conf->ctx));
126 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
127 conf->session_last_flushed = request->timestamp;
130 if ((new_tls = SSL_new(conf->ctx)) == NULL) {
131 radlog(L_ERR, "SSL: Error creating new SSL: %s",
132 ERR_error_string(ERR_get_error(), NULL));
136 /* We use the SSL's "app_data" to indicate a call-back */
137 SSL_set_app_data(new_tls, NULL);
139 state = (tls_session_t *)malloc(sizeof(*state));
140 memset(state, 0, sizeof(*state));
143 state->ctx = conf->ctx;
144 state->ssl = new_tls;
147 * Initialize callbacks
149 state->record_init = record_init;
150 state->record_close = record_close;
151 state->record_plus = record_plus;
152 state->record_minus = record_minus;
155 * Create & hook the BIOs to handle the dirty side of the
156 * SSL. This is *very important* as we want to handle
157 * the transmission part. Now the only IO interface
158 * that SSL is aware of, is our defined BIO buffers.
160 * This means that all SSL IO is done to/from memory,
161 * and we can update those BIOs from the packets we've
164 state->into_ssl = BIO_new(BIO_s_mem());
165 state->from_ssl = BIO_new(BIO_s_mem());
166 SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
169 * Add the message callback to identify what type of
170 * message/handshake is passed
172 SSL_set_msg_callback(new_tls, cbtls_msg);
173 SSL_set_msg_callback_arg(new_tls, state);
174 SSL_set_info_callback(new_tls, cbtls_info);
177 * In Server mode we only accept.
179 SSL_set_accept_state(state->ssl);
182 * Verify the peer certificate, if asked.
185 RDEBUG2("Requiring client certificate");
186 verify_mode = SSL_VERIFY_PEER;
187 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
188 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
190 SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
192 SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
193 state->length_flag = conf->include_length;
196 * We use default fragment size, unless the Framed-MTU
197 * tells us it's too big. Note that we do NOT account
198 * for the EAP-TLS headers if conf->fragment_size is
199 * large, because that config item looks to be confusing.
201 * i.e. it should REALLY be called MTU, and the code here
202 * should figure out what that means for TLS fragment size.
203 * asking the administrator to know the internal details
204 * of EAP-TLS in order to calculate fragment sizes is
207 state->offset = conf->fragment_size;
208 vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0);
209 if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
210 state->offset = vp->vp_integer;
213 if (conf->session_cache_enable) {
214 state->allow_session_resumption = 1; /* otherwise it's zero */
223 * Print out some text describing the error.
225 static int int_ssl_check(REQUEST *request, SSL *s, int ret, const char *text)
230 if ((l = ERR_get_error()) != 0) {
231 const char *p = ERR_error_string(l, NULL);
234 radlog(L_ERR, "SSL error %s", p);
237 vp = pairmake("Module-Failure-Message", p, T_OP_ADD);
238 if (vp) pairadd(&request->packet->vps, vp);
241 e = SSL_get_error(s, ret);
245 * These seem to be harmless and already "dealt
246 * with" by our non-blocking environment. NB:
247 * "ZERO_RETURN" is the clean "error"
248 * indicating a successfully closed SSL
249 * tunnel. We let this happen because our IO
250 * loop should not appear to have broken on
251 * this condition - and outside the IO loop, the
252 * "shutdown" state is checked.
254 * Don't print anything if we ignore the error.
257 case SSL_ERROR_WANT_READ:
258 case SSL_ERROR_WANT_WRITE:
259 case SSL_ERROR_WANT_X509_LOOKUP:
260 case SSL_ERROR_ZERO_RETURN:
264 * These seem to be indications of a genuine
265 * error that should result in the SSL tunnel
266 * being regarded as "dead".
268 case SSL_ERROR_SYSCALL:
269 radlog(L_ERR, "SSL: %s failed in a system call (%d), TLS session fails.",
274 radlog(L_ERR, "SSL: %s failed inside of TLS (%d), TLS session fails.",
280 * For any other errors that (a) exist, and (b)
281 * crop up - we need to interpret what to do with
282 * them - so "politely inform" the caller that
283 * the code needs updating here.
285 radlog(L_ERR, "SSL: FATAL SSL error ..... %d\n", e);
293 * We are the server, we always get the dirty data
294 * (Handshake data is also considered as dirty data)
295 * During handshake, since SSL API handles itself,
296 * After clean-up, dirty_out will be filled with
297 * the data required for handshaking. So we check
298 * if dirty_out is empty then we simply send it back.
299 * As of now, if handshake is successful, then we keep going,
302 * Fill the Bio with the dirty data to clean it
303 * Get the cleaned data from SSL, if it is not Handshake data
305 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
309 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
310 if (err != (int) ssn->dirty_in.used) {
311 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
313 record_init(&ssn->dirty_in);
316 record_init(&ssn->dirty_in);
318 err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
319 sizeof(ssn->clean_out.data) - ssn->clean_out.used);
321 ssn->clean_out.used += err;
325 if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
329 /* Some Extra STATE information for easy debugging */
330 if (SSL_is_init_finished(ssn->ssl)) {
331 DEBUG2("SSL Connection Established\n");
333 if (SSL_in_init(ssn->ssl)) {
334 DEBUG2("In SSL Handshake Phase\n");
336 if (SSL_in_before(ssn->ssl)) {
337 DEBUG2("Before SSL Handshake Phase\n");
339 if (SSL_in_accept_init(ssn->ssl)) {
340 DEBUG2("In SSL Accept mode \n");
342 if (SSL_in_connect_init(ssn->ssl)) {
343 DEBUG2("In SSL Connect mode \n");
346 err = BIO_ctrl_pending(ssn->from_ssl);
348 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
349 sizeof(ssn->dirty_out.data));
351 ssn->dirty_out.used = err;
353 } else if (BIO_should_retry(ssn->from_ssl)) {
354 record_init(&ssn->dirty_in);
355 DEBUG2(" tls: Asking for more data in tunnel");
359 int_ssl_check(request, ssn->ssl, err, "BIO_read");
360 record_init(&ssn->dirty_in);
364 DEBUG2("SSL Application Data");
365 /* Its clean application data, do whatever we want */
366 record_init(&ssn->clean_out);
369 /* We are done with dirty_in, reinitialize it */
370 record_init(&ssn->dirty_in);
375 * Take clear-text user data, and encrypt it into the output buffer,
376 * to send to the client at the other end of the SSL connection.
378 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
383 * If there's un-encrypted data in 'clean_in', then write
384 * that data to the SSL session, and then call the BIO function
385 * to get that encrypted data from the SSL session, into
386 * a buffer which we can then package into an EAP packet.
388 * Based on Server's logic this clean_in is expected to
389 * contain the data to send to the client.
391 if (ssn->clean_in.used > 0) {
394 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
395 record_minus(&ssn->clean_in, NULL, written);
397 /* Get the dirty data from Bio to send it */
398 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
399 sizeof(ssn->dirty_out.data));
401 ssn->dirty_out.used = err;
403 int_ssl_check(request, ssn->ssl, err, "handshake_send");
410 void session_init(tls_session_t *ssn)
413 ssn->into_ssl = ssn->from_ssl = NULL;
414 record_init(&ssn->clean_in);
415 record_init(&ssn->clean_out);
416 record_init(&ssn->dirty_in);
417 record_init(&ssn->dirty_out);
419 memset(&ssn->info, 0, sizeof(ssn->info));
423 ssn->tls_msg_len = 0;
424 ssn->length_flag = 0;
426 ssn->free_opaque = NULL;
429 void session_close(tls_session_t *ssn)
431 SSL_set_quiet_shutdown(ssn->ssl, 1);
432 SSL_shutdown(ssn->ssl);
437 record_close(&ssn->clean_in);
438 record_close(&ssn->clean_out);
439 record_close(&ssn->dirty_in);
440 record_close(&ssn->dirty_out);
444 void session_free(void *ssn)
446 tls_session_t *sess = (tls_session_t *)ssn;
451 * Free any opaque TTLS or PEAP data.
453 if ((sess->opaque) && (sess->free_opaque)) {
454 sess->free_opaque(sess->opaque);
463 static void record_init(record_t *rec)
468 static void record_close(record_t *rec)
475 * Copy data to the intermediate buffer, before we send
478 static unsigned int record_plus(record_t *rec, const void *ptr,
481 unsigned int added = MAX_RECORD_SIZE - rec->used;
487 memcpy(rec->data + rec->used, ptr, added);
493 * Take data from the buffer, and give it to the caller.
495 static unsigned int record_minus(record_t *rec, void *ptr,
498 unsigned int taken = rec->used;
505 memcpy(ptr, rec->data, taken);
509 * This is pretty bad...
512 memmove(rec->data, rec->data + taken, rec->used);
516 void tls_session_information(tls_session_t *tls_session)
518 const char *str_write_p, *str_version, *str_content_type = "";
519 const char *str_details1 = "", *str_details2= "";
523 * Don't print this out in the normal course of
526 if (debug_flag == 0) {
530 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
532 switch (tls_session->info.version)
535 str_version = "SSL 2.0";
538 str_version = "SSL 3.0 ";
541 str_version = "TLS 1.0 ";
544 str_version = "Unknown TLS version";
548 if (tls_session->info.version == SSL3_VERSION ||
549 tls_session->info.version == TLS1_VERSION) {
550 switch (tls_session->info.content_type) {
551 case SSL3_RT_CHANGE_CIPHER_SPEC:
552 str_content_type = "ChangeCipherSpec";
555 str_content_type = "Alert";
557 case SSL3_RT_HANDSHAKE:
558 str_content_type = "Handshake";
560 case SSL3_RT_APPLICATION_DATA:
561 str_content_type = "ApplicationData";
564 str_content_type = "UnknownContentType";
568 if (tls_session->info.content_type == SSL3_RT_ALERT) {
569 str_details1 = ", ???";
571 if (tls_session->info.record_len == 2) {
573 switch (tls_session->info.alert_level) {
574 case SSL3_AL_WARNING:
575 str_details1 = ", warning";
578 str_details1 = ", fatal";
582 str_details2 = " ???";
583 switch (tls_session->info.alert_description) {
584 case SSL3_AD_CLOSE_NOTIFY:
585 str_details2 = " close_notify";
587 case SSL3_AD_UNEXPECTED_MESSAGE:
588 str_details2 = " unexpected_message";
590 case SSL3_AD_BAD_RECORD_MAC:
591 str_details2 = " bad_record_mac";
593 case TLS1_AD_DECRYPTION_FAILED:
594 str_details2 = " decryption_failed";
596 case TLS1_AD_RECORD_OVERFLOW:
597 str_details2 = " record_overflow";
599 case SSL3_AD_DECOMPRESSION_FAILURE:
600 str_details2 = " decompression_failure";
602 case SSL3_AD_HANDSHAKE_FAILURE:
603 str_details2 = " handshake_failure";
605 case SSL3_AD_BAD_CERTIFICATE:
606 str_details2 = " bad_certificate";
608 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
609 str_details2 = " unsupported_certificate";
611 case SSL3_AD_CERTIFICATE_REVOKED:
612 str_details2 = " certificate_revoked";
614 case SSL3_AD_CERTIFICATE_EXPIRED:
615 str_details2 = " certificate_expired";
617 case SSL3_AD_CERTIFICATE_UNKNOWN:
618 str_details2 = " certificate_unknown";
620 case SSL3_AD_ILLEGAL_PARAMETER:
621 str_details2 = " illegal_parameter";
623 case TLS1_AD_UNKNOWN_CA:
624 str_details2 = " unknown_ca";
626 case TLS1_AD_ACCESS_DENIED:
627 str_details2 = " access_denied";
629 case TLS1_AD_DECODE_ERROR:
630 str_details2 = " decode_error";
632 case TLS1_AD_DECRYPT_ERROR:
633 str_details2 = " decrypt_error";
635 case TLS1_AD_EXPORT_RESTRICTION:
636 str_details2 = " export_restriction";
638 case TLS1_AD_PROTOCOL_VERSION:
639 str_details2 = " protocol_version";
641 case TLS1_AD_INSUFFICIENT_SECURITY:
642 str_details2 = " insufficient_security";
644 case TLS1_AD_INTERNAL_ERROR:
645 str_details2 = " internal_error";
647 case TLS1_AD_USER_CANCELLED:
648 str_details2 = " user_canceled";
650 case TLS1_AD_NO_RENEGOTIATION:
651 str_details2 = " no_renegotiation";
657 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
658 str_details1 = "???";
660 if (tls_session->info.record_len > 0)
661 switch (tls_session->info.handshake_type)
663 case SSL3_MT_HELLO_REQUEST:
664 str_details1 = ", HelloRequest";
666 case SSL3_MT_CLIENT_HELLO:
667 str_details1 = ", ClientHello";
669 case SSL3_MT_SERVER_HELLO:
670 str_details1 = ", ServerHello";
672 case SSL3_MT_CERTIFICATE:
673 str_details1 = ", Certificate";
675 case SSL3_MT_SERVER_KEY_EXCHANGE:
676 str_details1 = ", ServerKeyExchange";
678 case SSL3_MT_CERTIFICATE_REQUEST:
679 str_details1 = ", CertificateRequest";
681 case SSL3_MT_SERVER_DONE:
682 str_details1 = ", ServerHelloDone";
684 case SSL3_MT_CERTIFICATE_VERIFY:
685 str_details1 = ", CertificateVerify";
687 case SSL3_MT_CLIENT_KEY_EXCHANGE:
688 str_details1 = ", ClientKeyExchange";
690 case SSL3_MT_FINISHED:
691 str_details1 = ", Finished";
697 snprintf(tls_session->info.info_description,
698 sizeof(tls_session->info.info_description),
699 "%s %s%s [length %04lx]%s%s\n",
700 str_write_p, str_version, str_content_type,
701 (unsigned long)tls_session->info.record_len,
702 str_details1, str_details2);
704 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
706 RDEBUG2("%s\n", tls_session->info.info_description);
709 static CONF_PARSER cache_config[] = {
710 { "enable", PW_TYPE_BOOLEAN,
711 offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
712 { "lifetime", PW_TYPE_INTEGER,
713 offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
714 { "max_entries", PW_TYPE_INTEGER,
715 offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
716 { "name", PW_TYPE_STRING_PTR,
717 offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
718 { NULL, -1, 0, NULL, NULL } /* end the list */
721 static CONF_PARSER verify_config[] = {
722 { "tmpdir", PW_TYPE_STRING_PTR,
723 offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
724 { "client", PW_TYPE_STRING_PTR,
725 offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
726 { NULL, -1, 0, NULL, NULL } /* end the list */
729 #ifdef HAVE_OPENSSL_OCSP_H
730 static CONF_PARSER ocsp_config[] = {
731 { "enable", PW_TYPE_BOOLEAN,
732 offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
733 { "override_cert_url", PW_TYPE_BOOLEAN,
734 offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
735 { "url", PW_TYPE_STRING_PTR,
736 offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
737 { NULL, -1, 0, NULL, NULL } /* end the list */
741 static CONF_PARSER tls_server_config[] = {
742 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
743 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
744 { "dh_key_exchange", PW_TYPE_BOOLEAN,
745 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
746 { "rsa_key_length", PW_TYPE_INTEGER,
747 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
748 { "dh_key_length", PW_TYPE_INTEGER,
749 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
750 { "verify_depth", PW_TYPE_INTEGER,
751 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
752 { "CA_path", PW_TYPE_FILENAME,
753 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
754 { "pem_file_type", PW_TYPE_BOOLEAN,
755 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
756 { "private_key_file", PW_TYPE_FILENAME,
757 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
758 { "certificate_file", PW_TYPE_FILENAME,
759 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
760 { "CA_file", PW_TYPE_FILENAME,
761 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
762 { "private_key_password", PW_TYPE_STRING_PTR,
763 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
764 { "dh_file", PW_TYPE_STRING_PTR,
765 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
766 { "random_file", PW_TYPE_STRING_PTR,
767 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
768 { "fragment_size", PW_TYPE_INTEGER,
769 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
770 { "include_length", PW_TYPE_BOOLEAN,
771 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
772 { "check_crl", PW_TYPE_BOOLEAN,
773 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
774 { "allow_expired_crl", PW_TYPE_BOOLEAN,
775 offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
776 { "check_cert_cn", PW_TYPE_STRING_PTR,
777 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
778 { "cipher_list", PW_TYPE_STRING_PTR,
779 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
780 { "check_cert_issuer", PW_TYPE_STRING_PTR,
781 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
782 { "make_cert_command", PW_TYPE_STRING_PTR,
783 offsetof(fr_tls_server_conf_t, make_cert_command), NULL, NULL},
784 { "require_client_cert", PW_TYPE_BOOLEAN,
785 offsetof(fr_tls_server_conf_t, require_client_cert), NULL, NULL },
787 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
788 #ifndef OPENSSL_NO_ECDH
789 { "ecdh_curve", PW_TYPE_STRING_PTR,
790 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
794 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
796 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
798 #ifdef HAVE_OPENSSL_OCSP_H
799 { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
802 { NULL, -1, 0, NULL, NULL } /* end the list */
806 static CONF_PARSER tls_client_config[] = {
807 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
808 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
809 { "dh_key_exchange", PW_TYPE_BOOLEAN,
810 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
811 { "rsa_key_length", PW_TYPE_INTEGER,
812 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
813 { "dh_key_length", PW_TYPE_INTEGER,
814 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
815 { "verify_depth", PW_TYPE_INTEGER,
816 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
817 { "CA_path", PW_TYPE_FILENAME,
818 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
819 { "pem_file_type", PW_TYPE_BOOLEAN,
820 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
821 { "private_key_file", PW_TYPE_FILENAME,
822 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
823 { "certificate_file", PW_TYPE_FILENAME,
824 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
825 { "CA_file", PW_TYPE_FILENAME,
826 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
827 { "private_key_password", PW_TYPE_STRING_PTR,
828 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
829 { "dh_file", PW_TYPE_STRING_PTR,
830 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
831 { "random_file", PW_TYPE_STRING_PTR,
832 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
833 { "fragment_size", PW_TYPE_INTEGER,
834 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
835 { "include_length", PW_TYPE_BOOLEAN,
836 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
837 { "check_crl", PW_TYPE_BOOLEAN,
838 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
839 { "check_cert_cn", PW_TYPE_STRING_PTR,
840 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
841 { "cipher_list", PW_TYPE_STRING_PTR,
842 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
843 { "check_cert_issuer", PW_TYPE_STRING_PTR,
844 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
846 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
847 #ifndef OPENSSL_NO_ECDH
848 { "ecdh_curve", PW_TYPE_STRING_PTR,
849 offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
853 { NULL, -1, 0, NULL, NULL } /* end the list */
858 * TODO: Check for the type of key exchange * like conf->dh_key
860 static int load_dh_params(SSL_CTX *ctx, char *file)
865 if ((bio = BIO_new_file(file, "r")) == NULL) {
866 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
870 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
873 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters. DH cipher suites may not work!");
874 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
878 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
879 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
890 * Generate ephemeral RSA keys.
892 static int generate_eph_rsa_key(SSL_CTX *ctx)
896 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
898 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
899 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
909 * Print debugging messages, and free data.
911 * FIXME: Write sessions to some long-term storage, so that
912 * session resumption can still occur after the server
915 #define MAX_SESSION_SIZE (256)
917 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
923 char buffer[2 * MAX_SESSION_SIZE + 1];
925 size = sess->session_id_length;
926 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
928 fr_bin2hex(sess->session_id, buffer, size);
930 DEBUG2(" SSL: Removing session %s from the cache", buffer);
932 vp = SSL_SESSION_get_ex_data(sess, FR_TLS_EX_INDEX_VPS);
933 if (vp) pairfree(&vp);
935 for (i = 0; i <= FR_TLS_EX_INDEX_STORE; i++) {
936 SSL_SESSION_get_ex_data(sess, i, NULL);
939 SSL_SESSION_free(sess);
944 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
947 char buffer[2 * MAX_SESSION_SIZE + 1];
949 size = sess->session_id_length;
950 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
952 fr_bin2hex(sess->session_id, buffer, size);
954 DEBUG2(" SSL: adding session %s to cache", buffer);
959 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
960 unsigned char *data, int len,
964 char buffer[2 * MAX_SESSION_SIZE + 1];
967 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
969 fr_bin2hex(data, buffer, size);
971 DEBUG2(" SSL: Client requested nonexistent cached session %s",
977 #ifdef HAVE_OPENSSL_OCSP_H
979 * This function extracts the OCSP Responder URL
980 * from an existing x509 certificate.
982 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
983 char **ppath, int *pssl)
987 AUTHORITY_INFO_ACCESS *aia;
988 ACCESS_DESCRIPTION *ad;
990 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
992 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
993 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
994 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
995 if (ad->location->type == GEN_URI) {
996 if(OCSP_parse_url(ad->location->d.ia5->data,
997 phost, pport, ppath, pssl))
1006 * This function sends a OCSP request to a defined OCSP responder
1007 * and checks the OCSP response for correctness.
1010 /* Maximum leeway in validity period: default 5 minutes */
1011 #define MAX_VALIDITY_PERIOD (5 * 60)
1013 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1014 fr_tls_server_conf_t *conf)
1016 OCSP_CERTID *certid;
1018 OCSP_RESPONSE *resp;
1019 OCSP_BASICRESP *bresp = NULL;
1024 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1025 BIO *cbio, *bio_out;
1028 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1032 * Create OCSP Request
1034 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1035 req = OCSP_REQUEST_new();
1036 OCSP_request_add0_id(req, certid);
1037 OCSP_request_add1_nonce(req, NULL, 8);
1040 * Send OCSP Request and get OCSP Response
1043 /* Get OCSP responder URL */
1044 if(conf->ocsp_override_url) {
1045 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
1048 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1051 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1053 /* Setup BIO socket to OCSP responder */
1054 cbio = BIO_new_connect(host);
1056 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1058 BIO_set_conn_port(cbio, port);
1059 BIO_do_connect(cbio);
1061 /* Send OCSP request and wait for response */
1062 resp = OCSP_sendreq_bio(cbio, path, req);
1064 radlog(L_ERR, "Error: Couldn't get OCSP response");
1068 /* Verify OCSP response status */
1069 status = OCSP_response_status(resp);
1070 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1071 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1072 radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status));
1075 bresp = OCSP_response_get1_basic(resp);
1076 if(OCSP_check_nonce(req, bresp)!=1) {
1077 radlog(L_ERR, "Error: OCSP response has wrong nonce value");
1080 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1081 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
1085 /* Verify OCSP cert status */
1086 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1087 &rev, &thisupd, &nextupd)) {
1088 radlog(L_ERR, "ERROR: No Status found.\n");
1092 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1093 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1094 ERR_print_errors(bio_out);
1097 BIO_puts(bio_out, "\tThis Update: ");
1098 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1099 BIO_puts(bio_out, "\n");
1100 BIO_puts(bio_out, "\tNext Update: ");
1101 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1102 BIO_puts(bio_out, "\n");
1105 case V_OCSP_CERTSTATUS_GOOD:
1106 DEBUG2("[oscp] --> Cert status: good");
1111 /* REVOKED / UNKNOWN */
1112 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1114 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1115 BIO_puts(bio_out, "\tRevocation Time: ");
1116 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1117 BIO_puts(bio_out, "\n");
1122 /* Free OCSP Stuff */
1123 OCSP_REQUEST_free(req);
1124 OCSP_RESPONSE_free(resp);
1129 OCSP_BASICRESP_free(bresp);
1132 DEBUG2("[ocsp] --> Certificate is valid!");
1134 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1139 #endif /* HAVE_OPENSSL_OCSP_H */
1142 * For creating certificate attributes.
1144 static const char *cert_attr_names[5][2] = {
1145 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1146 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1147 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1148 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1149 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" }
1152 #define FR_TLS_SERIAL (0)
1153 #define FR_TLS_EXPIRATION (1)
1154 #define FR_TLS_SUBJECT (2)
1155 #define FR_TLS_ISSUER (3)
1156 #define FR_TLS_CN (4)
1159 * Before trusting a certificate, you must make sure that the
1160 * certificate is 'valid'. There are several steps that your
1161 * application can take in determining if a certificate is
1162 * valid. Commonly used steps are:
1164 * 1.Verifying the certificate's signature, and verifying that
1165 * the certificate has been issued by a trusted Certificate
1168 * 2.Verifying that the certificate is valid for the present date
1169 * (i.e. it is being presented within its validity dates).
1171 * 3.Verifying that the certificate has not been revoked by its
1172 * issuing Certificate Authority, by checking with respect to a
1173 * Certificate Revocation List (CRL).
1175 * 4.Verifying that the credentials presented by the certificate
1176 * fulfill additional requirements specific to the application,
1177 * such as with respect to access control lists or with respect
1178 * to OCSP (Online Certificate Status Processing).
1180 * NOTE: This callback will be called multiple times based on the
1181 * depth of the root certificate chain
1183 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1185 char subject[1024]; /* Used for the subject name */
1186 char issuer[1024]; /* Used for the issuer name */
1187 char common_name[1024];
1192 int err, depth, lookup;
1193 fr_tls_server_conf_t *conf;
1196 ASN1_INTEGER *sn = NULL;
1197 ASN1_TIME *asn_time = NULL;
1200 #ifdef HAVE_OPENSSL_OCSP_H
1201 X509_STORE *ocsp_store = NULL;
1205 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1206 err = X509_STORE_CTX_get_error(ctx);
1207 depth = X509_STORE_CTX_get_error_depth(ctx);
1212 * Log client/issuing cert. If there's an error, log
1215 if ((lookup > 1) && !my_ok) lookup = 1;
1218 * Retrieve the pointer to the SSL of the connection currently treated
1219 * and the application specific data stored into the SSL object.
1221 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1222 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1223 if (!conf) return 1;
1225 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1227 if (!request) return 1; /* FIXME: outbound TLS */
1229 rad_assert(request != NULL);
1230 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1231 rad_assert(certs != NULL);
1232 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1233 #ifdef HAVE_OPENSSL_OCSP_H
1234 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1239 * Get the Serial Number
1242 sn = X509_get_serialNumber(client_cert);
1245 * For this next bit, we create the attributes *only* if
1246 * we're at the client or issuing certificate, AND we
1247 * have a user identity. i.e. we don't create the
1248 * attributes for RadSec connections.
1251 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1255 for (i = 0; i < sn->length; i++) {
1256 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1260 pairmake(cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET));
1265 * Get the Expiration Date
1268 asn_time = X509_get_notAfter(client_cert);
1269 if (identity && (lookup <= 1) && asn_time &&
1270 (asn_time->length < MAX_STRING_LEN)) {
1271 memcpy(buf, (char*) asn_time->data, asn_time->length);
1272 buf[asn_time->length] = '\0';
1274 pairmake(cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET));
1278 * Get the Subject & Issuer
1280 subject[0] = issuer[0] = '\0';
1281 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1283 subject[sizeof(subject) - 1] = '\0';
1284 if (identity && (lookup <= 1) && subject[0] &&
1285 (strlen(subject) < MAX_STRING_LEN)) {
1287 pairmake(cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET));
1290 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1292 issuer[sizeof(issuer) - 1] = '\0';
1293 if (identity && (lookup <= 1) && issuer[0] &&
1294 (strlen(issuer) < MAX_STRING_LEN)) {
1296 pairmake(cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET));
1300 * Get the Common Name
1302 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1303 NID_commonName, common_name, sizeof(common_name));
1304 common_name[sizeof(common_name) - 1] = '\0';
1305 if (identity && (lookup <= 1) && common_name[0] &&
1306 (strlen(common_name) < MAX_STRING_LEN)) {
1308 pairmake(cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET));
1312 * If the CRL has expired, that might still be OK.
1315 (conf->allow_expired_crl) &&
1316 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1318 X509_STORE_CTX_set_error( ctx, 0 );
1322 const char *p = X509_verify_cert_error_string(err);
1323 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
1324 radius_pairmake(request, &request->packet->vps,
1325 "Module-Failure-Message", p, T_OP_SET);
1329 switch (ctx->error) {
1331 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1332 radlog(L_ERR, "issuer= %s\n", issuer);
1334 case X509_V_ERR_CERT_NOT_YET_VALID:
1335 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1336 radlog(L_ERR, "notBefore=");
1338 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1341 case X509_V_ERR_CERT_HAS_EXPIRED:
1342 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1343 radlog(L_ERR, "notAfter=");
1345 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1351 * If we're at the actual client cert, apply additional
1356 * If the conf tells us to, check cert issuer
1357 * against the specified value and fail
1358 * verification if they don't match.
1360 if (conf->check_cert_issuer &&
1361 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1362 radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1367 * If the conf tells us to, check the CN in the
1368 * cert against xlat'ed value, but only if the
1369 * previous checks passed.
1371 if (my_ok && conf->check_cert_cn) {
1372 if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, request, NULL)) {
1373 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
1374 conf->check_cert_cn);
1375 /* if this fails, fail the verification */
1378 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1379 if (strcmp(cn_str, common_name) != 0) {
1380 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1384 } /* check_cert_cn */
1386 #ifdef HAVE_OPENSSL_OCSP_H
1387 if (my_ok && conf->ocsp_enable){
1388 RDEBUG2("--> Starting OCSP Request");
1389 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1390 radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
1392 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1396 while (conf->verify_client_cert_cmd) {
1401 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1402 conf->verify_tmp_dir, progname);
1403 fd = mkstemp(filename);
1405 RDEBUG("Failed creating file in %s: %s",
1406 conf->verify_tmp_dir, strerror(errno));
1410 fp = fdopen(fd, "w");
1412 RDEBUG("Failed opening file %s: %s",
1413 filename, strerror(errno));
1417 if (!PEM_write_X509(fp, client_cert)) {
1419 RDEBUG("Failed writing certificate to file");
1424 if (!radius_pairmake(request, &request->packet->vps,
1425 "TLS-Client-Cert-Filename",
1426 filename, T_OP_SET)) {
1427 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1432 RDEBUG("Verifying client certificate: %s",
1433 conf->verify_client_cert_cmd);
1434 if (radius_exec_program(conf->verify_client_cert_cmd,
1435 request, 1, NULL, 0,
1436 request->packet->vps,
1438 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
1441 RDEBUG("Client certificate CN %s passed external validation", common_name);
1452 if (debug_flag > 0) {
1453 RDEBUG2("chain-depth=%d, ", depth);
1454 RDEBUG2("error=%d", err);
1456 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1457 RDEBUG2("--> BUF-Name = %s", common_name);
1458 RDEBUG2("--> subject = %s", subject);
1459 RDEBUG2("--> issuer = %s", issuer);
1460 RDEBUG2("--> verify return:%d", my_ok);
1466 #ifdef HAVE_OPENSSL_OCSP_H
1468 * Create Global X509 revocation store and use it to verify
1471 * - Load the trusted CAs
1472 * - Load the trusted issuer certificates
1474 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1476 X509_STORE *store = NULL;
1478 store = X509_STORE_new();
1480 /* Load the CAs we trust */
1481 if (conf->ca_file || conf->ca_path)
1482 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1483 radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1484 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1488 #ifdef X509_V_FLAG_CRL_CHECK
1489 if (conf->check_crl)
1490 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1494 #endif /* HAVE_OPENSSL_OCSP_H */
1496 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1497 #ifndef OPENSSL_NO_ECDH
1498 static int set_ecdh_curve(SSL_CTX *ctx, const char *ecdh_curve)
1503 if (!ecdh_curve || !*ecdh_curve) return 0;
1505 nid = OBJ_sn2nid(ecdh_curve);
1507 radlog(L_ERR, "Unknown ecdh_curve \"%s\"", ecdh_curve);
1511 ecdh = EC_KEY_new_by_curve_name(nid);
1513 radlog(L_ERR, "Unable to create new curve \"%s\"", ecdh_curve);
1517 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1519 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1529 * Create Global context SSL and use it in every new session
1531 * - Load the trusted CAs
1532 * - Load the Private key & the certificate
1533 * - Set the Context options & Verify options
1535 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf)
1537 const SSL_METHOD *meth;
1539 X509_STORE *certstore;
1540 int verify_mode = SSL_VERIFY_NONE;
1541 int ctx_options = 0;
1545 * Add all the default ciphers and message digests
1546 * Create our context.
1549 SSL_load_error_strings();
1552 * SHA256 is in all versions of OpenSSL, but isn't
1553 * initialized by default. It's needed for WiMAX
1556 #ifdef HAVE_OPENSSL_EVP_SHA256
1557 EVP_add_digest(EVP_sha256());
1560 meth = TLSv1_method();
1561 ctx = SSL_CTX_new(meth);
1564 * Identify the type of certificates that needs to be loaded
1566 if (conf->file_type) {
1567 type = SSL_FILETYPE_PEM;
1569 type = SSL_FILETYPE_ASN1;
1573 * Set the password to load private key
1575 if (conf->private_key_password) {
1578 * We don't want to put the private key password in eap.conf, so check
1579 * for our special string which indicates we should get the password
1582 const char* special_string = "Apple:UseCertAdmin";
1583 if (strncmp(conf->private_key_password,
1585 strlen(special_string)) == 0)
1588 const long max_password_len = 128;
1589 snprintf(cmd, sizeof(cmd) - 1,
1590 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
1591 conf->private_key_file);
1593 DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
1595 FILE* cmd_pipe = popen(cmd, "r");
1597 radlog(L_ERR, "rlm_eap: %s command failed. Unable to get private_key_password", cmd);
1598 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1602 free(conf->private_key_password);
1603 conf->private_key_password = malloc(max_password_len * sizeof(char));
1604 if (!conf->private_key_password) {
1605 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
1606 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1611 fgets(conf->private_key_password, max_password_len, cmd_pipe);
1614 /* Get rid of newline at end of password. */
1615 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
1616 DEBUG2("rlm_eap: Password from command = \"%s\"", conf->private_key_password);
1619 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
1620 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
1624 * Load our keys and certificates
1626 * If certificates are of type PEM then we can make use
1627 * of cert chain authentication using openssl api call
1628 * SSL_CTX_use_certificate_chain_file. Please see how
1629 * the cert chain needs to be given in PEM from
1632 if (!conf->certificate_file) goto load_ca;
1634 if (type == SSL_FILETYPE_PEM) {
1635 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
1636 radlog(L_ERR, "Error reading certificate file %s:%s",
1637 conf->certificate_file,
1638 ERR_error_string(ERR_get_error(), NULL));
1642 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
1643 radlog(L_ERR, "Error reading certificate file %s:%s",
1644 conf->certificate_file,
1645 ERR_error_string(ERR_get_error(), NULL));
1649 /* Load the CAs we trust */
1651 if (conf->ca_file || conf->ca_path) {
1652 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
1653 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1654 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1658 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
1660 if (conf->private_key_file) {
1661 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
1662 radlog(L_ERR, "Failed reading private key file %s:%s",
1663 conf->private_key_file,
1664 ERR_error_string(ERR_get_error(), NULL));
1669 * Check if the loaded private key is the right one
1671 if (!SSL_CTX_check_private_key(ctx)) {
1672 radlog(L_ERR, "Private key does not match the certificate public key");
1680 ctx_options |= SSL_OP_NO_SSLv2;
1681 ctx_options |= SSL_OP_NO_SSLv3;
1682 #ifdef SSL_OP_NO_TICKET
1683 ctx_options |= SSL_OP_NO_TICKET ;
1687 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
1688 * small subgroup attacks and forward secrecy. Always
1691 * SSL_OP_SINGLE_DH_USE has an impact on the computer
1692 * time needed during negotiation, but it is not very
1695 ctx_options |= SSL_OP_SINGLE_DH_USE;
1698 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
1699 * in Windows Vista client.
1700 * http://www.openssl.org/~bodo/tls-cbc.txt
1701 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
1703 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1705 SSL_CTX_set_options(ctx, ctx_options);
1708 * TODO: Set the RSA & DH
1709 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
1710 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
1714 * set the message callback to identify the type of
1715 * message. For every new session, there can be a
1716 * different callback argument.
1718 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
1722 * Set eliptical curve crypto configuration.
1724 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1725 #ifndef OPENSSL_NO_ECDH
1726 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
1732 /* Set Info callback */
1733 SSL_CTX_set_info_callback(ctx, cbtls_info);
1736 * Callbacks, etc. for session resumption.
1738 if (conf->session_cache_enable) {
1739 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
1740 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
1741 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
1743 SSL_CTX_set_quiet_shutdown(ctx, 1);
1747 * Check the certificates for revocation.
1749 #ifdef X509_V_FLAG_CRL_CHECK
1750 if (conf->check_crl) {
1751 certstore = SSL_CTX_get_cert_store(ctx);
1752 if (certstore == NULL) {
1753 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1754 radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
1757 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
1763 * Always verify the peer certificate
1765 verify_mode |= SSL_VERIFY_PEER;
1766 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1767 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1768 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
1770 if (conf->verify_depth) {
1771 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
1774 /* Load randomness */
1775 if (!(RAND_load_file(conf->random_file, 1024*1024))) {
1776 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1777 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
1782 * Set the cipher list if we were told to
1784 if (conf->cipher_list) {
1785 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
1786 radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
1792 * Setup session caching
1794 if (conf->session_cache_enable) {
1796 * Create a unique context Id per EAP-TLS configuration.
1798 if (conf->session_id_name) {
1799 snprintf(conf->session_context_id,
1800 sizeof(conf->session_context_id),
1801 "FreeRADIUS EAP-TLS %s",
1802 conf->session_id_name);
1804 snprintf(conf->session_context_id,
1805 sizeof(conf->session_context_id),
1806 "FreeRADIUS EAP-TLS %p", conf);
1810 * Cache it, and DON'T auto-clear it.
1812 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
1814 SSL_CTX_set_session_id_context(ctx,
1815 (unsigned char *) conf->session_context_id,
1816 (unsigned int) strlen(conf->session_context_id));
1819 * Our timeout is in hours, this is in seconds.
1821 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
1824 * Set the maximum number of entries in the
1827 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
1830 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1837 void tls_server_conf_free(fr_tls_server_conf_t *conf)
1841 if (conf->cs) cf_section_parse_free(conf->cs, conf);
1843 if (conf->ctx) SSL_CTX_free(conf->ctx);
1845 #ifdef HAVE_OPENSSL_OCSP_H
1846 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
1847 conf->ocsp_store = NULL;
1850 memset(conf, 0, sizeof(*conf));
1855 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
1857 fr_tls_server_conf_t *conf;
1859 conf = malloc(sizeof(*conf));
1861 radlog(L_ERR, "Out of memory");
1864 memset(conf, 0, sizeof(*conf));
1866 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
1868 tls_server_conf_free(conf);
1873 * Save people from their own stupidity.
1875 if (conf->fragment_size < 100) conf->fragment_size = 100;
1878 * This magic makes the administrators life HUGELY easier
1879 * on initial deployments.
1881 * If the server starts up in debugging mode, AND the
1882 * bootstrap command is configured, AND it exists, AND
1883 * there is no server certificate
1885 if (conf->make_cert_command && (debug_flag >= 2)) {
1888 if ((stat(conf->make_cert_command, &buf) == 0) &&
1889 (stat(conf->certificate_file, &buf) < 0) &&
1890 (errno == ENOENT) &&
1891 (radius_exec_program(conf->make_cert_command, NULL, 1,
1892 NULL, 0, NULL, NULL, 0) != 0)) {
1897 if (!conf->private_key_file) {
1898 radlog(L_ERR, "TLS Server requires a private key file");
1902 if (!conf->certificate_file) {
1903 radlog(L_ERR, "TLS Server requires a certificate file");
1910 conf->ctx = init_tls_ctx(conf);
1911 if (conf->ctx == NULL) {
1915 #ifdef HAVE_OPENSSL_OCSP_H
1917 * Initialize OCSP Revocation Store
1919 if (conf->ocsp_enable) {
1920 conf->ocsp_store = init_revocation_store(conf);
1921 if (conf->ocsp_store == NULL) goto error;
1923 #endif /*HAVE_OPENSSL_OCSP_H*/
1925 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
1929 if (generate_eph_rsa_key(conf->ctx) < 0) {
1933 if (conf->verify_tmp_dir) {
1934 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
1935 radlog(L_ERR, "Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
1940 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
1941 radlog(L_ERR, "You MUST set the verify directory in order to use verify_client_cmd");
1948 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
1950 fr_tls_server_conf_t *conf;
1952 conf = malloc(sizeof(*conf));
1954 radlog(L_ERR, "Out of memory");
1957 memset(conf, 0, sizeof(*conf));
1959 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
1961 tls_server_conf_free(conf);
1966 * Save people from their own stupidity.
1968 if (conf->fragment_size < 100) conf->fragment_size = 100;
1973 conf->ctx = init_tls_ctx(conf);
1974 if (conf->ctx == NULL) {
1978 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
1982 if (generate_eph_rsa_key(conf->ctx) < 0) {
1989 int tls_success(tls_session_t *ssn, REQUEST *request)
1991 VALUE_PAIR *vp, *vps = NULL;
1992 fr_tls_server_conf_t *conf;
1994 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
1995 rad_assert(conf != NULL);
1998 * If there's no session resumption, delete the entry
1999 * from the cache. This means either it's disabled
2000 * globally for this SSL context, OR we were told to
2001 * disable it for this user.
2003 * This also means you can't turn it on just for one
2006 if ((!ssn->allow_session_resumption) ||
2007 (((vp = pairfind(request->config_items, 1127, 0)) != NULL) &&
2008 (vp->vp_integer == 0))) {
2009 SSL_CTX_remove_session(ssn->ctx,
2011 ssn->allow_session_resumption = 0;
2014 * If we're in a resumed session and it's
2017 if (SSL_session_reused(ssn->ssl)) {
2018 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed.");
2023 * Else resumption IS allowed, so we store the
2024 * user data in the cache.
2026 } else if (!SSL_session_reused(ssn->ssl)) {
2027 RDEBUG2("Saving response in the cache");
2029 vp = paircopy2(request->reply->vps, PW_USER_NAME, 0);
2030 if (vp) pairadd(&vps, vp);
2032 vp = paircopy2(request->packet->vps, PW_STRIPPED_USER_NAME, 0);
2033 if (vp) pairadd(&vps, vp);
2035 vp = paircopy2(request->reply->vps, PW_CACHED_SESSION_POLICY, 0);
2036 if (vp) pairadd(&vps, vp);
2039 SSL_SESSION_set_ex_data(ssn->ssl->session,
2040 FR_TLS_EX_INDEX_VPS, vps);
2042 RDEBUG2("WARNING: No information to cache: session caching will be disabled for this session.");
2043 SSL_CTX_remove_session(ssn->ctx,
2048 * Else the session WAS allowed. Copy the cached
2053 vp = SSL_SESSION_get_ex_data(ssn->ssl->session,
2054 FR_TLS_EX_INDEX_VPS);
2056 RDEBUG("WARNING: No information in cached session!");
2060 RDEBUG("Adding cached attributes to the reply:");
2061 debug_pair_list(vp);
2062 pairadd(&request->reply->vps, paircopy(vp));
2065 * Mark the request as resumed.
2067 vp = pairmake("EAP-Session-Resumed", "1", T_OP_SET);
2068 if (vp) pairadd(&request->packet->vps, vp);
2076 void tls_fail(tls_session_t *ssn)
2079 * Force the session to NOT be cached.
2081 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2084 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2091 * Decrypt the complete record.
2093 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2094 ssn->dirty_in.used);
2095 if (err != (int) ssn->dirty_in.used) {
2096 record_init(&ssn->dirty_in);
2097 RDEBUG("Failed writing %d to SSL BIO: %d",
2098 ssn->dirty_in.used, err);
2103 * Clear the dirty buffer now that we are done with it
2104 * and init the clean_out buffer to store decrypted data
2106 record_init(&ssn->dirty_in);
2107 record_init(&ssn->clean_out);
2110 * Read (and decrypt) the tunneled data from the
2111 * SSL session, and put it into the decrypted
2114 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2115 sizeof(ssn->clean_out.data));
2120 RDEBUG("SSL_read Error");
2122 code = SSL_get_error(ssn->ssl, err);
2124 case SSL_ERROR_WANT_READ:
2125 return FR_TLS_MORE_FRAGMENTS;
2126 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2129 case SSL_ERROR_WANT_WRITE:
2130 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2134 DEBUG("Error in fragmentation logic: ?");
2137 * FIXME: Call int_ssl_check?
2145 RDEBUG("WARNING: No data inside of the tunnel.");
2149 * Passed all checks, successfully decrypted data
2151 ssn->clean_out.used = err;
2158 * Acknowledge received is for one of the following messages sent earlier
2159 * 1. Handshake completed Message, so now send, EAP-Success
2160 * 2. Alert Message, now send, EAP-Failure
2161 * 3. Fragment Message, now send, next Fragment
2163 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2165 RDEBUG2("Received TLS ACK");
2168 radlog_request(L_ERR, 0, request, "FAIL: Unexpected ACK received. Could not obtain session information.");
2169 return FR_TLS_INVALID;
2171 if (ssn->info.initialized == 0) {
2172 RDEBUG("No SSL info available. Waiting for more SSL data.");
2173 return FR_TLS_REQUEST;
2175 if ((ssn->info.content_type == handshake) &&
2176 (ssn->info.origin == 0)) {
2177 radlog_request(L_ERR, 0, request, "FAIL: ACK without earlier message.");
2178 return FR_TLS_INVALID;
2181 switch (ssn->info.content_type) {
2183 RDEBUG2("ACK alert");
2187 if ((ssn->info.handshake_type == finished) &&
2188 (ssn->dirty_out.used == 0)) {
2189 RDEBUG2("ACK handshake is finished");
2192 * From now on all the content is
2193 * application data set it here as nobody else
2196 ssn->info.content_type = application_data;
2197 return FR_TLS_SUCCESS;
2198 } /* else more data to send */
2200 RDEBUG2("ACK handshake fragment handler");
2201 /* Fragmentation handler, send next fragment */
2202 return FR_TLS_REQUEST;
2204 case application_data:
2205 RDEBUG2("ACK handshake fragment handler in application data");
2206 return FR_TLS_REQUEST;
2209 * For the rest of the conditions, switch over
2210 * to the default section below.
2213 RDEBUG2("ACK default");
2214 radlog_request(L_ERR, 0, request, "Invalid ACK received: %d",
2215 ssn->info.content_type);
2216 return FR_TLS_INVALID;
2220 static void dump_hex(const char *msg, const uint8_t *data, size_t data_len)
2224 if (debug_flag < 3) return;
2226 printf("%s %d\n", msg, (int) data_len);
2227 if (data_len > 256) data_len = 256;
2229 for (i = 0; i < data_len; i++) {
2230 if ((i & 0x0f) == 0x00) printf ("%02x: ", (unsigned int) i);
2231 printf("%02x ", data[i]);
2232 if ((i & 0x0f) == 0x0f) printf ("\n");
2238 static void tls_socket_close(rad_listen_t *listener)
2240 listen_socket_t *sock = listener->data;
2242 listener->status = RAD_LISTEN_STATUS_REMOVE_FD;
2243 listener->tls = NULL; /* parent owns this! */
2247 * Decrement the number of connections.
2249 if (sock->parent->num_connections > 0) {
2250 sock->parent->num_connections--;
2252 if (sock->client->num_connections > 0) {
2253 sock->client->num_connections--;
2258 * Tell the event handler that an FD has disappeared.
2260 DEBUG("Client has closed connection");
2261 event_new_fd(listener);
2264 * Do NOT free the listener here. It's in use by
2265 * a request, and will need to hang around until
2266 * all of the requests are done.
2268 * It is instead free'd in remove_from_request_hash()
2272 static int tls_socket_write(rad_listen_t *listener, REQUEST *request)
2276 listen_socket_t *sock = listener->data;
2278 p = sock->ssn->dirty_out.data;
2280 while (p < (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used)) {
2281 RDEBUG3("Writing to socket %d", request->packet->sockfd);
2282 rcode = write(request->packet->sockfd, p,
2283 (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used) - p);
2285 RDEBUG("Error writing to TLS socket: %s", strerror(errno));
2287 tls_socket_close(listener);
2293 sock->ssn->dirty_out.used = 0;
2299 static int tls_socket_recv(rad_listen_t *listener)
2301 int doing_init = FALSE;
2303 RADIUS_PACKET *packet;
2305 listen_socket_t *sock = listener->data;
2306 fr_tls_status_t status;
2307 RADCLIENT *client = sock->client;
2309 if (!sock->packet) {
2310 sock->packet = rad_alloc(0);
2311 if (!sock->packet) return 0;
2313 sock->packet->sockfd = listener->fd;
2314 sock->packet->src_ipaddr = sock->other_ipaddr;
2315 sock->packet->src_port = sock->other_port;
2316 sock->packet->dst_ipaddr = sock->my_ipaddr;
2317 sock->packet->dst_port = sock->my_port;
2319 if (sock->request) sock->request->packet = sock->packet;
2323 * Allocate a REQUEST for debugging.
2325 if (!sock->request) {
2326 sock->request = request = request_alloc();
2327 if (!sock->request) {
2328 radlog(L_ERR, "Out of memory");
2332 rad_assert(request->packet == NULL);
2333 rad_assert(sock->packet != NULL);
2334 request->packet = sock->packet;
2336 request->component = "<core>";
2337 request->component = "<tls-connect>";
2340 * Not sure if we should do this on every packet...
2342 request->reply = rad_alloc(0);
2343 if (!request->reply) return 0;
2345 request->options = RAD_REQUEST_OPTION_DEBUG2;
2347 rad_assert(sock->ssn == NULL);
2349 sock->ssn = tls_new_session(listener->tls, sock->request,
2350 listener->tls->require_client_cert);
2352 request_free(&sock->request);
2353 sock->packet = NULL;
2357 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
2358 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_CERTS, (void *)&request->packet->vps);
2363 rad_assert(sock->request != NULL);
2364 rad_assert(sock->request->packet != NULL);
2365 rad_assert(sock->packet != NULL);
2366 rad_assert(sock->ssn != NULL);
2368 request = sock->request;
2370 RDEBUG3("Reading from socket %d", request->packet->sockfd);
2371 PTHREAD_MUTEX_LOCK(&sock->mutex);
2372 rcode = read(request->packet->sockfd,
2373 sock->ssn->dirty_in.data,
2374 sizeof(sock->ssn->dirty_in.data));
2375 if ((rcode < 0) && (errno == ECONNRESET)) {
2377 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2378 tls_socket_close(listener);
2383 RDEBUG("Error reading TLS socket: %s", strerror(errno));
2388 * Normal socket close.
2390 if (rcode == 0) goto do_close;
2392 sock->ssn->dirty_in.used = rcode;
2393 memset(sock->ssn->dirty_in.data + sock->ssn->dirty_in.used,
2396 dump_hex("READ FROM SSL", sock->ssn->dirty_in.data, sock->ssn->dirty_in.used);
2399 * Catch attempts to use non-SSL.
2401 if (doing_init && (sock->ssn->dirty_in.data[0] != handshake)) {
2402 RDEBUG("Non-TLS data sent to TLS socket: closing");
2407 * Skip ahead to reading application data.
2409 if (SSL_is_init_finished(sock->ssn->ssl)) goto app;
2411 if (!tls_handshake_recv(request, sock->ssn)) {
2412 RDEBUG("FAILED in TLS handshake receive");
2416 if (sock->ssn->dirty_out.used > 0) {
2417 tls_socket_write(listener, request);
2418 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2424 * FIXME: Run the packet through a virtual server in
2425 * order to see if we like the certificate presented by
2429 status = tls_application_data(sock->ssn, request);
2430 RDEBUG("Application data status %d", status);
2432 if (status == FR_TLS_MORE_FRAGMENTS) {
2433 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2437 if (sock->ssn->clean_out.used == 0) {
2438 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2442 dump_hex("TUNNELED DATA", sock->ssn->clean_out.data, sock->ssn->clean_out.used);
2445 * If the packet is a complete RADIUS packet, return it to
2446 * the caller. Otherwise...
2448 if ((sock->ssn->clean_out.used < 20) ||
2449 (((sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]) != (int) sock->ssn->clean_out.used)) {
2450 RDEBUG("Received bad packet: Length %d contents %d",
2451 sock->ssn->clean_out.used,
2452 (sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]);
2456 packet = sock->packet;
2457 packet->data = rad_malloc(sock->ssn->clean_out.used);
2458 packet->data_len = sock->ssn->clean_out.used;
2459 record_minus(&sock->ssn->clean_out, packet->data, packet->data_len);
2461 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2463 if (!rad_packet_ok(packet, 0)) {
2464 RDEBUG("Received bad packet: %s", fr_strerror());
2465 tls_socket_close(listener);
2466 return 0; /* do_close unlocks the mutex */
2470 * Copied from src/lib/radius.c, rad_recv();
2472 if (fr_debug_flag) {
2473 char host_ipaddr[128];
2475 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2476 RDEBUG("tls_recv: %s packet from host %s port %d, id=%d, length=%d",
2477 fr_packet_codes[packet->code],
2478 inet_ntop(packet->src_ipaddr.af,
2479 &packet->src_ipaddr.ipaddr,
2480 host_ipaddr, sizeof(host_ipaddr)),
2482 packet->id, (int) packet->data_len);
2484 RDEBUG("tls_recv: Packet from host %s port %d code=%d, id=%d, length=%d",
2485 inet_ntop(packet->src_ipaddr.af,
2486 &packet->src_ipaddr.ipaddr,
2487 host_ipaddr, sizeof(host_ipaddr)),
2490 packet->id, (int) packet->data_len);
2494 FR_STATS_INC(auth, total_requests);
2500 int dual_tls_recv(rad_listen_t *listener)
2502 RADIUS_PACKET *packet;
2504 RAD_REQUEST_FUNP fun = NULL;
2505 listen_socket_t *sock = listener->data;
2506 RADCLIENT *client = sock->client;
2508 if (!tls_socket_recv(listener)) {
2512 rad_assert(sock->request != NULL);
2513 rad_assert(sock->request->packet != NULL);
2514 rad_assert(sock->packet != NULL);
2515 rad_assert(sock->ssn != NULL);
2517 request = sock->request;
2518 packet = sock->packet;
2521 * Some sanity checks, based on the packet code.
2523 switch(packet->code) {
2524 case PW_AUTHENTICATION_REQUEST:
2525 if (listener->type != RAD_LISTEN_AUTH) goto bad_packet;
2526 FR_STATS_INC(auth, total_requests);
2527 fun = rad_authenticate;
2530 case PW_ACCOUNTING_REQUEST:
2531 if (listener->type != RAD_LISTEN_ACCT) goto bad_packet;
2532 FR_STATS_INC(acct, total_requests);
2533 fun = rad_accounting;
2536 case PW_STATUS_SERVER:
2537 if (!mainconfig.status_server) {
2538 FR_STATS_INC(auth, total_unknown_types);
2539 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
2540 rad_free(&sock->packet);
2541 request->packet = NULL;
2544 fun = rad_status_server;
2549 FR_STATS_INC(auth, total_unknown_types);
2551 DEBUG("Invalid packet code %d sent from client %s port %d : IGNORED",
2552 packet->code, client->shortname, packet->src_port);
2553 rad_free(&sock->packet);
2554 request->packet = NULL;
2556 } /* switch over packet types */
2558 if (!request_receive(listener, packet, client, fun)) {
2559 FR_STATS_INC(auth, total_packets_dropped);
2560 rad_free(&sock->packet);
2561 request->packet = NULL;
2565 sock->packet = NULL; /* we have no need for more partial reads */
2566 request->packet = NULL;
2573 * Send a response packet
2575 int dual_tls_send(rad_listen_t *listener, REQUEST *request)
2577 listen_socket_t *sock = listener->data;
2579 rad_assert(request->listener == listener);
2580 rad_assert(listener->send == dual_tls_send);
2583 * Accounting reject's are silently dropped.
2585 * We do it here to avoid polluting the rest of the
2586 * code with this knowledge
2588 if (request->reply->code == 0) return 0;
2593 if (rad_encode(request->reply, request->packet,
2594 request->client->secret) < 0) {
2595 RDEBUG("Failed encoding packet: %s", fr_strerror());
2602 if (rad_sign(request->reply, request->packet,
2603 request->client->secret) < 0) {
2604 RDEBUG("Failed signing packet: %s", fr_strerror());
2608 PTHREAD_MUTEX_LOCK(&sock->mutex);
2610 * Write the packet to the SSL buffers.
2612 record_plus(&sock->ssn->clean_in,
2613 request->reply->data, request->reply->data_len);
2616 * Do SSL magic to get encrypted data.
2618 tls_handshake_send(request, sock->ssn);
2621 * And finally write the data to the socket.
2623 if (sock->ssn->dirty_out.used > 0) {
2624 dump_hex("WRITE TO SSL", sock->ssn->dirty_out.data, sock->ssn->dirty_out.used);
2626 tls_socket_write(listener, request);
2628 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2634 int proxy_tls_recv(rad_listen_t *listener)
2638 listen_socket_t *sock = listener->data;
2641 RADIUS_PACKET *packet;
2642 RAD_REQUEST_FUNP fun = NULL;
2644 DEBUG3("Proxy SSL socket has data to read");
2645 PTHREAD_MUTEX_LOCK(&sock->mutex);
2647 rcode = SSL_read(sock->ssn->ssl, data, 4);
2649 int err = SSL_get_error(sock->ssn->ssl, rcode);
2651 case SSL_ERROR_WANT_READ:
2652 case SSL_ERROR_WANT_WRITE:
2655 case SSL_ERROR_ZERO_RETURN:
2656 /* remote end sent close_notify, send one back */
2657 SSL_shutdown(sock->ssn->ssl);
2659 case SSL_ERROR_SYSCALL:
2661 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2662 tls_socket_close(listener);
2666 while ((err = ERR_get_error())) {
2667 DEBUG("proxy recv says %s",
2668 ERR_error_string(err, NULL));
2675 length = (data[2] << 8) | data[3];
2676 DEBUG3("Proxy received header saying we have a packet of %u bytes",
2677 (unsigned int) length);
2679 if (length > sizeof(data)) {
2680 DEBUG("Received packet will be too large! (%u)",
2681 (data[2] << 8) | data[3]);
2685 rcode = SSL_read(sock->ssn->ssl, data + 4, length);
2687 switch (SSL_get_error(sock->ssn->ssl, rcode)) {
2688 case SSL_ERROR_WANT_READ:
2689 case SSL_ERROR_WANT_WRITE:
2693 case SSL_ERROR_ZERO_RETURN:
2694 /* remote end sent close_notify, send one back */
2695 SSL_shutdown(sock->ssn->ssl);
2701 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2703 packet = rad_alloc(0);
2704 packet->sockfd = listener->fd;
2705 packet->src_ipaddr = sock->other_ipaddr;
2706 packet->src_port = sock->other_port;
2707 packet->dst_ipaddr = sock->my_ipaddr;
2708 packet->dst_port = sock->my_port;
2709 packet->code = data[0];
2710 packet->id = data[1];
2711 packet->data_len = length;
2712 packet->data = rad_malloc(packet->data_len);
2713 memcpy(packet->data, data, packet->data_len);
2714 memcpy(packet->vector, packet->data + 4, 16);
2717 * FIXME: Client MIB updates?
2719 switch(packet->code) {
2720 case PW_AUTHENTICATION_ACK:
2721 case PW_ACCESS_CHALLENGE:
2722 case PW_AUTHENTICATION_REJECT:
2723 fun = rad_authenticate;
2726 #ifdef WITH_ACCOUNTING
2727 case PW_ACCOUNTING_RESPONSE:
2728 fun = rad_accounting;
2734 * FIXME: Update MIB for packet types?
2736 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
2737 "from home server %s port %d - ID %d : IGNORED",
2739 ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
2740 packet->src_port, packet->id);
2745 if (!request_proxy_reply(packet)) {
2753 int proxy_tls_send(rad_listen_t *listener, REQUEST *request)
2756 listen_socket_t *sock = listener->data;
2759 * Normal proxying calls us with the data already
2760 * encoded. The "ping home server" code does not. So,
2761 * if there's no packet, encode it here.
2763 if (!request->proxy->data) {
2764 request->proxy_listener->encode(request->proxy_listener,
2768 DEBUG3("Proxy is writing %u bytes to SSL",
2769 (unsigned int) request->proxy->data_len);
2770 PTHREAD_MUTEX_LOCK(&sock->mutex);
2771 while ((rcode = SSL_write(sock->ssn->ssl, request->proxy->data,
2772 request->proxy->data_len)) < 0) {
2774 while ((err = ERR_get_error())) {
2775 DEBUG("proxy SSL_write says %s",
2776 ERR_error_string(err, NULL));
2778 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2779 tls_socket_close(listener);
2782 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2787 #endif /* WITH_TLS */