2 * rlm_eap_tls.c contains the interfaces that are called from eap
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2001 hereUare Communications, Inc. <raghud@hereuare.com>
21 * Copyright 2003 Alan DeKok <aland@freeradius.org>
22 * Copyright 2006 The FreeRADIUS server project
26 #include <freeradius-devel/ident.h>
29 #include <freeradius-devel/autoconf.h>
31 #ifdef HAVE_OPENSSL_RAND_H
32 #include <openssl/rand.h>
35 #ifdef HAVE_OPENSSL_EVP_H
36 #include <openssl/evp.h>
39 #include "rlm_eap_tls.h"
42 #ifdef HAVE_SYS_STAT_H
46 static CONF_PARSER cache_config[] = {
47 { "enable", PW_TYPE_BOOLEAN,
48 offsetof(EAP_TLS_CONF, session_cache_enable), NULL, "no" },
49 { "lifetime", PW_TYPE_INTEGER,
50 offsetof(EAP_TLS_CONF, session_timeout), NULL, "24" },
51 { "max_entries", PW_TYPE_INTEGER,
52 offsetof(EAP_TLS_CONF, session_cache_size), NULL, "255" },
53 { "name", PW_TYPE_STRING_PTR,
54 offsetof(EAP_TLS_CONF, session_id_name), NULL, NULL},
55 { NULL, -1, 0, NULL, NULL } /* end the list */
58 static CONF_PARSER verify_config[] = {
59 { "tmpdir", PW_TYPE_STRING_PTR,
60 offsetof(EAP_TLS_CONF, verify_tmp_dir), NULL, NULL},
61 { "client", PW_TYPE_STRING_PTR,
62 offsetof(EAP_TLS_CONF, verify_client_cert_cmd), NULL, NULL},
63 { NULL, -1, 0, NULL, NULL } /* end the list */
66 static CONF_PARSER module_config[] = {
67 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
68 offsetof(EAP_TLS_CONF, rsa_key), NULL, "no" },
69 { "dh_key_exchange", PW_TYPE_BOOLEAN,
70 offsetof(EAP_TLS_CONF, dh_key), NULL, "yes" },
71 { "rsa_key_length", PW_TYPE_INTEGER,
72 offsetof(EAP_TLS_CONF, rsa_key_length), NULL, "512" },
73 { "dh_key_length", PW_TYPE_INTEGER,
74 offsetof(EAP_TLS_CONF, dh_key_length), NULL, "512" },
75 { "verify_depth", PW_TYPE_INTEGER,
76 offsetof(EAP_TLS_CONF, verify_depth), NULL, "0" },
77 { "CA_path", PW_TYPE_FILENAME,
78 offsetof(EAP_TLS_CONF, ca_path), NULL, NULL },
79 { "pem_file_type", PW_TYPE_BOOLEAN,
80 offsetof(EAP_TLS_CONF, file_type), NULL, "yes" },
81 { "private_key_file", PW_TYPE_FILENAME,
82 offsetof(EAP_TLS_CONF, private_key_file), NULL, NULL },
83 { "certificate_file", PW_TYPE_FILENAME,
84 offsetof(EAP_TLS_CONF, certificate_file), NULL, NULL },
85 { "CA_file", PW_TYPE_FILENAME,
86 offsetof(EAP_TLS_CONF, ca_file), NULL, NULL },
87 { "private_key_password", PW_TYPE_STRING_PTR,
88 offsetof(EAP_TLS_CONF, private_key_password), NULL, NULL },
89 { "dh_file", PW_TYPE_STRING_PTR,
90 offsetof(EAP_TLS_CONF, dh_file), NULL, NULL },
91 { "random_file", PW_TYPE_STRING_PTR,
92 offsetof(EAP_TLS_CONF, random_file), NULL, NULL },
93 { "fragment_size", PW_TYPE_INTEGER,
94 offsetof(EAP_TLS_CONF, fragment_size), NULL, "1024" },
95 { "include_length", PW_TYPE_BOOLEAN,
96 offsetof(EAP_TLS_CONF, include_length), NULL, "yes" },
97 { "check_crl", PW_TYPE_BOOLEAN,
98 offsetof(EAP_TLS_CONF, check_crl), NULL, "no"},
99 { "check_cert_cn", PW_TYPE_STRING_PTR,
100 offsetof(EAP_TLS_CONF, check_cert_cn), NULL, NULL},
101 { "cipher_list", PW_TYPE_STRING_PTR,
102 offsetof(EAP_TLS_CONF, cipher_list), NULL, NULL},
103 { "check_cert_issuer", PW_TYPE_STRING_PTR,
104 offsetof(EAP_TLS_CONF, check_cert_issuer), NULL, NULL},
105 { "make_cert_command", PW_TYPE_STRING_PTR,
106 offsetof(EAP_TLS_CONF, make_cert_command), NULL, NULL},
108 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
110 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
112 { NULL, -1, 0, NULL, NULL } /* end the list */
117 * TODO: Check for the type of key exchange * like conf->dh_key
119 static int load_dh_params(SSL_CTX *ctx, char *file)
124 if ((bio = BIO_new_file(file, "r")) == NULL) {
125 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
129 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
132 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters. DH cipher suites may not work!");
133 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
137 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
138 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
149 * Generate ephemeral RSA keys.
151 static int generate_eph_rsa_key(SSL_CTX *ctx)
155 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
157 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
158 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
168 * These functions don't do anything other than print debugging
171 * FIXME: Write sessions to some long-term storage, so that
172 * session resumption can still occur after the server
175 #define MAX_SESSION_SIZE (256)
177 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
180 char buffer[2 * MAX_SESSION_SIZE + 1];
182 size = sess->session_id_length;
183 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
185 fr_bin2hex(sess->session_id, buffer, size);
187 DEBUG2(" SSL: Removing session %s from the cache", buffer);
188 SSL_SESSION_free(sess);
193 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
196 char buffer[2 * MAX_SESSION_SIZE + 1];
198 size = sess->session_id_length;
199 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
201 fr_bin2hex(sess->session_id, buffer, size);
203 DEBUG2(" SSL: adding session %s to cache", buffer);
208 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
209 unsigned char *data, int len,
213 char buffer[2 * MAX_SESSION_SIZE + 1];
216 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
218 fr_bin2hex(data, buffer, size);
220 DEBUG2(" SSL: Client requested nonexistent cached session %s",
227 * For creating certificate attributes.
229 static const char *cert_attr_names[5][2] = {
230 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
231 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
232 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
233 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
234 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" }
237 #define EAPTLS_SERIAL (0)
238 #define EAPTLS_EXPIRATION (1)
239 #define EAPTLS_SUBJECT (2)
240 #define EAPTLS_ISSUER (3)
241 #define EAPTLS_CN (4)
244 * Before trusting a certificate, you must make sure that the
245 * certificate is 'valid'. There are several steps that your
246 * application can take in determining if a certificate is
247 * valid. Commonly used steps are:
249 * 1.Verifying the certificate's signature, and verifying that
250 * the certificate has been issued by a trusted Certificate
253 * 2.Verifying that the certificate is valid for the present date
254 * (i.e. it is being presented within its validity dates).
256 * 3.Verifying that the certificate has not been revoked by its
257 * issuing Certificate Authority, by checking with respect to a
258 * Certificate Revocation List (CRL).
260 * 4.Verifying that the credentials presented by the certificate
261 * fulfill additional requirements specific to the application,
262 * such as with respect to access control lists or with respect
263 * to OCSP (Online Certificate Status Processing).
265 * NOTE: This callback will be called multiple times based on the
266 * depth of the root certificate chain
268 static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
270 char subject[1024]; /* Used for the subject name */
271 char issuer[1024]; /* Used for the issuer name */
272 char common_name[1024];
275 EAP_HANDLER *handler = NULL;
278 int err, depth, lookup;
282 ASN1_INTEGER *sn = NULL;
283 ASN1_TIME *asn_time = NULL;
285 client_cert = X509_STORE_CTX_get_current_cert(ctx);
286 err = X509_STORE_CTX_get_error(ctx);
287 depth = X509_STORE_CTX_get_error_depth(ctx);
292 * Log client/issuing cert. If there's an error, log
295 if ((lookup > 1) && !my_ok) lookup = 1;
298 * Retrieve the pointer to the SSL of the connection currently treated
299 * and the application specific data stored into the SSL object.
301 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
302 handler = (EAP_HANDLER *)SSL_get_ex_data(ssl, 0);
303 request = handler->request;
304 conf = (EAP_TLS_CONF *)SSL_get_ex_data(ssl, 1);
307 * Get the Serial Number
310 sn = X509_get_serialNumber(client_cert);
313 * For this next bit, we create the attributes *only* if
314 * we're at the client or issuing certificate.
316 if ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {
320 for (i = 0; i < sn->length; i++) {
321 sprintf(p, "%02x", (unsigned int)sn->data[i]);
324 pairadd(&handler->certs,
325 pairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));
330 * Get the Expiration Date
333 asn_time = X509_get_notAfter(client_cert);
334 if ((lookup <= 1) && asn_time && (asn_time->length < MAX_STRING_LEN)) {
335 memcpy(buf, (char*) asn_time->data, asn_time->length);
336 buf[asn_time->length] = '\0';
337 pairadd(&handler->certs,
338 pairmake(cert_attr_names[EAPTLS_EXPIRATION][lookup], buf, T_OP_SET));
342 * Get the Subject & Issuer
344 subject[0] = issuer[0] = '\0';
345 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
347 subject[sizeof(subject) - 1] = '\0';
348 if ((lookup <= 1) && subject[0] && (strlen(subject) < MAX_STRING_LEN)) {
349 pairadd(&handler->certs,
350 pairmake(cert_attr_names[EAPTLS_SUBJECT][lookup], subject, T_OP_SET));
353 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
355 issuer[sizeof(issuer) - 1] = '\0';
356 if ((lookup <= 1) && issuer[0] && (strlen(issuer) < MAX_STRING_LEN)) {
357 pairadd(&handler->certs,
358 pairmake(cert_attr_names[EAPTLS_ISSUER][lookup], issuer, T_OP_SET));
362 * Get the Common Name
364 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
365 NID_commonName, common_name, sizeof(common_name));
366 common_name[sizeof(common_name) - 1] = '\0';
367 if ((lookup <= 1) && common_name[0] && (strlen(common_name) < MAX_STRING_LEN)) {
368 pairadd(&handler->certs,
369 pairmake(cert_attr_names[EAPTLS_CN][lookup], common_name, T_OP_SET));
373 const char *p = X509_verify_cert_error_string(err);
374 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
375 radius_pairmake(request, &request->packet->vps,
376 "Module-Failure-Message", p, T_OP_SET);
380 switch (ctx->error) {
382 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
383 radlog(L_ERR, "issuer= %s\n", issuer);
385 case X509_V_ERR_CERT_NOT_YET_VALID:
386 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
387 radlog(L_ERR, "notBefore=");
389 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
392 case X509_V_ERR_CERT_HAS_EXPIRED:
393 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
394 radlog(L_ERR, "notAfter=");
396 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
402 * If we're at the actual client cert, apply additional
407 * If the conf tells us to, check cert issuer
408 * against the specified value and fail
409 * verification if they don't match.
411 if (conf->check_cert_issuer &&
412 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
413 radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
418 * If the conf tells us to, check the CN in the
419 * cert against xlat'ed value, but only if the
420 * previous checks passed.
422 if (my_ok && conf->check_cert_cn) {
423 if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, handler->request, NULL)) {
424 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
425 conf->check_cert_cn);
426 /* if this fails, fail the verification */
429 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
430 if (strcmp(cn_str, common_name) != 0) {
431 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
435 } /* check_cert_cn */
437 while (conf->verify_client_cert_cmd) {
441 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
442 conf->verify_tmp_dir, progname);
443 if (mkstemp(filename) < 0) {
444 RDEBUG("Failed creating file in %s: %s",
445 conf->verify_tmp_dir, strerror(errno));
449 fp = fopen(filename, "w");
451 RDEBUG("Failed opening file %s: %s",
452 filename, strerror(errno));
456 if (!PEM_write_X509(fp, client_cert)) {
458 RDEBUG("Failed writing certificate to file");
463 if (!radius_pairmake(request, &request->packet->vps,
464 "TLS-Client-Cert-Filename",
465 filename, T_OP_SET)) {
466 RDEBUG("Failed creating TLS-Client-Cert-Filename");
471 RDEBUG("Verifying client certificate: %s",
472 conf->verify_client_cert_cmd);
473 if (radius_exec_program(conf->verify_client_cert_cmd,
475 request->packet->vps,
477 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
480 RDEBUG("Client certificate CN %s passed external validation", common_name);
491 if (debug_flag > 0) {
492 RDEBUG2("chain-depth=%d, ", depth);
493 RDEBUG2("error=%d", err);
495 RDEBUG2("--> User-Name = %s", handler->identity);
496 RDEBUG2("--> BUF-Name = %s", common_name);
497 RDEBUG2("--> subject = %s", subject);
498 RDEBUG2("--> issuer = %s", issuer);
499 RDEBUG2("--> verify return:%d", my_ok);
506 * Free cached session data, which is always a list of VALUE_PAIRs
508 static void eaptls_session_free(UNUSED void *parent, void *data_ptr,
509 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
510 UNUSED long argl, UNUSED void *argp)
512 VALUE_PAIR *vp = data_ptr;
513 if (!data_ptr) return;
520 * Create Global context SSL and use it in every new session
522 * - Load the trusted CAs
523 * - Load the Private key & the certificate
524 * - Set the Context options & Verify options
526 static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
530 X509_STORE *certstore;
531 int verify_mode = SSL_VERIFY_NONE;
536 * Add all the default ciphers and message digests
537 * Create our context.
540 SSL_load_error_strings();
543 * SHA256 is in all versions of OpenSSL, but isn't
544 * initialized by default. It's needed for WiMAX
547 #ifdef HAVE_OPENSSL_EVP_SHA256
548 EVP_add_digest(EVP_sha256());
551 meth = TLSv1_method();
552 ctx = SSL_CTX_new(meth);
555 * Identify the type of certificates that needs to be loaded
557 if (conf->file_type) {
558 type = SSL_FILETYPE_PEM;
560 type = SSL_FILETYPE_ASN1;
564 * Set the password to load private key
566 if (conf->private_key_password) {
569 * We don't want to put the private key password in eap.conf, so check
570 * for our special string which indicates we should get the password
573 const char* special_string = "Apple:UseCertAdmin";
574 if (strncmp(conf->private_key_password,
576 strlen(special_string)) == 0)
579 const long max_password_len = 128;
580 snprintf(cmd, sizeof(cmd) - 1,
581 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
582 conf->private_key_file);
584 DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
586 FILE* cmd_pipe = popen(cmd, "r");
588 radlog(L_ERR, "rlm_eap: %s command failed. Unable to get private_key_password", cmd);
589 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
593 free(conf->private_key_password);
594 conf->private_key_password = malloc(max_password_len * sizeof(char));
595 if (!conf->private_key_password) {
596 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
597 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
602 fgets(conf->private_key_password, max_password_len, cmd_pipe);
605 /* Get rid of newline at end of password. */
606 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
607 DEBUG2("rlm_eap: Password from command = \"%s\"", conf->private_key_password);
610 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
611 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
615 * Load our keys and certificates
617 * If certificates are of type PEM then we can make use
618 * of cert chain authentication using openssl api call
619 * SSL_CTX_use_certificate_chain_file. Please see how
620 * the cert chain needs to be given in PEM from
623 if (type == SSL_FILETYPE_PEM) {
624 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
625 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
626 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
630 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
631 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
632 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
636 /* Load the CAs we trust */
637 if (conf->ca_file || conf->ca_path) {
638 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
639 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
640 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
644 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
645 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
646 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
647 radlog(L_ERR, "rlm_eap_tls: Error reading private key file %s", conf->private_key_file);
652 * Check if the loaded private key is the right one
654 if (!SSL_CTX_check_private_key(ctx)) {
655 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
662 ctx_options |= SSL_OP_NO_SSLv2;
663 ctx_options |= SSL_OP_NO_SSLv3;
664 #ifdef SSL_OP_NO_TICKET
665 ctx_options |= SSL_OP_NO_TICKET ;
669 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
670 * small subgroup attacks and forward secrecy. Always
673 * SSL_OP_SINGLE_DH_USE has an impact on the computer
674 * time needed during negotiation, but it is not very
677 ctx_options |= SSL_OP_SINGLE_DH_USE;
680 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
681 * in Windows Vista client.
682 * http://www.openssl.org/~bodo/tls-cbc.txt
683 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
685 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
687 SSL_CTX_set_options(ctx, ctx_options);
690 * TODO: Set the RSA & DH
691 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
692 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
696 * set the message callback to identify the type of
697 * message. For every new session, there can be a
698 * different callback argument.
700 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
703 /* Set Info callback */
704 SSL_CTX_set_info_callback(ctx, cbtls_info);
707 * Callbacks, etc. for session resumption.
709 if (conf->session_cache_enable) {
710 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
711 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
712 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
714 SSL_CTX_set_quiet_shutdown(ctx, 1);
718 * Check the certificates for revocation.
720 #ifdef X509_V_FLAG_CRL_CHECK
721 if (conf->check_crl) {
722 certstore = SSL_CTX_get_cert_store(ctx);
723 if (certstore == NULL) {
724 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
725 radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
728 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
734 * Always verify the peer certificate
736 verify_mode |= SSL_VERIFY_PEER;
737 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
738 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
739 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
741 if (conf->verify_depth) {
742 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
745 /* Load randomness */
746 if (!(RAND_load_file(conf->random_file, 1024*1024))) {
747 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
748 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
753 * Set the cipher list if we were told to
755 if (conf->cipher_list) {
756 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
757 radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
763 * Setup session caching
765 if (conf->session_cache_enable) {
767 * Create a unique context Id per EAP-TLS configuration.
769 if (conf->session_id_name) {
770 snprintf(conf->session_context_id,
771 sizeof(conf->session_context_id),
772 "FreeRADIUS EAP-TLS %s",
773 conf->session_id_name);
775 snprintf(conf->session_context_id,
776 sizeof(conf->session_context_id),
777 "FreeRADIUS EAP-TLS %p", conf);
781 * Cache it, and DON'T auto-clear it.
783 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
785 SSL_CTX_set_session_id_context(ctx,
786 (unsigned char *) conf->session_context_id,
787 (unsigned int) strlen(conf->session_context_id));
790 * Our timeout is in hours, this is in seconds.
792 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
795 * Set the maximum number of entries in the
798 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
801 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
805 * Register the application indices. We can't use
806 * hard-coded "0" and "1" as before, because we need to
807 * set up a "free" handler for the cached session
810 if (eaptls_handle_idx < 0) {
811 eaptls_handle_idx = SSL_get_ex_new_index(0, "eaptls_handle_idx",
815 if (eaptls_conf_idx < 0) {
816 eaptls_conf_idx = SSL_get_ex_new_index(0, "eaptls_conf_idx",
820 if (eaptls_session_idx < 0) {
821 eaptls_session_idx = SSL_get_ex_new_index(0, "eaptls_session_idx",
823 eaptls_session_free);
831 * Detach the EAP-TLS module.
833 static int eaptls_detach(void *arg)
838 inst = (eap_tls_t *) arg;
842 memset(conf, 0, sizeof(*conf));
847 if (inst->ctx) SSL_CTX_free(inst->ctx);
857 * Attach the EAP-TLS module.
859 static int eaptls_attach(CONF_SECTION *cs, void **instance)
864 /* Store all these values in the data structure for later references */
865 inst = (eap_tls_t *)malloc(sizeof(*inst));
867 radlog(L_ERR, "rlm_eap_tls: out of memory");
870 memset(inst, 0, sizeof(*inst));
873 * Parse the config file & get all the configured values
875 conf = (EAP_TLS_CONF *)malloc(sizeof(*conf));
878 radlog(L_ERR, "rlm_eap_tls: out of memory");
881 memset(conf, 0, sizeof(*conf));
884 if (cf_section_parse(cs, conf, module_config) < 0) {
890 * The EAP RFC's say 1020, but we're less picky.
892 if (conf->fragment_size < 100) {
893 radlog(L_ERR, "rlm_eap_tls: Fragment size is too small.");
899 * The maximum size for a RADIUS packet is 4096,
900 * minus the header (20), Message-Authenticator (18),
901 * and State (18), etc. results in about 4000 bytes of data
902 * that can be devoted *solely* to EAP.
904 if (conf->fragment_size > 4000) {
905 radlog(L_ERR, "rlm_eap_tls: Fragment size is too large.");
911 * Account for the EAP header (4), and the EAP-TLS header
912 * (6), as per Section 4.2 of RFC 2716. What's left is
913 * the maximum amount of data we read from a TLS buffer.
915 conf->fragment_size -= 10;
918 * This magic makes the administrators life HUGELY easier
919 * on initial deployments.
921 * If the server starts up in debugging mode, AND the
922 * bootstrap command is configured, AND it exists, AND
923 * there is no server certificate
925 if (conf->make_cert_command && (debug_flag >= 2)) {
928 if ((stat(conf->make_cert_command, &buf) == 0) &&
929 (stat(conf->certificate_file, &buf) < 0) &&
931 (radius_exec_program(conf->make_cert_command, NULL, 1,
932 NULL, 0, NULL, NULL, 0) != 0)) {
942 inst->ctx = init_tls_ctx(conf);
943 if (inst->ctx == NULL) {
948 if (load_dh_params(inst->ctx, conf->dh_file) < 0) {
953 if (generate_eph_rsa_key(inst->ctx) < 0) {
958 if (conf->verify_tmp_dir) {
961 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
962 radlog(L_ERR, "rlm_eap_tls: Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
968 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
969 radlog(L_ERR, "rlm_eap_tls: You MUST set the verify directory in order to use verify_client_cmd");
981 * Send an initial eap-tls request to the peer.
983 * Frame eap reply packet.
984 * len = header + type + tls_typedata
985 * tls_typedata = flags(Start (S) bit set, and no data)
987 * Once having received the peer's Identity, the EAP server MUST
988 * respond with an EAP-TLS/Start packet, which is an
989 * EAP-Request packet with EAP-Type=EAP-TLS, the Start (S) bit
990 * set, and no data. The EAP-TLS conversation will then begin,
991 * with the peer sending an EAP-Response packet with
992 * EAP-Type = EAP-TLS. The data field of that packet will
995 * Fragment length is Framed-MTU - 4.
997 * http://mail.frascone.com/pipermail/public/eap/2003-July/001426.html
999 static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
1005 int client_cert = TRUE;
1006 int verify_mode = 0;
1007 REQUEST *request = handler->request;
1009 inst = (eap_tls_t *)type_arg;
1011 handler->tls = TRUE;
1012 handler->finished = FALSE;
1015 * Manually flush the sessions every so often. If HALF
1016 * of the session lifetime has passed since we last
1017 * flushed, then flush it again.
1019 * FIXME: Also do it every N sessions?
1021 if (inst->conf->session_cache_enable &&
1022 ((inst->conf->session_last_flushed + (inst->conf->session_timeout * 1800)) <= request->timestamp)) {
1023 RDEBUG2("Flushing SSL sessions (of #%ld)",
1024 SSL_CTX_sess_number(inst->ctx));
1026 SSL_CTX_flush_sessions(inst->ctx, request->timestamp);
1027 inst->conf->session_last_flushed = request->timestamp;
1031 * If we're TTLS or PEAP, then do NOT require a client
1034 * FIXME: This should be more configurable.
1036 if (handler->eap_type != PW_EAP_TLS) {
1037 vp = pairfind(handler->request->config_items,
1038 PW_EAP_TLS_REQUIRE_CLIENT_CERT, 0);
1040 client_cert = FALSE;
1042 client_cert = vp->vp_integer;
1047 * Every new session is started only from EAP-TLS-START.
1048 * Before Sending EAP-TLS-START, open a new SSL session.
1049 * Create all the required data structures & store them
1050 * in Opaque. So that we can use these data structures
1051 * when we get the response
1053 ssn = eaptls_new_session(inst->ctx, client_cert);
1059 * Verify the peer certificate, if asked.
1062 RDEBUG2("Requiring client certificate");
1063 verify_mode = SSL_VERIFY_PEER;
1064 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1065 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1067 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
1070 * Create a structure for all the items required to be
1071 * verified for each client and set that as opaque data
1074 * NOTE: If we want to set each item sepearately then
1075 * this index should be global.
1077 SSL_set_ex_data(ssn->ssl, 0, (void *)handler);
1078 SSL_set_ex_data(ssn->ssl, 1, (void *)inst->conf);
1080 ssn->length_flag = inst->conf->include_length;
1083 * We use default fragment size, unless the Framed-MTU
1084 * tells us it's too big. Note that we do NOT account
1085 * for the EAP-TLS headers if conf->fragment_size is
1086 * large, because that config item looks to be confusing.
1088 * i.e. it should REALLY be called MTU, and the code here
1089 * should figure out what that means for TLS fragment size.
1090 * asking the administrator to know the internal details
1091 * of EAP-TLS in order to calculate fragment sizes is
1094 ssn->offset = inst->conf->fragment_size;
1095 vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU, 0);
1096 if (vp && ((vp->vp_integer - 14) < ssn->offset)) {
1098 * Discount the Framed-MTU by:
1100 * 4 : EAP header (code + id + length)
1101 * 1 : EAP type == EAP-TLS
1103 * 4 : EAP-TLS Message length
1104 * (even if conf->include_length == 0,
1109 ssn->offset = vp->vp_integer - 14;
1112 handler->opaque = ((void *)ssn);
1113 handler->free_opaque = session_free;
1115 RDEBUG2("Initiate");
1118 * Set up type-specific information.
1120 switch (handler->eap_type) {
1123 ssn->prf_label = "client EAP encryption";
1127 ssn->prf_label = "ttls keying material";
1131 * PEAP-specific breakage.
1135 * As it is a poorly designed protocol, PEAP uses
1136 * bits in the TLS header to indicate PEAP
1137 * version numbers. For now, we only support
1138 * PEAP version 0, so it doesn't matter too much.
1139 * However, if we support later versions of PEAP,
1140 * we will need this flag to indicate which
1141 * version we're currently dealing with.
1143 ssn->peap_flag = 0x00;
1146 * PEAP version 0 requires 'include_length = no',
1147 * so rather than hoping the user figures it out,
1150 ssn->length_flag = 0;
1152 ssn->prf_label = "client EAP encryption";
1156 if (inst->conf->session_cache_enable) {
1157 ssn->allow_session_resumption = 1; /* otherwise it's zero */
1161 * TLS session initialization is over. Now handle TLS
1162 * related handshaking or application data.
1164 status = eaptls_start(handler->eap_ds, ssn->peap_flag);
1165 RDEBUG2("Start returned %d", status);
1170 * The next stage to process the packet.
1172 handler->stage = AUTHENTICATE;
1178 * Do authentication, by letting EAP-TLS do most of the work.
1180 static int eaptls_authenticate(void *arg, EAP_HANDLER *handler)
1182 eaptls_status_t status;
1183 tls_session_t *tls_session = (tls_session_t *) handler->opaque;
1184 REQUEST *request = handler->request;
1185 eap_tls_t *inst = (eap_tls_t *) arg;
1187 RDEBUG2("Authenticate");
1189 status = eaptls_process(handler);
1190 RDEBUG2("eaptls_process returned %d\n", status);
1193 * EAP-TLS handshake was successful, return an
1194 * EAP-TLS-Success packet here.
1196 case EAPTLS_SUCCESS:
1200 * The TLS code is still working on the TLS
1201 * exchange, and it's a valid TLS request.
1204 case EAPTLS_HANDLED:
1208 * Handshake is done, proceed with decoding tunneled
1212 RDEBUG2("Received unexpected tunneled data after successful handshake.");
1214 if ((debug_flag > 2) && fr_log_fp) {
1216 unsigned int data_len;
1217 unsigned char buffer[1024];
1219 data_len = (tls_session->record_minus)(&tls_session->dirty_in,
1220 buffer, sizeof(buffer));
1221 log_debug(" Tunneled data (%u bytes)\n", data_len);
1222 for (i = 0; i < data_len; i++) {
1223 if ((i & 0x0f) == 0x00) fprintf(fr_log_fp, " %x: ", i);
1224 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
1226 fprintf(fr_log_fp, "%02x ", buffer[i]);
1228 fprintf(fr_log_fp, "\n");
1232 eaptls_fail(handler, 0);
1237 * Anything else: fail.
1239 * Also, remove the session from the cache so that
1240 * the client can't re-use it.
1243 if (inst->conf->session_cache_enable) {
1244 SSL_CTX_remove_session(inst->ctx,
1245 tls_session->ssl->session);
1252 * New sessions cause some additional information to be
1255 if (!SSL_session_reused(tls_session->ssl)) {
1257 * FIXME: Store miscellaneous data.
1259 RDEBUG2("Adding user data to cached session");
1262 SSL_SESSION_set_ex_data(tls_session->ssl->session,
1263 ssl_session_idx_user_session, session_data);
1267 * FIXME: Retrieve miscellaneous data.
1270 data = SSL_SESSION_get_ex_data(tls_session->ssl->session,
1271 ssl_session_idx_user_session);
1273 if (!session_data) {
1274 radlog_request(L_ERR, 0, request,
1275 "No user session data in cached session - "
1281 RDEBUG2("Retrieved session data from cached session");
1285 * Success: Automatically return MPPE keys.
1287 return eaptls_success(handler, 0);
1291 * The module name should be the only globally exported symbol.
1292 * That is, everything else should be 'static'.
1294 EAP_TYPE rlm_eap_tls = {
1296 eaptls_attach, /* attach */
1297 eaptls_initiate, /* Start the initial request */
1298 NULL, /* authorization */
1299 eaptls_authenticate, /* authentication */
1300 eaptls_detach /* detach */