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 if (ssn->ssl->session) {
434 vp = SSL_SESSION_get_ex_data(ssn->ssl->session,
435 FR_TLS_EX_INDEX_VPS);
436 if (vp) pairfree(&vp);
439 SSL_set_quiet_shutdown(ssn->ssl, 1);
440 SSL_shutdown(ssn->ssl);
446 * WARNING: SSL_free seems to decrement the reference counts already,
447 * so doing this might crash the application.
450 BIO_free(ssn->into_ssl);
452 BIO_free(ssn->from_ssl);
454 record_close(&ssn->clean_in);
455 record_close(&ssn->clean_out);
456 record_close(&ssn->dirty_in);
457 record_close(&ssn->dirty_out);
461 void session_free(void *ssn)
463 tls_session_t *sess = (tls_session_t *)ssn;
468 * Free any opaque TTLS or PEAP data.
470 if ((sess->opaque) && (sess->free_opaque)) {
471 sess->free_opaque(sess->opaque);
480 static void record_init(record_t *rec)
485 static void record_close(record_t *rec)
492 * Copy data to the intermediate buffer, before we send
495 static unsigned int record_plus(record_t *rec, const void *ptr,
498 unsigned int added = MAX_RECORD_SIZE - rec->used;
504 memcpy(rec->data + rec->used, ptr, added);
510 * Take data from the buffer, and give it to the caller.
512 static unsigned int record_minus(record_t *rec, void *ptr,
515 unsigned int taken = rec->used;
522 memcpy(ptr, rec->data, taken);
526 * This is pretty bad...
529 memmove(rec->data, rec->data + taken, rec->used);
533 void tls_session_information(tls_session_t *tls_session)
535 const char *str_write_p, *str_version, *str_content_type = "";
536 const char *str_details1 = "", *str_details2= "";
540 * Don't print this out in the normal course of
543 if (debug_flag == 0) {
547 str_write_p = tls_session->info.origin ? ">>>" : "<<<";
549 switch (tls_session->info.version)
552 str_version = "SSL 2.0";
555 str_version = "SSL 3.0 ";
558 str_version = "TLS 1.0 ";
561 str_version = "Unknown TLS version";
565 if (tls_session->info.version == SSL3_VERSION ||
566 tls_session->info.version == TLS1_VERSION) {
567 switch (tls_session->info.content_type) {
568 case SSL3_RT_CHANGE_CIPHER_SPEC:
569 str_content_type = "ChangeCipherSpec";
572 str_content_type = "Alert";
574 case SSL3_RT_HANDSHAKE:
575 str_content_type = "Handshake";
577 case SSL3_RT_APPLICATION_DATA:
578 str_content_type = "ApplicationData";
581 str_content_type = "UnknownContentType";
585 if (tls_session->info.content_type == SSL3_RT_ALERT) {
586 str_details1 = ", ???";
588 if (tls_session->info.record_len == 2) {
590 switch (tls_session->info.alert_level) {
591 case SSL3_AL_WARNING:
592 str_details1 = ", warning";
595 str_details1 = ", fatal";
599 str_details2 = " ???";
600 switch (tls_session->info.alert_description) {
601 case SSL3_AD_CLOSE_NOTIFY:
602 str_details2 = " close_notify";
604 case SSL3_AD_UNEXPECTED_MESSAGE:
605 str_details2 = " unexpected_message";
607 case SSL3_AD_BAD_RECORD_MAC:
608 str_details2 = " bad_record_mac";
610 case TLS1_AD_DECRYPTION_FAILED:
611 str_details2 = " decryption_failed";
613 case TLS1_AD_RECORD_OVERFLOW:
614 str_details2 = " record_overflow";
616 case SSL3_AD_DECOMPRESSION_FAILURE:
617 str_details2 = " decompression_failure";
619 case SSL3_AD_HANDSHAKE_FAILURE:
620 str_details2 = " handshake_failure";
622 case SSL3_AD_BAD_CERTIFICATE:
623 str_details2 = " bad_certificate";
625 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
626 str_details2 = " unsupported_certificate";
628 case SSL3_AD_CERTIFICATE_REVOKED:
629 str_details2 = " certificate_revoked";
631 case SSL3_AD_CERTIFICATE_EXPIRED:
632 str_details2 = " certificate_expired";
634 case SSL3_AD_CERTIFICATE_UNKNOWN:
635 str_details2 = " certificate_unknown";
637 case SSL3_AD_ILLEGAL_PARAMETER:
638 str_details2 = " illegal_parameter";
640 case TLS1_AD_UNKNOWN_CA:
641 str_details2 = " unknown_ca";
643 case TLS1_AD_ACCESS_DENIED:
644 str_details2 = " access_denied";
646 case TLS1_AD_DECODE_ERROR:
647 str_details2 = " decode_error";
649 case TLS1_AD_DECRYPT_ERROR:
650 str_details2 = " decrypt_error";
652 case TLS1_AD_EXPORT_RESTRICTION:
653 str_details2 = " export_restriction";
655 case TLS1_AD_PROTOCOL_VERSION:
656 str_details2 = " protocol_version";
658 case TLS1_AD_INSUFFICIENT_SECURITY:
659 str_details2 = " insufficient_security";
661 case TLS1_AD_INTERNAL_ERROR:
662 str_details2 = " internal_error";
664 case TLS1_AD_USER_CANCELLED:
665 str_details2 = " user_canceled";
667 case TLS1_AD_NO_RENEGOTIATION:
668 str_details2 = " no_renegotiation";
674 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
675 str_details1 = "???";
677 if (tls_session->info.record_len > 0)
678 switch (tls_session->info.handshake_type)
680 case SSL3_MT_HELLO_REQUEST:
681 str_details1 = ", HelloRequest";
683 case SSL3_MT_CLIENT_HELLO:
684 str_details1 = ", ClientHello";
686 case SSL3_MT_SERVER_HELLO:
687 str_details1 = ", ServerHello";
689 case SSL3_MT_CERTIFICATE:
690 str_details1 = ", Certificate";
692 case SSL3_MT_SERVER_KEY_EXCHANGE:
693 str_details1 = ", ServerKeyExchange";
695 case SSL3_MT_CERTIFICATE_REQUEST:
696 str_details1 = ", CertificateRequest";
698 case SSL3_MT_SERVER_DONE:
699 str_details1 = ", ServerHelloDone";
701 case SSL3_MT_CERTIFICATE_VERIFY:
702 str_details1 = ", CertificateVerify";
704 case SSL3_MT_CLIENT_KEY_EXCHANGE:
705 str_details1 = ", ClientKeyExchange";
707 case SSL3_MT_FINISHED:
708 str_details1 = ", Finished";
714 snprintf(tls_session->info.info_description,
715 sizeof(tls_session->info.info_description),
716 "%s %s%s [length %04lx]%s%s\n",
717 str_write_p, str_version, str_content_type,
718 (unsigned long)tls_session->info.record_len,
719 str_details1, str_details2);
721 request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
723 RDEBUG2("%s\n", tls_session->info.info_description);
726 static CONF_PARSER cache_config[] = {
727 { "enable", PW_TYPE_BOOLEAN,
728 offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
729 { "lifetime", PW_TYPE_INTEGER,
730 offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
731 { "max_entries", PW_TYPE_INTEGER,
732 offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
733 { "name", PW_TYPE_STRING_PTR,
734 offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
735 { NULL, -1, 0, NULL, NULL } /* end the list */
738 static CONF_PARSER verify_config[] = {
739 { "tmpdir", PW_TYPE_STRING_PTR,
740 offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
741 { "client", PW_TYPE_STRING_PTR,
742 offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
743 { NULL, -1, 0, NULL, NULL } /* end the list */
746 #ifdef HAVE_OPENSSL_OCSP_H
747 static CONF_PARSER ocsp_config[] = {
748 { "enable", PW_TYPE_BOOLEAN,
749 offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
750 { "override_cert_url", PW_TYPE_BOOLEAN,
751 offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
752 { "url", PW_TYPE_STRING_PTR,
753 offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
754 { NULL, -1, 0, NULL, NULL } /* end the list */
758 static CONF_PARSER tls_server_config[] = {
759 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
760 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
761 { "dh_key_exchange", PW_TYPE_BOOLEAN,
762 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
763 { "rsa_key_length", PW_TYPE_INTEGER,
764 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
765 { "dh_key_length", PW_TYPE_INTEGER,
766 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
767 { "verify_depth", PW_TYPE_INTEGER,
768 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
769 { "CA_path", PW_TYPE_FILENAME,
770 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
771 { "pem_file_type", PW_TYPE_BOOLEAN,
772 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
773 { "private_key_file", PW_TYPE_FILENAME,
774 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
775 { "certificate_file", PW_TYPE_FILENAME,
776 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
777 { "CA_file", PW_TYPE_FILENAME,
778 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
779 { "private_key_password", PW_TYPE_STRING_PTR,
780 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
781 { "dh_file", PW_TYPE_STRING_PTR,
782 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
783 { "random_file", PW_TYPE_STRING_PTR,
784 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
785 { "fragment_size", PW_TYPE_INTEGER,
786 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
787 { "include_length", PW_TYPE_BOOLEAN,
788 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
789 { "check_crl", PW_TYPE_BOOLEAN,
790 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
791 { "allow_expired_crl", PW_TYPE_BOOLEAN,
792 offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
793 { "check_cert_cn", PW_TYPE_STRING_PTR,
794 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
795 { "cipher_list", PW_TYPE_STRING_PTR,
796 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
797 { "check_cert_issuer", PW_TYPE_STRING_PTR,
798 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
799 { "make_cert_command", PW_TYPE_STRING_PTR,
800 offsetof(fr_tls_server_conf_t, make_cert_command), NULL, NULL},
801 { "require_client_cert", PW_TYPE_BOOLEAN,
802 offsetof(fr_tls_server_conf_t, require_client_cert), NULL, NULL },
804 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
806 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
808 #ifdef HAVE_OPENSSL_OCSP_H
809 { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
812 { NULL, -1, 0, NULL, NULL } /* end the list */
816 static CONF_PARSER tls_client_config[] = {
817 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
818 offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
819 { "dh_key_exchange", PW_TYPE_BOOLEAN,
820 offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
821 { "rsa_key_length", PW_TYPE_INTEGER,
822 offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
823 { "dh_key_length", PW_TYPE_INTEGER,
824 offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
825 { "verify_depth", PW_TYPE_INTEGER,
826 offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
827 { "CA_path", PW_TYPE_FILENAME,
828 offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
829 { "pem_file_type", PW_TYPE_BOOLEAN,
830 offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
831 { "private_key_file", PW_TYPE_FILENAME,
832 offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
833 { "certificate_file", PW_TYPE_FILENAME,
834 offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
835 { "CA_file", PW_TYPE_FILENAME,
836 offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
837 { "private_key_password", PW_TYPE_STRING_PTR,
838 offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
839 { "dh_file", PW_TYPE_STRING_PTR,
840 offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
841 { "random_file", PW_TYPE_STRING_PTR,
842 offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
843 { "fragment_size", PW_TYPE_INTEGER,
844 offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
845 { "include_length", PW_TYPE_BOOLEAN,
846 offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
847 { "check_crl", PW_TYPE_BOOLEAN,
848 offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
849 { "check_cert_cn", PW_TYPE_STRING_PTR,
850 offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
851 { "cipher_list", PW_TYPE_STRING_PTR,
852 offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
853 { "check_cert_issuer", PW_TYPE_STRING_PTR,
854 offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
856 { NULL, -1, 0, NULL, NULL } /* end the list */
861 * TODO: Check for the type of key exchange * like conf->dh_key
863 static int load_dh_params(SSL_CTX *ctx, char *file)
868 if ((bio = BIO_new_file(file, "r")) == NULL) {
869 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
873 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
876 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters. DH cipher suites may not work!");
877 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
881 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
882 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
893 * Generate ephemeral RSA keys.
895 static int generate_eph_rsa_key(SSL_CTX *ctx)
899 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
901 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
902 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
912 * These functions don't do anything other than print debugging
915 * FIXME: Write sessions to some long-term storage, so that
916 * session resumption can still occur after the server
919 #define MAX_SESSION_SIZE (256)
921 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
924 char buffer[2 * MAX_SESSION_SIZE + 1];
926 size = sess->session_id_length;
927 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
929 fr_bin2hex(sess->session_id, buffer, size);
931 DEBUG2(" SSL: Removing session %s from the cache", buffer);
932 SSL_SESSION_free(sess);
937 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
940 char buffer[2 * MAX_SESSION_SIZE + 1];
942 size = sess->session_id_length;
943 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
945 fr_bin2hex(sess->session_id, buffer, size);
947 DEBUG2(" SSL: adding session %s to cache", buffer);
952 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
953 unsigned char *data, int len,
957 char buffer[2 * MAX_SESSION_SIZE + 1];
960 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
962 fr_bin2hex(data, buffer, size);
964 DEBUG2(" SSL: Client requested nonexistent cached session %s",
970 #ifdef HAVE_OPENSSL_OCSP_H
972 * This function extracts the OCSP Responder URL
973 * from an existing x509 certificate.
975 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
976 char **ppath, int *pssl)
980 AUTHORITY_INFO_ACCESS *aia;
981 ACCESS_DESCRIPTION *ad;
983 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
985 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
986 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
987 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
988 if (ad->location->type == GEN_URI) {
989 if(OCSP_parse_url(ad->location->d.ia5->data,
990 phost, pport, ppath, pssl))
999 * This function sends a OCSP request to a defined OCSP responder
1000 * and checks the OCSP response for correctness.
1002 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1003 fr_tls_server_conf_t *conf)
1005 OCSP_CERTID *certid;
1007 OCSP_RESPONSE *resp;
1008 OCSP_BASICRESP *bresp = NULL;
1018 * Create OCSP Request
1020 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1021 req = OCSP_REQUEST_new();
1022 OCSP_request_add0_id(req, certid);
1023 OCSP_request_add1_nonce(req, NULL, 8);
1026 * Send OCSP Request and get OCSP Response
1029 /* Get OCSP responder URL */
1030 if(conf->ocsp_override_url) {
1031 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
1034 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1037 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1039 /* Setup BIO socket to OCSP responder */
1040 cbio = BIO_new_connect(host);
1041 BIO_set_conn_port(cbio, port);
1042 BIO_do_connect(cbio);
1044 /* Send OCSP request and wait for response */
1045 resp = OCSP_sendreq_bio(cbio, path, req);
1047 radlog(L_ERR, "Error: Couldn't get OCSP response");
1052 /* Verify OCSP response */
1053 status = OCSP_response_status(resp);
1054 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1055 radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status));
1059 bresp = OCSP_response_get1_basic(resp);
1060 if(OCSP_check_nonce(req, bresp)!=1) {
1061 radlog(L_ERR, "Error: OCSP response has wrong nonce value");
1065 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1066 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
1074 /* Free OCSP Stuff */
1075 OCSP_REQUEST_free(req);
1076 OCSP_RESPONSE_free(resp);
1081 OCSP_BASICRESP_free(bresp);
1084 DEBUG2("[ocsp] --> Certificate is valid!");
1086 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1091 #endif /* HAVE_OPENSSL_OCSP_H */
1094 * For creating certificate attributes.
1096 static const char *cert_attr_names[5][2] = {
1097 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
1098 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
1099 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
1100 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
1101 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" }
1104 #define FR_TLS_SERIAL (0)
1105 #define FR_TLS_EXPIRATION (1)
1106 #define FR_TLS_SUBJECT (2)
1107 #define FR_TLS_ISSUER (3)
1108 #define FR_TLS_CN (4)
1111 * Before trusting a certificate, you must make sure that the
1112 * certificate is 'valid'. There are several steps that your
1113 * application can take in determining if a certificate is
1114 * valid. Commonly used steps are:
1116 * 1.Verifying the certificate's signature, and verifying that
1117 * the certificate has been issued by a trusted Certificate
1120 * 2.Verifying that the certificate is valid for the present date
1121 * (i.e. it is being presented within its validity dates).
1123 * 3.Verifying that the certificate has not been revoked by its
1124 * issuing Certificate Authority, by checking with respect to a
1125 * Certificate Revocation List (CRL).
1127 * 4.Verifying that the credentials presented by the certificate
1128 * fulfill additional requirements specific to the application,
1129 * such as with respect to access control lists or with respect
1130 * to OCSP (Online Certificate Status Processing).
1132 * NOTE: This callback will be called multiple times based on the
1133 * depth of the root certificate chain
1135 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1137 char subject[1024]; /* Used for the subject name */
1138 char issuer[1024]; /* Used for the issuer name */
1139 char common_name[1024];
1144 int err, depth, lookup;
1145 fr_tls_server_conf_t *conf;
1148 ASN1_INTEGER *sn = NULL;
1149 ASN1_TIME *asn_time = NULL;
1152 #ifdef HAVE_OPENSSL_OCSP_H
1153 X509_STORE *ocsp_store = NULL;
1157 client_cert = X509_STORE_CTX_get_current_cert(ctx);
1158 err = X509_STORE_CTX_get_error(ctx);
1159 depth = X509_STORE_CTX_get_error_depth(ctx);
1164 * Log client/issuing cert. If there's an error, log
1167 if ((lookup > 1) && !my_ok) lookup = 1;
1170 * Retrieve the pointer to the SSL of the connection currently treated
1171 * and the application specific data stored into the SSL object.
1173 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1174 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1175 if (!conf) return 1;
1177 request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1179 if (!request) return 1; /* FIXME: outbound TLS */
1181 rad_assert(request != NULL);
1182 certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1183 rad_assert(certs != NULL);
1184 identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1185 #ifdef HAVE_OPENSSL_OCSP_H
1186 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1191 * Get the Serial Number
1194 sn = X509_get_serialNumber(client_cert);
1197 * For this next bit, we create the attributes *only* if
1198 * we're at the client or issuing certificate, AND we
1199 * have a user identity. i.e. we don't create the
1200 * attributes for RadSec connections.
1203 (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1207 for (i = 0; i < sn->length; i++) {
1208 sprintf(p, "%02x", (unsigned int)sn->data[i]);
1212 pairmake(cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET));
1217 * Get the Expiration Date
1220 asn_time = X509_get_notAfter(client_cert);
1221 if (identity && (lookup <= 1) && asn_time &&
1222 (asn_time->length < MAX_STRING_LEN)) {
1223 memcpy(buf, (char*) asn_time->data, asn_time->length);
1224 buf[asn_time->length] = '\0';
1226 pairmake(cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET));
1230 * Get the Subject & Issuer
1232 subject[0] = issuer[0] = '\0';
1233 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1235 subject[sizeof(subject) - 1] = '\0';
1236 if (identity && (lookup <= 1) && subject[0] &&
1237 (strlen(subject) < MAX_STRING_LEN)) {
1239 pairmake(cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET));
1242 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1244 issuer[sizeof(issuer) - 1] = '\0';
1245 if (identity && (lookup <= 1) && issuer[0] &&
1246 (strlen(issuer) < MAX_STRING_LEN)) {
1248 pairmake(cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET));
1252 * Get the Common Name
1254 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1255 NID_commonName, common_name, sizeof(common_name));
1256 common_name[sizeof(common_name) - 1] = '\0';
1257 if (identity && (lookup <= 1) && common_name[0] &&
1258 (strlen(common_name) < MAX_STRING_LEN)) {
1260 pairmake(cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET));
1264 * If the CRL has expired, that might still be OK.
1267 (conf->allow_expired_crl) &&
1268 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1270 X509_STORE_CTX_set_error( ctx, 0 );
1274 const char *p = X509_verify_cert_error_string(err);
1275 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
1276 radius_pairmake(request, &request->packet->vps,
1277 "Module-Failure-Message", p, T_OP_SET);
1281 switch (ctx->error) {
1283 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1284 radlog(L_ERR, "issuer= %s\n", issuer);
1286 case X509_V_ERR_CERT_NOT_YET_VALID:
1287 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1288 radlog(L_ERR, "notBefore=");
1290 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1293 case X509_V_ERR_CERT_HAS_EXPIRED:
1294 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1295 radlog(L_ERR, "notAfter=");
1297 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1303 * If we're at the actual client cert, apply additional
1308 * If the conf tells us to, check cert issuer
1309 * against the specified value and fail
1310 * verification if they don't match.
1312 if (conf->check_cert_issuer &&
1313 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1314 radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1319 * If the conf tells us to, check the CN in the
1320 * cert against xlat'ed value, but only if the
1321 * previous checks passed.
1323 if (my_ok && conf->check_cert_cn) {
1324 if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, request, NULL)) {
1325 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
1326 conf->check_cert_cn);
1327 /* if this fails, fail the verification */
1330 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1331 if (strcmp(cn_str, common_name) != 0) {
1332 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1336 } /* check_cert_cn */
1338 #ifdef HAVE_OPENSSL_OCSP_H
1339 if (my_ok && conf->ocsp_enable){
1340 RDEBUG2("--> Starting OCSP Request");
1341 if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1342 radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
1344 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1348 while (conf->verify_client_cert_cmd) {
1353 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1354 conf->verify_tmp_dir, progname);
1355 fd = mkstemp(filename);
1357 RDEBUG("Failed creating file in %s: %s",
1358 conf->verify_tmp_dir, strerror(errno));
1362 fp = fdopen(fd, "w");
1364 RDEBUG("Failed opening file %s: %s",
1365 filename, strerror(errno));
1369 if (!PEM_write_X509(fp, client_cert)) {
1371 RDEBUG("Failed writing certificate to file");
1376 if (!radius_pairmake(request, &request->packet->vps,
1377 "TLS-Client-Cert-Filename",
1378 filename, T_OP_SET)) {
1379 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1384 RDEBUG("Verifying client certificate: %s",
1385 conf->verify_client_cert_cmd);
1386 if (radius_exec_program(conf->verify_client_cert_cmd,
1387 request, 1, NULL, 0,
1388 request->packet->vps,
1390 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
1393 RDEBUG("Client certificate CN %s passed external validation", common_name);
1404 if (debug_flag > 0) {
1405 RDEBUG2("chain-depth=%d, ", depth);
1406 RDEBUG2("error=%d", err);
1408 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1409 RDEBUG2("--> BUF-Name = %s", common_name);
1410 RDEBUG2("--> subject = %s", subject);
1411 RDEBUG2("--> issuer = %s", issuer);
1412 RDEBUG2("--> verify return:%d", my_ok);
1418 #ifdef HAVE_OPENSSL_OCSP_H
1420 * Create Global X509 revocation store and use it to verify
1423 * - Load the trusted CAs
1424 * - Load the trusted issuer certificates
1426 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1428 X509_STORE *store = NULL;
1430 store = X509_STORE_new();
1432 /* Load the CAs we trust */
1433 if (conf->ca_file || conf->ca_path)
1434 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1435 radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1436 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1440 #ifdef X509_V_FLAG_CRL_CHECK
1441 if (conf->check_crl)
1442 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1446 #endif /* HAVE_OPENSSL_OCSP_H */
1449 * Create Global context SSL and use it in every new session
1451 * - Load the trusted CAs
1452 * - Load the Private key & the certificate
1453 * - Set the Context options & Verify options
1455 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf)
1457 const SSL_METHOD *meth;
1459 X509_STORE *certstore;
1460 int verify_mode = SSL_VERIFY_NONE;
1461 int ctx_options = 0;
1465 * Add all the default ciphers and message digests
1466 * Create our context.
1469 SSL_load_error_strings();
1472 * SHA256 is in all versions of OpenSSL, but isn't
1473 * initialized by default. It's needed for WiMAX
1476 #ifdef HAVE_OPENSSL_EVP_SHA256
1477 EVP_add_digest(EVP_sha256());
1480 meth = TLSv1_method();
1481 ctx = SSL_CTX_new(meth);
1484 * Identify the type of certificates that needs to be loaded
1486 if (conf->file_type) {
1487 type = SSL_FILETYPE_PEM;
1489 type = SSL_FILETYPE_ASN1;
1493 * Set the password to load private key
1495 if (conf->private_key_password) {
1498 * We don't want to put the private key password in eap.conf, so check
1499 * for our special string which indicates we should get the password
1502 const char* special_string = "Apple:UseCertAdmin";
1503 if (strncmp(conf->private_key_password,
1505 strlen(special_string)) == 0)
1508 const long max_password_len = 128;
1509 snprintf(cmd, sizeof(cmd) - 1,
1510 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
1511 conf->private_key_file);
1513 DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
1515 FILE* cmd_pipe = popen(cmd, "r");
1517 radlog(L_ERR, "rlm_eap: %s command failed. Unable to get private_key_password", cmd);
1518 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1522 free(conf->private_key_password);
1523 conf->private_key_password = malloc(max_password_len * sizeof(char));
1524 if (!conf->private_key_password) {
1525 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
1526 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1531 fgets(conf->private_key_password, max_password_len, cmd_pipe);
1534 /* Get rid of newline at end of password. */
1535 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
1536 DEBUG2("rlm_eap: Password from command = \"%s\"", conf->private_key_password);
1539 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
1540 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
1544 * Load our keys and certificates
1546 * If certificates are of type PEM then we can make use
1547 * of cert chain authentication using openssl api call
1548 * SSL_CTX_use_certificate_chain_file. Please see how
1549 * the cert chain needs to be given in PEM from
1552 if (!conf->certificate_file) goto load_ca;
1554 if (type == SSL_FILETYPE_PEM) {
1555 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
1556 radlog(L_ERR, "Error reading certificate file %s:%s",
1557 conf->certificate_file,
1558 ERR_error_string(ERR_get_error(), NULL));
1562 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
1563 radlog(L_ERR, "Error reading certificate file %s:%s",
1564 conf->certificate_file,
1565 ERR_error_string(ERR_get_error(), NULL));
1569 /* Load the CAs we trust */
1571 if (conf->ca_file || conf->ca_path) {
1572 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
1573 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1574 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1578 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
1580 if (conf->private_key_file) {
1581 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
1582 radlog(L_ERR, "Failed reading private key file %s:%s",
1583 conf->private_key_file,
1584 ERR_error_string(ERR_get_error(), NULL));
1589 * Check if the loaded private key is the right one
1591 if (!SSL_CTX_check_private_key(ctx)) {
1592 radlog(L_ERR, "Private key does not match the certificate public key");
1600 ctx_options |= SSL_OP_NO_SSLv2;
1601 ctx_options |= SSL_OP_NO_SSLv3;
1602 #ifdef SSL_OP_NO_TICKET
1603 ctx_options |= SSL_OP_NO_TICKET ;
1607 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
1608 * small subgroup attacks and forward secrecy. Always
1611 * SSL_OP_SINGLE_DH_USE has an impact on the computer
1612 * time needed during negotiation, but it is not very
1615 ctx_options |= SSL_OP_SINGLE_DH_USE;
1618 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
1619 * in Windows Vista client.
1620 * http://www.openssl.org/~bodo/tls-cbc.txt
1621 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
1623 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1625 SSL_CTX_set_options(ctx, ctx_options);
1628 * TODO: Set the RSA & DH
1629 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
1630 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
1634 * set the message callback to identify the type of
1635 * message. For every new session, there can be a
1636 * different callback argument.
1638 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
1641 /* Set Info callback */
1642 SSL_CTX_set_info_callback(ctx, cbtls_info);
1645 * Callbacks, etc. for session resumption.
1647 if (conf->session_cache_enable) {
1648 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
1649 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
1650 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
1652 SSL_CTX_set_quiet_shutdown(ctx, 1);
1656 * Check the certificates for revocation.
1658 #ifdef X509_V_FLAG_CRL_CHECK
1659 if (conf->check_crl) {
1660 certstore = SSL_CTX_get_cert_store(ctx);
1661 if (certstore == NULL) {
1662 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1663 radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
1666 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
1672 * Always verify the peer certificate
1674 verify_mode |= SSL_VERIFY_PEER;
1675 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1676 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1677 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
1679 if (conf->verify_depth) {
1680 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
1683 /* Load randomness */
1684 if (!(RAND_load_file(conf->random_file, 1024*1024))) {
1685 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1686 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
1691 * Set the cipher list if we were told to
1693 if (conf->cipher_list) {
1694 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
1695 radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
1701 * Setup session caching
1703 if (conf->session_cache_enable) {
1705 * Create a unique context Id per EAP-TLS configuration.
1707 if (conf->session_id_name) {
1708 snprintf(conf->session_context_id,
1709 sizeof(conf->session_context_id),
1710 "FreeRADIUS EAP-TLS %s",
1711 conf->session_id_name);
1713 snprintf(conf->session_context_id,
1714 sizeof(conf->session_context_id),
1715 "FreeRADIUS EAP-TLS %p", conf);
1719 * Cache it, and DON'T auto-clear it.
1721 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
1723 SSL_CTX_set_session_id_context(ctx,
1724 (unsigned char *) conf->session_context_id,
1725 (unsigned int) strlen(conf->session_context_id));
1728 * Our timeout is in hours, this is in seconds.
1730 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
1733 * Set the maximum number of entries in the
1736 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
1739 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1746 void tls_server_conf_free(fr_tls_server_conf_t *conf)
1750 if (conf->cs) cf_section_parse_free(conf->cs, conf);
1752 if (conf->ctx) SSL_CTX_free(conf->ctx);
1754 #ifdef HAVE_OPENSSL_OCSP_H
1755 if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
1756 conf->ocsp_store = NULL;
1759 memset(conf, 0, sizeof(*conf));
1764 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
1766 fr_tls_server_conf_t *conf;
1768 conf = malloc(sizeof(*conf));
1770 radlog(L_ERR, "Out of memory");
1773 memset(conf, 0, sizeof(*conf));
1775 if (cf_section_parse(cs, conf, tls_server_config) < 0) {
1777 tls_server_conf_free(conf);
1782 * Save people from their own stupidity.
1784 if (conf->fragment_size < 100) conf->fragment_size = 100;
1787 * This magic makes the administrators life HUGELY easier
1788 * on initial deployments.
1790 * If the server starts up in debugging mode, AND the
1791 * bootstrap command is configured, AND it exists, AND
1792 * there is no server certificate
1794 if (conf->make_cert_command && (debug_flag >= 2)) {
1797 if ((stat(conf->make_cert_command, &buf) == 0) &&
1798 (stat(conf->certificate_file, &buf) < 0) &&
1799 (errno == ENOENT) &&
1800 (radius_exec_program(conf->make_cert_command, NULL, 1,
1801 NULL, 0, NULL, NULL, 0) != 0)) {
1806 if (!conf->private_key_file) {
1807 radlog(L_ERR, "TLS Server requires a private key file");
1811 if (!conf->private_key_password) {
1812 radlog(L_ERR, "TLS Server requires a private key password");
1816 if (!conf->certificate_file) {
1817 radlog(L_ERR, "TLS Server requires a certificate file");
1824 conf->ctx = init_tls_ctx(conf);
1825 if (conf->ctx == NULL) {
1829 #ifdef HAVE_OPENSSL_OCSP_H
1831 * Initialize OCSP Revocation Store
1833 if (conf->ocsp_enable) {
1834 conf->ocsp_store = init_revocation_store(conf);
1835 if (conf->ocsp_store == NULL) goto error;
1837 #endif HAVE_OPENSSL_OCSP_H
1839 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
1843 if (generate_eph_rsa_key(conf->ctx) < 0) {
1847 if (conf->verify_tmp_dir) {
1848 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
1849 radlog(L_ERR, "Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
1854 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
1855 radlog(L_ERR, "You MUST set the verify directory in order to use verify_client_cmd");
1862 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
1864 fr_tls_server_conf_t *conf;
1866 conf = malloc(sizeof(*conf));
1868 radlog(L_ERR, "Out of memory");
1871 memset(conf, 0, sizeof(*conf));
1873 if (cf_section_parse(cs, conf, tls_client_config) < 0) {
1875 tls_server_conf_free(conf);
1880 * Save people from their own stupidity.
1882 if (conf->fragment_size < 100) conf->fragment_size = 100;
1887 conf->ctx = init_tls_ctx(conf);
1888 if (conf->ctx == NULL) {
1892 if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
1896 if (generate_eph_rsa_key(conf->ctx) < 0) {
1903 int tls_success(tls_session_t *ssn, REQUEST *request)
1905 VALUE_PAIR *vp, *vps = NULL;
1906 fr_tls_server_conf_t *conf;
1908 conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
1909 rad_assert(conf != NULL);
1912 * If there's no session resumption, delete the entry
1913 * from the cache. This means either it's disabled
1914 * globally for this SSL context, OR we were told to
1915 * disable it for this user.
1917 * This also means you can't turn it on just for one
1920 if ((!ssn->allow_session_resumption) ||
1921 (((vp = pairfind(request->config_items, 1127, 0)) != NULL) &&
1922 (vp->vp_integer == 0))) {
1923 SSL_CTX_remove_session(ssn->ctx,
1925 ssn->allow_session_resumption = 0;
1928 * If we're in a resumed session and it's
1931 if (SSL_session_reused(ssn->ssl)) {
1932 RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed.");
1937 * Else resumption IS allowed, so we store the
1938 * user data in the cache.
1940 } else if (!SSL_session_reused(ssn->ssl)) {
1941 RDEBUG2("Saving response in the cache");
1943 vp = paircopy2(request->reply->vps, PW_USER_NAME, 0);
1944 if (vp) pairadd(&vps, vp);
1946 vp = paircopy2(request->packet->vps, PW_STRIPPED_USER_NAME, 0);
1947 if (vp) pairadd(&vps, vp);
1949 vp = paircopy2(request->reply->vps, PW_CACHED_SESSION_POLICY, 0);
1950 if (vp) pairadd(&vps, vp);
1953 SSL_SESSION_set_ex_data(ssn->ssl->session,
1954 FR_TLS_EX_INDEX_VPS, vps);
1956 RDEBUG2("WARNING: No information to cache: session caching will be disabled for this session.");
1957 SSL_CTX_remove_session(ssn->ctx,
1962 * Else the session WAS allowed. Copy the cached
1967 vp = SSL_SESSION_get_ex_data(ssn->ssl->session,
1968 FR_TLS_EX_INDEX_VPS);
1970 RDEBUG("WARNING: No information in cached session!");
1974 RDEBUG("Adding cached attributes to the reply:");
1975 debug_pair_list(vp);
1976 pairadd(&request->reply->vps, paircopy(vp));
1979 * Mark the request as resumed.
1981 vp = pairmake("EAP-Session-Resumed", "1", T_OP_SET);
1982 if (vp) pairadd(&request->packet->vps, vp);
1990 void tls_fail(tls_session_t *ssn)
1993 * Force the session to NOT be cached.
1995 SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
1998 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2005 * Decrypt the complete record.
2007 err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2008 ssn->dirty_in.used);
2009 if (err != (int) ssn->dirty_in.used) {
2010 record_init(&ssn->dirty_in);
2011 RDEBUG("Failed writing %d to SSL BIO: %d",
2012 ssn->dirty_in.used, err);
2017 * Clear the dirty buffer now that we are done with it
2018 * and init the clean_out buffer to store decrypted data
2020 record_init(&ssn->dirty_in);
2021 record_init(&ssn->clean_out);
2024 * Read (and decrypt) the tunneled data from the
2025 * SSL session, and put it into the decrypted
2028 err = SSL_read(ssn->ssl, ssn->clean_out.data,
2029 sizeof(ssn->clean_out.data));
2034 RDEBUG("SSL_read Error");
2036 code = SSL_get_error(ssn->ssl, err);
2038 case SSL_ERROR_WANT_READ:
2039 return FR_TLS_MORE_FRAGMENTS;
2040 DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2043 case SSL_ERROR_WANT_WRITE:
2044 DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2048 DEBUG("Error in fragmentation logic: ?");
2051 * FIXME: Call int_ssl_check?
2059 RDEBUG("WARNING: No data inside of the tunnel.");
2063 * Passed all checks, successfully decrypted data
2065 ssn->clean_out.used = err;
2072 * Acknowledge received is for one of the following messages sent earlier
2073 * 1. Handshake completed Message, so now send, EAP-Success
2074 * 2. Alert Message, now send, EAP-Failure
2075 * 3. Fragment Message, now send, next Fragment
2077 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2079 RDEBUG2("Received TLS ACK");
2082 radlog_request(L_ERR, 0, request, "FAIL: Unexpected ACK received. Could not obtain session information.");
2083 return FR_TLS_INVALID;
2085 if (ssn->info.initialized == 0) {
2086 RDEBUG("No SSL info available. Waiting for more SSL data.");
2087 return FR_TLS_REQUEST;
2089 if ((ssn->info.content_type == handshake) &&
2090 (ssn->info.origin == 0)) {
2091 radlog_request(L_ERR, 0, request, "FAIL: ACK without earlier message.");
2092 return FR_TLS_INVALID;
2095 switch (ssn->info.content_type) {
2097 RDEBUG2("ACK alert");
2101 if ((ssn->info.handshake_type == finished) &&
2102 (ssn->dirty_out.used == 0)) {
2103 RDEBUG2("ACK handshake is finished");
2106 * From now on all the content is
2107 * application data set it here as nobody else
2110 ssn->info.content_type = application_data;
2111 return FR_TLS_SUCCESS;
2112 } /* else more data to send */
2114 RDEBUG2("ACK handshake fragment handler");
2115 /* Fragmentation handler, send next fragment */
2116 return FR_TLS_REQUEST;
2118 case application_data:
2119 RDEBUG2("ACK handshake fragment handler in application data");
2120 return FR_TLS_REQUEST;
2123 * For the rest of the conditions, switch over
2124 * to the default section below.
2127 RDEBUG2("ACK default");
2128 radlog_request(L_ERR, 0, request, "Invalid ACK received: %d",
2129 ssn->info.content_type);
2130 return FR_TLS_INVALID;
2134 static void dump_hex(const char *msg, const uint8_t *data, size_t data_len)
2138 if (debug_flag < 3) return;
2140 printf("%s %d\n", msg, (int) data_len);
2141 if (data_len > 256) data_len = 256;
2143 for (i = 0; i < data_len; i++) {
2144 if ((i & 0x0f) == 0x00) printf ("%02x: ", (unsigned int) i);
2145 printf("%02x ", data[i]);
2146 if ((i & 0x0f) == 0x0f) printf ("\n");
2152 static void tls_socket_close(rad_listen_t *listener)
2154 listen_socket_t *sock = listener->data;
2156 listener->status = RAD_LISTEN_STATUS_REMOVE_FD;
2157 listener->tls = NULL; /* parent owns this! */
2161 * Decrement the number of connections.
2163 if (sock->parent->num_connections > 0) {
2164 sock->parent->num_connections--;
2166 if (sock->client->num_connections > 0) {
2167 sock->client->num_connections--;
2172 * Tell the event handler that an FD has disappeared.
2174 DEBUG("Client has closed connection");
2175 event_new_fd(listener);
2178 * Do NOT free the listener here. It's in use by
2179 * a request, and will need to hang around until
2180 * all of the requests are done.
2182 * It is instead free'd in remove_from_request_hash()
2186 static int tls_socket_write(rad_listen_t *listener, REQUEST *request)
2190 listen_socket_t *sock = listener->data;
2192 p = sock->ssn->dirty_out.data;
2194 while (p < (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used)) {
2195 RDEBUG3("Writing to socket %d", request->packet->sockfd);
2196 rcode = write(request->packet->sockfd, p,
2197 (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used) - p);
2199 RDEBUG("Error writing to TLS socket: %s", strerror(errno));
2201 tls_socket_close(listener);
2207 sock->ssn->dirty_out.used = 0;
2213 static int tls_socket_recv(rad_listen_t *listener)
2215 int doing_init = FALSE;
2217 RADIUS_PACKET *packet;
2219 listen_socket_t *sock = listener->data;
2220 fr_tls_status_t status;
2221 RADCLIENT *client = sock->client;
2223 if (!sock->packet) {
2224 sock->packet = rad_alloc(0);
2225 if (!sock->packet) return 0;
2227 sock->packet->sockfd = listener->fd;
2228 sock->packet->src_ipaddr = sock->other_ipaddr;
2229 sock->packet->src_port = sock->other_port;
2230 sock->packet->dst_ipaddr = sock->my_ipaddr;
2231 sock->packet->dst_port = sock->my_port;
2233 if (sock->request) sock->request->packet = sock->packet;
2237 * Allocate a REQUEST for debugging.
2239 if (!sock->request) {
2240 sock->request = request = request_alloc();
2241 if (!sock->request) {
2242 radlog(L_ERR, "Out of memory");
2246 rad_assert(request->packet == NULL);
2247 rad_assert(sock->packet != NULL);
2248 request->packet = sock->packet;
2250 request->component = "<core>";
2251 request->component = "<tls-connect>";
2254 * Not sure if we should do this on every packet...
2256 request->reply = rad_alloc(0);
2257 if (!request->reply) return 0;
2259 request->options = RAD_REQUEST_OPTION_DEBUG2;
2261 rad_assert(sock->ssn == NULL);
2263 sock->ssn = tls_new_session(listener->tls, sock->request,
2264 listener->tls->require_client_cert);
2266 request_free(&sock->request);
2267 sock->packet = NULL;
2271 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
2272 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_CERTS, (void *)&request->packet->vps);
2277 rad_assert(sock->request != NULL);
2278 rad_assert(sock->request->packet != NULL);
2279 rad_assert(sock->packet != NULL);
2280 rad_assert(sock->ssn != NULL);
2282 request = sock->request;
2284 RDEBUG3("Reading from socket %d", request->packet->sockfd);
2285 PTHREAD_MUTEX_LOCK(&sock->mutex);
2286 rcode = read(request->packet->sockfd,
2287 sock->ssn->dirty_in.data,
2288 sizeof(sock->ssn->dirty_in.data));
2289 if ((rcode < 0) && (errno == ECONNRESET)) {
2291 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2292 tls_socket_close(listener);
2297 RDEBUG("Error reading TLS socket: %s", strerror(errno));
2302 * Normal socket close.
2304 if (rcode == 0) goto do_close;
2306 sock->ssn->dirty_in.used = rcode;
2307 memset(sock->ssn->dirty_in.data + sock->ssn->dirty_in.used,
2310 dump_hex("READ FROM SSL", sock->ssn->dirty_in.data, sock->ssn->dirty_in.used);
2313 * Catch attempts to use non-SSL.
2315 if (doing_init && (sock->ssn->dirty_in.data[0] != handshake)) {
2316 RDEBUG("Non-TLS data sent to TLS socket: closing");
2321 * Skip ahead to reading application data.
2323 if (SSL_is_init_finished(sock->ssn->ssl)) goto app;
2325 if (!tls_handshake_recv(request, sock->ssn)) {
2326 RDEBUG("FAILED in TLS handshake receive");
2330 if (sock->ssn->dirty_out.used > 0) {
2331 tls_socket_write(listener, request);
2332 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2338 * FIXME: Run the packet through a virtual server in
2339 * order to see if we like the certificate presented by
2343 status = tls_application_data(sock->ssn, request);
2344 RDEBUG("Application data status %d", status);
2346 if (status == FR_TLS_MORE_FRAGMENTS) {
2347 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2351 if (sock->ssn->clean_out.used == 0) {
2352 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2356 dump_hex("TUNNELED DATA", sock->ssn->clean_out.data, sock->ssn->clean_out.used);
2359 * If the packet is a complete RADIUS packet, return it to
2360 * the caller. Otherwise...
2362 if ((sock->ssn->clean_out.used < 20) ||
2363 (((sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]) != (int) sock->ssn->clean_out.used)) {
2364 RDEBUG("Received bad packet: Length %d contents %d",
2365 sock->ssn->clean_out.used,
2366 (sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]);
2370 packet = sock->packet;
2371 packet->data = rad_malloc(sock->ssn->clean_out.used);
2372 packet->data_len = sock->ssn->clean_out.used;
2373 memcpy(packet->data, sock->ssn->clean_out.data, packet->data_len);
2375 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2377 if (!rad_packet_ok(packet, 0)) {
2378 RDEBUG("Received bad packet: %s", fr_strerror());
2379 tls_socket_close(listener);
2380 return 0; /* do_close unlocks the mutex */
2384 * Copied from src/lib/radius.c, rad_recv();
2386 if (fr_debug_flag) {
2387 char host_ipaddr[128];
2389 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2390 RDEBUG("tls_recv: %s packet from host %s port %d, id=%d, length=%d",
2391 fr_packet_codes[packet->code],
2392 inet_ntop(packet->src_ipaddr.af,
2393 &packet->src_ipaddr.ipaddr,
2394 host_ipaddr, sizeof(host_ipaddr)),
2396 packet->id, (int) packet->data_len);
2398 RDEBUG("tls_recv: Packet from host %s port %d code=%d, id=%d, length=%d",
2399 inet_ntop(packet->src_ipaddr.af,
2400 &packet->src_ipaddr.ipaddr,
2401 host_ipaddr, sizeof(host_ipaddr)),
2404 packet->id, (int) packet->data_len);
2408 FR_STATS_INC(auth, total_requests);
2414 int dual_tls_recv(rad_listen_t *listener)
2416 RADIUS_PACKET *packet;
2418 RAD_REQUEST_FUNP fun = NULL;
2419 listen_socket_t *sock = listener->data;
2420 RADCLIENT *client = sock->client;
2422 if (!tls_socket_recv(listener)) {
2426 rad_assert(sock->request != NULL);
2427 rad_assert(sock->request->packet != NULL);
2428 rad_assert(sock->packet != NULL);
2429 rad_assert(sock->ssn != NULL);
2431 request = sock->request;
2432 packet = sock->packet;
2435 * Some sanity checks, based on the packet code.
2437 switch(packet->code) {
2438 case PW_AUTHENTICATION_REQUEST:
2439 if (listener->type != RAD_LISTEN_AUTH) goto bad_packet;
2440 FR_STATS_INC(auth, total_requests);
2441 fun = rad_authenticate;
2444 case PW_ACCOUNTING_REQUEST:
2445 if (listener->type != RAD_LISTEN_ACCT) goto bad_packet;
2446 FR_STATS_INC(acct, total_requests);
2447 fun = rad_accounting;
2450 case PW_STATUS_SERVER:
2451 if (!mainconfig.status_server) {
2452 FR_STATS_INC(auth, total_unknown_types);
2453 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
2454 rad_free(&sock->packet);
2455 request->packet = NULL;
2458 fun = rad_status_server;
2463 FR_STATS_INC(auth, total_unknown_types);
2465 DEBUG("Invalid packet code %d sent from client %s port %d : IGNORED",
2466 packet->code, client->shortname, packet->src_port);
2467 rad_free(&sock->packet);
2468 request->packet = NULL;
2470 } /* switch over packet types */
2472 if (!request_receive(listener, packet, client, fun)) {
2473 FR_STATS_INC(auth, total_packets_dropped);
2474 rad_free(&sock->packet);
2475 request->packet = NULL;
2479 sock->packet = NULL; /* we have no need for more partial reads */
2480 request->packet = NULL;
2487 * Send a response packet
2489 int dual_tls_send(rad_listen_t *listener, REQUEST *request)
2491 listen_socket_t *sock = listener->data;
2493 rad_assert(request->listener == listener);
2494 rad_assert(listener->send == dual_tls_send);
2497 * Accounting reject's are silently dropped.
2499 * We do it here to avoid polluting the rest of the
2500 * code with this knowledge
2502 if (request->reply->code == 0) return 0;
2507 if (rad_encode(request->reply, request->packet,
2508 request->client->secret) < 0) {
2509 RDEBUG("Failed encoding packet: %s", fr_strerror());
2516 if (rad_sign(request->reply, request->packet,
2517 request->client->secret) < 0) {
2518 RDEBUG("Failed signing packet: %s", fr_strerror());
2522 PTHREAD_MUTEX_LOCK(&sock->mutex);
2524 * Write the packet to the SSL buffers.
2526 record_plus(&sock->ssn->clean_in,
2527 request->reply->data, request->reply->data_len);
2530 * Do SSL magic to get encrypted data.
2532 tls_handshake_send(request, sock->ssn);
2535 * And finally write the data to the socket.
2537 if (sock->ssn->dirty_out.used > 0) {
2538 dump_hex("WRITE TO SSL", sock->ssn->dirty_out.data, sock->ssn->dirty_out.used);
2540 tls_socket_write(listener, request);
2542 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2548 int proxy_tls_recv(rad_listen_t *listener)
2552 listen_socket_t *sock = listener->data;
2555 RADIUS_PACKET *packet;
2556 RAD_REQUEST_FUNP fun = NULL;
2558 DEBUG3("Proxy SSL socket has data to read");
2559 PTHREAD_MUTEX_LOCK(&sock->mutex);
2561 rcode = SSL_read(sock->ssn->ssl, data, 4);
2563 int err = SSL_get_error(sock->ssn->ssl, rcode);
2565 case SSL_ERROR_WANT_READ:
2566 case SSL_ERROR_WANT_WRITE:
2569 case SSL_ERROR_ZERO_RETURN:
2570 /* remote end sent close_notify, send one back */
2571 SSL_shutdown(sock->ssn->ssl);
2573 case SSL_ERROR_SYSCALL:
2575 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2576 tls_socket_close(listener);
2580 while ((err = ERR_get_error())) {
2581 DEBUG("proxy recv says %s",
2582 ERR_error_string(err, NULL));
2589 length = (data[2] << 8) | data[3];
2590 DEBUG3("Proxy received header saying we have a packet of %u bytes",
2591 (unsigned int) length);
2593 if (length > sizeof(data)) {
2594 DEBUG("Received packet will be too large! (%u)",
2595 (data[2] << 8) | data[3]);
2599 rcode = SSL_read(sock->ssn->ssl, data + 4, length);
2601 switch (SSL_get_error(sock->ssn->ssl, rcode)) {
2602 case SSL_ERROR_WANT_READ:
2603 case SSL_ERROR_WANT_WRITE:
2607 case SSL_ERROR_ZERO_RETURN:
2608 /* remote end sent close_notify, send one back */
2609 SSL_shutdown(sock->ssn->ssl);
2615 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2617 packet = rad_alloc(0);
2618 packet->sockfd = listener->fd;
2619 packet->src_ipaddr = sock->other_ipaddr;
2620 packet->src_port = sock->other_port;
2621 packet->dst_ipaddr = sock->my_ipaddr;
2622 packet->dst_port = sock->my_port;
2623 packet->code = data[0];
2624 packet->id = data[1];
2625 packet->data_len = length;
2626 packet->data = rad_malloc(packet->data_len);
2627 memcpy(packet->data, data, packet->data_len);
2628 memcpy(packet->vector, packet->data + 4, 16);
2631 * FIXME: Client MIB updates?
2633 switch(packet->code) {
2634 case PW_AUTHENTICATION_ACK:
2635 case PW_ACCESS_CHALLENGE:
2636 case PW_AUTHENTICATION_REJECT:
2637 fun = rad_authenticate;
2640 #ifdef WITH_ACCOUNTING
2641 case PW_ACCOUNTING_RESPONSE:
2642 fun = rad_accounting;
2648 * FIXME: Update MIB for packet types?
2650 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
2651 "from home server %s port %d - ID %d : IGNORED",
2653 ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
2654 packet->src_port, packet->id);
2659 if (!request_proxy_reply(packet)) {
2667 int proxy_tls_send(rad_listen_t *listener, REQUEST *request)
2670 listen_socket_t *sock = listener->data;
2673 * Normal proxying calls us with the data already
2674 * encoded. The "ping home server" code does not. So,
2675 * if there's no packet, encode it here.
2677 if (!request->proxy->data) {
2678 request->proxy_listener->encode(request->proxy_listener,
2682 DEBUG3("Proxy is writing %u bytes to SSL",
2683 (unsigned int) request->proxy->data_len);
2684 PTHREAD_MUTEX_LOCK(&sock->mutex);
2685 while ((rcode = SSL_write(sock->ssn->ssl, request->proxy->data,
2686 request->proxy->data_len)) < 0) {
2688 while ((err = ERR_get_error())) {
2689 DEBUG("proxy SSL_write says %s",
2690 ERR_error_string(err, NULL));
2692 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2693 tls_socket_close(listener);
2696 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
2701 #endif /* WITH_TLS */