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 <openssl/x509.h>
41 #include "rlm_eap_tls.h"
44 #ifdef HAVE_SYS_STAT_H
48 #ifdef HAVE_OPENSSL_OCSP_H
49 #include <openssl/ocsp.h>
52 static CONF_PARSER cache_config[] = {
53 { "enable", PW_TYPE_BOOLEAN,
54 offsetof(EAP_TLS_CONF, session_cache_enable), NULL, "no" },
55 { "lifetime", PW_TYPE_INTEGER,
56 offsetof(EAP_TLS_CONF, session_timeout), NULL, "24" },
57 { "max_entries", PW_TYPE_INTEGER,
58 offsetof(EAP_TLS_CONF, session_cache_size), NULL, "255" },
59 { "name", PW_TYPE_STRING_PTR,
60 offsetof(EAP_TLS_CONF, session_id_name), NULL, NULL},
61 { NULL, -1, 0, NULL, NULL } /* end the list */
64 static CONF_PARSER verify_config[] = {
65 { "tmpdir", PW_TYPE_STRING_PTR,
66 offsetof(EAP_TLS_CONF, verify_tmp_dir), NULL, NULL},
67 { "client", PW_TYPE_STRING_PTR,
68 offsetof(EAP_TLS_CONF, verify_client_cert_cmd), NULL, NULL},
69 { NULL, -1, 0, NULL, NULL } /* end the list */
72 #ifdef HAVE_OPENSSL_OCSP_H
73 static CONF_PARSER ocsp_config[] = {
74 { "enable", PW_TYPE_BOOLEAN,
75 offsetof(EAP_TLS_CONF, ocsp_enable), NULL, "no"},
76 { "override_cert_url", PW_TYPE_BOOLEAN,
77 offsetof(EAP_TLS_CONF, ocsp_override_url), NULL, "no"},
78 { "url", PW_TYPE_STRING_PTR,
79 offsetof(EAP_TLS_CONF, ocsp_url), NULL, NULL },
80 { "use_nonce", PW_TYPE_BOOLEAN,
81 offsetof(EAP_TLS_CONF, ocsp_use_nonce), NULL, "yes"},
82 { "timeout", PW_TYPE_INTEGER,
83 offsetof(EAP_TLS_CONF, ocsp_timeout), NULL, "0" },
84 { "softfail", PW_TYPE_BOOLEAN,
85 offsetof(EAP_TLS_CONF, ocsp_softfail), NULL, "no"},
86 { NULL, -1, 0, NULL, NULL } /* end the list */
90 static CONF_PARSER module_config[] = {
91 { "rsa_key_exchange", PW_TYPE_BOOLEAN,
92 offsetof(EAP_TLS_CONF, rsa_key), NULL, "no" },
93 { "dh_key_exchange", PW_TYPE_BOOLEAN,
94 offsetof(EAP_TLS_CONF, dh_key), NULL, "yes" },
95 { "rsa_key_length", PW_TYPE_INTEGER,
96 offsetof(EAP_TLS_CONF, rsa_key_length), NULL, "512" },
97 { "dh_key_length", PW_TYPE_INTEGER,
98 offsetof(EAP_TLS_CONF, dh_key_length), NULL, "512" },
99 { "verify_depth", PW_TYPE_INTEGER,
100 offsetof(EAP_TLS_CONF, verify_depth), NULL, "0" },
101 { "CA_path", PW_TYPE_FILENAME,
102 offsetof(EAP_TLS_CONF, ca_path), NULL, NULL },
103 { "pem_file_type", PW_TYPE_BOOLEAN,
104 offsetof(EAP_TLS_CONF, file_type), NULL, "yes" },
105 { "private_key_file", PW_TYPE_FILENAME,
106 offsetof(EAP_TLS_CONF, private_key_file), NULL, NULL },
107 { "certificate_file", PW_TYPE_FILENAME,
108 offsetof(EAP_TLS_CONF, certificate_file), NULL, NULL },
109 { "CA_file", PW_TYPE_FILENAME,
110 offsetof(EAP_TLS_CONF, ca_file), NULL, NULL },
111 { "private_key_password", PW_TYPE_STRING_PTR,
112 offsetof(EAP_TLS_CONF, private_key_password), NULL, NULL },
113 { "dh_file", PW_TYPE_STRING_PTR,
114 offsetof(EAP_TLS_CONF, dh_file), NULL, NULL },
115 { "random_file", PW_TYPE_STRING_PTR,
116 offsetof(EAP_TLS_CONF, random_file), NULL, NULL },
117 { "fragment_size", PW_TYPE_INTEGER,
118 offsetof(EAP_TLS_CONF, fragment_size), NULL, "1024" },
119 { "include_length", PW_TYPE_BOOLEAN,
120 offsetof(EAP_TLS_CONF, include_length), NULL, "yes" },
121 { "check_crl", PW_TYPE_BOOLEAN,
122 offsetof(EAP_TLS_CONF, check_crl), NULL, "no"},
123 { "allow_expired_crl", PW_TYPE_BOOLEAN,
124 offsetof(EAP_TLS_CONF, allow_expired_crl), NULL, NULL},
125 { "check_cert_cn", PW_TYPE_STRING_PTR,
126 offsetof(EAP_TLS_CONF, check_cert_cn), NULL, NULL},
127 { "cipher_list", PW_TYPE_STRING_PTR,
128 offsetof(EAP_TLS_CONF, cipher_list), NULL, NULL},
129 { "check_cert_issuer", PW_TYPE_STRING_PTR,
130 offsetof(EAP_TLS_CONF, check_cert_issuer), NULL, NULL},
131 { "make_cert_command", PW_TYPE_STRING_PTR,
132 offsetof(EAP_TLS_CONF, make_cert_command), NULL, NULL},
133 { "virtual_server", PW_TYPE_STRING_PTR,
134 offsetof(EAP_TLS_CONF, virtual_server), NULL, NULL },
136 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
137 #ifndef OPENSSL_NO_ECDH
138 { "ecdh_curve", PW_TYPE_STRING_PTR,
139 offsetof(EAP_TLS_CONF, ecdh_curve), NULL, "prime256v1"},
143 #ifdef SSL_OP_NO_TLSv1_1
144 { "disable_tlsv1_1", PW_TYPE_BOOLEAN,
145 offsetof(EAP_TLS_CONF, disable_tlsv1_1), NULL, NULL },
149 * @fixme Disabled because using TLS1.2 seems to cause MPPE key issues with eapol_test
150 * need to fix FreeRADIUS or wpa_supplicant.
152 #ifdef SSL_OP_NO_TLSv1_2
153 { "disable_tlsv1_2", PW_TYPE_BOOLEAN,
154 offsetof(EAP_TLS_CONF, disable_tlsv1_2), NULL, "yes" },
157 { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
159 { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
161 #ifdef HAVE_OPENSSL_OCSP_H
162 { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
165 { NULL, -1, 0, NULL, NULL } /* end the list */
170 * TODO: Check for the type of key exchange * like conf->dh_key
172 static int load_dh_params(SSL_CTX *ctx, char *file)
177 if (!ctx || !file) return 0;
179 if ((bio = BIO_new_file(file, "r")) == NULL) {
180 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
184 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
187 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters. DH cipher suites may not work!");
188 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
192 if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
193 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
204 * Generate ephemeral RSA keys.
206 static int generate_eph_rsa_key(SSL_CTX *ctx)
210 if (!SSL_CTX_need_tmp_RSA(ctx)) return 0;
212 rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
214 if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
215 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
225 * FIXME: Write sessions to some long-term storage, so that
226 * session resumption can still occur after the server
229 #define MAX_SESSION_SIZE (256)
231 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
234 char buffer[2 * MAX_SESSION_SIZE + 1];
236 size = sess->session_id_length;
237 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
239 fr_bin2hex(sess->session_id, buffer, size);
241 DEBUG2(" SSL: Removing session %s from the cache", buffer);
242 SSL_SESSION_free(sess);
247 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
250 char buffer[2 * MAX_SESSION_SIZE + 1];
252 size = sess->session_id_length;
253 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
255 fr_bin2hex(sess->session_id, buffer, size);
257 DEBUG2(" SSL: adding session %s to cache", buffer);
262 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
263 unsigned char *data, int len,
267 char buffer[2 * MAX_SESSION_SIZE + 1];
270 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
272 fr_bin2hex(data, buffer, size);
274 DEBUG2(" SSL: Client requested nonexistent cached session %s",
280 #ifdef HAVE_OPENSSL_OCSP_H
282 * This function extracts the OCSP Responder URL
283 * from an existing x509 certificate.
285 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
286 char **ppath, int *pssl)
290 AUTHORITY_INFO_ACCESS *aia;
291 ACCESS_DESCRIPTION *ad;
293 aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
295 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
296 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
297 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
298 if (ad->location->type == GEN_URI) {
299 if(OCSP_parse_url(ad->location->d.ia5->data,
300 phost, pport, ppath, pssl))
309 * This function sends a OCSP request to a defined OCSP responder
310 * and checks the OCSP response for correctness.
313 /* Maximum leeway in validity period: default 5 minutes */
314 #define MAX_VALIDITY_PERIOD (5 * 60)
316 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
321 OCSP_RESPONSE *resp = NULL;
322 OCSP_BASICRESP *bresp = NULL;
327 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
331 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
333 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
341 * Create OCSP Request
343 certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
344 req = OCSP_REQUEST_new();
345 OCSP_request_add0_id(req, certid);
346 if(conf->ocsp_use_nonce){
347 OCSP_request_add1_nonce(req, NULL, 8);
351 * Send OCSP Request and get OCSP Response
354 /* Get OCSP responder URL */
355 if(conf->ocsp_override_url) {
356 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
359 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
362 if (!host || !port || !path) {
363 DEBUG2("[ocsp] - Host / port / path missing. Not doing OCSP.");
368 DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
370 /* Setup BIO socket to OCSP responder */
371 cbio = BIO_new_connect(host);
374 * Only print debugging information if we're in debugging
378 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
383 BIO_set_conn_port(cbio, port);
384 #if OPENSSL_VERSION_NUMBER < 0x1000003f
385 BIO_do_connect(cbio);
387 /* Send OCSP request and wait for response */
388 resp = OCSP_sendreq_bio(cbio, path, req);
390 radlog(L_ERR, "Error: Couldn't get OCSP response");
395 if (conf->ocsp_timeout)
396 BIO_set_nbio(cbio, 1);
398 rc = BIO_do_connect(cbio);
399 if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
400 radlog(L_ERR, "Error: Couldn't connect to OCSP responder");
405 ctx = OCSP_sendreq_new(cbio, path, req, -1);
407 radlog(L_ERR, "Error: Couldn't send OCSP request");
412 gettimeofday(&when, NULL);
413 when.tv_sec += conf->ocsp_timeout;
416 rc = OCSP_sendreq_nbio(&resp, ctx);
417 if (conf->ocsp_timeout) {
418 gettimeofday(&now, NULL);
419 if (!timercmp(&now, &when, <))
422 } while ((rc == -1) && BIO_should_retry(cbio));
424 if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
425 radlog(L_ERR, "Error: OCSP response timed out");
430 OCSP_REQ_CTX_free(ctx);
433 radlog(L_ERR, "Error: Couldn't get OCSP response");
439 /* Verify OCSP response status */
440 status = OCSP_response_status(resp);
441 DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
442 if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
443 radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status));
446 bresp = OCSP_response_get1_basic(resp);
447 if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
448 radlog(L_ERR, "Error: OCSP response has wrong nonce value");
451 if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
452 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
455 /* Verify OCSP cert status */
456 if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
457 &rev, &thisupd, &nextupd)) {
458 radlog(L_ERR, "ERROR: No Status found.\n");
462 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
464 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
465 ERR_print_errors(bio_out);
471 BIO_puts(bio_out, "\tThis Update: ");
472 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
473 BIO_puts(bio_out, "\n");
475 BIO_puts(bio_out, "\tNext Update: ");
476 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
477 BIO_puts(bio_out, "\n");
482 case V_OCSP_CERTSTATUS_GOOD:
483 DEBUG2("[oscp] --> Cert status: good");
488 /* REVOKED / UNKNOWN */
489 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
491 DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
494 BIO_puts(bio_out, "\tRevocation Time: ");
495 ASN1_GENERALIZEDTIME_print(bio_out, rev);
496 BIO_puts(bio_out, "\n");
502 /* Free OCSP Stuff */
503 OCSP_REQUEST_free(req);
504 OCSP_RESPONSE_free(resp);
509 if (bio_out) BIO_free(bio_out);
510 OCSP_BASICRESP_free(bresp);
515 DEBUG2("[ocsp] --> Certificate is valid!");
518 if (conf->ocsp_softfail) {
519 DEBUG2("[ocsp] --> Unable to check certificate; assuming valid.");
520 DEBUG2("[ocsp] --> Warning! This may be insecure.");
523 DEBUG2("[ocsp] --> Unable to check certificate; failing!");
528 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
534 #endif /* HAVE_OPENSSL_OCSP_H */
537 * For creating certificate attributes.
539 static const char *cert_attr_names[6][2] = {
540 { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
541 { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
542 { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
543 { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
544 { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
545 { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" }
548 #define EAPTLS_SERIAL (0)
549 #define EAPTLS_EXPIRATION (1)
550 #define EAPTLS_SUBJECT (2)
551 #define EAPTLS_ISSUER (3)
552 #define EAPTLS_CN (4)
553 #define EAPTLS_SAN_EMAIL (5)
556 * Before trusting a certificate, you must make sure that the
557 * certificate is 'valid'. There are several steps that your
558 * application can take in determining if a certificate is
559 * valid. Commonly used steps are:
561 * 1.Verifying the certificate's signature, and verifying that
562 * the certificate has been issued by a trusted Certificate
565 * 2.Verifying that the certificate is valid for the present date
566 * (i.e. it is being presented within its validity dates).
568 * 3.Verifying that the certificate has not been revoked by its
569 * issuing Certificate Authority, by checking with respect to a
570 * Certificate Revocation List (CRL).
572 * 4.Verifying that the credentials presented by the certificate
573 * fulfill additional requirements specific to the application,
574 * such as with respect to access control lists or with respect
575 * to OCSP (Online Certificate Status Processing).
577 * NOTE: This callback will be called multiple times based on the
578 * depth of the root certificate chain
580 static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
582 char subject[1024]; /* Used for the subject name */
583 char issuer[1024]; /* Used for the issuer name */
584 char attribute[1024];
586 char common_name[1024];
589 EAP_HANDLER *handler = NULL;
591 X509_CINF *client_inf;
592 STACK_OF(X509_EXTENSION) *ext_list;
595 int err, depth, lookup, loc;
599 ASN1_INTEGER *sn = NULL;
600 ASN1_TIME *asn_time = NULL;
601 #ifdef HAVE_OPENSSL_OCSP_H
602 X509_STORE *ocsp_store = NULL;
605 client_cert = X509_STORE_CTX_get_current_cert(ctx);
606 err = X509_STORE_CTX_get_error(ctx);
607 depth = X509_STORE_CTX_get_error_depth(ctx);
612 * Log client/issuing cert. If there's an error, log
615 if ((lookup > 1) && !my_ok) lookup = 1;
618 * Retrieve the pointer to the SSL of the connection currently treated
619 * and the application specific data stored into the SSL object.
621 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
622 handler = (EAP_HANDLER *)SSL_get_ex_data(ssl, 0);
623 request = handler->request;
624 conf = (EAP_TLS_CONF *)SSL_get_ex_data(ssl, 1);
625 #ifdef HAVE_OPENSSL_OCSP_H
626 ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, 2);
631 * Get the Serial Number
634 sn = X509_get_serialNumber(client_cert);
637 * For this next bit, we create the attributes *only* if
638 * we're at the client or issuing certificate.
640 if ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {
644 for (i = 0; i < sn->length; i++) {
645 sprintf(p, "%02x", (unsigned int)sn->data[i]);
648 pairadd(&handler->certs,
649 pairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));
654 * Get the Expiration Date
657 asn_time = X509_get_notAfter(client_cert);
658 if ((lookup <= 1) && asn_time && (asn_time->length < sizeof(buf))) {
659 memcpy(buf, (char*) asn_time->data, asn_time->length);
660 buf[asn_time->length] = '\0';
661 pairadd(&handler->certs,
662 pairmake(cert_attr_names[EAPTLS_EXPIRATION][lookup], buf, T_OP_SET));
666 * Get the Subject & Issuer
668 subject[0] = issuer[0] = '\0';
669 X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
671 subject[sizeof(subject) - 1] = '\0';
672 if ((lookup <= 1) && subject[0] && (strlen(subject) < MAX_STRING_LEN)) {
673 pairadd(&handler->certs,
674 pairmake(cert_attr_names[EAPTLS_SUBJECT][lookup], subject, T_OP_SET));
677 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
679 issuer[sizeof(issuer) - 1] = '\0';
680 if ((lookup <= 1) && issuer[0] && (strlen(issuer) < MAX_STRING_LEN)) {
681 pairadd(&handler->certs,
682 pairmake(cert_attr_names[EAPTLS_ISSUER][lookup], issuer, T_OP_SET));
686 * Get the Common Name, if there is a subject.
688 X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
689 NID_commonName, common_name, sizeof(common_name));
690 common_name[sizeof(common_name) - 1] = '\0';
691 if ((lookup <= 1) && common_name[0] && subject[0] && (strlen(common_name) < MAX_STRING_LEN)) {
692 pairadd(&handler->certs,
693 pairmake(cert_attr_names[EAPTLS_CN][lookup], common_name, T_OP_SET));
698 * Get the RFC822 Subject Alternative Name
700 loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
701 if (lookup <= 1 && loc >= 0) {
702 X509_EXTENSION *ext = NULL;
703 GENERAL_NAMES *names = NULL;
706 if ((ext = X509_get_ext(client_cert, loc)) &&
707 (names = X509V3_EXT_d2i(ext))) {
708 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
709 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
711 switch (name->type) {
713 if (ASN1_STRING_length(name->d.rfc822Name) >= MAX_STRING_LEN)
716 pairadd(&handler->certs,
717 pairmake(cert_attr_names[EAPTLS_SAN_EMAIL][lookup],
718 (char *)ASN1_STRING_data(name->d.rfc822Name), T_OP_SET));
721 /* XXX TODO handle other SAN types */
727 sk_GENERAL_NAME_free(names);
729 #endif /* GEN_EMAIL */
732 * If the CRL has expired, that might still be OK.
735 (conf->allow_expired_crl) &&
736 (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
738 X509_STORE_CTX_set_error( ctx, 0 );
742 const char *p = X509_verify_cert_error_string(err);
743 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
744 radius_pairmake(request, &request->packet->vps,
745 "Module-Failure-Message", p, T_OP_SET);
750 client_inf = client_cert->cert_info;
751 ext_list = client_inf->extensions;
757 * Grab the X509 extensions, and create attributes out of them.
758 * For laziness, we re-use the OpenSSL names
760 if (sk_X509_EXTENSION_num(ext_list) > 0) {
765 out = BIO_new(BIO_s_mem());
766 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
768 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
773 ext = sk_X509_EXTENSION_value(ext_list, i);
775 obj = X509_EXTENSION_get_object(ext);
776 i2a_ASN1_OBJECT(out, obj);
777 len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
778 if (len <= 0) continue;
780 attribute[16 + len] = '\0';
782 X509V3_EXT_print(out, ext, 0, 0);
783 len = BIO_read(out, value, sizeof(value) - 1);
784 if (len <= 0) continue;
789 * Mash the OpenSSL name to our name, and
790 * create the attribute.
792 for (p = attribute + 16; *p != '\0'; p++) {
793 if (*p == ' ') *p = '-';
796 vp = pairmake(attribute, value, T_OP_ADD);
798 pairadd(&handler->certs, vp);
806 switch (ctx->error) {
808 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
809 radlog(L_ERR, "issuer= %s\n", issuer);
811 case X509_V_ERR_CERT_NOT_YET_VALID:
812 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
813 radlog(L_ERR, "notBefore=");
815 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
818 case X509_V_ERR_CERT_HAS_EXPIRED:
819 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
820 radlog(L_ERR, "notAfter=");
822 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
828 * If we're at the actual client cert, apply additional
833 * If the conf tells us to, check cert issuer
834 * against the specified value and fail
835 * verification if they don't match.
837 if (conf->check_cert_issuer &&
838 (strcmp(issuer, conf->check_cert_issuer) != 0)) {
839 radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
844 * If the conf tells us to, check the CN in the
845 * cert against xlat'ed value, but only if the
846 * previous checks passed.
848 if (my_ok && conf->check_cert_cn) {
849 if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, handler->request, NULL)) {
850 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
851 conf->check_cert_cn);
852 /* if this fails, fail the verification */
855 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
856 if (strcmp(cn_str, common_name) != 0) {
857 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
861 } /* check_cert_cn */
863 #ifdef HAVE_OPENSSL_OCSP_H
864 if (my_ok && conf->ocsp_enable){
865 RDEBUG2("--> Starting OCSP Request");
866 if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
867 radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
869 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
874 while (conf->verify_client_cert_cmd) {
879 snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
880 conf->verify_tmp_dir, progname);
881 fd = mkstemp(filename);
883 RDEBUG("Failed creating file in %s: %s",
884 conf->verify_tmp_dir, strerror(errno));
888 fp = fdopen(fd, "w");
890 RDEBUG("Failed opening file %s: %s",
891 filename, strerror(errno));
895 if (!PEM_write_X509(fp, client_cert)) {
897 RDEBUG("Failed writing certificate to file");
902 if (!radius_pairmake(request, &request->packet->vps,
903 "TLS-Client-Cert-Filename",
904 filename, T_OP_SET)) {
905 RDEBUG("Failed creating TLS-Client-Cert-Filename");
910 RDEBUG("Verifying client certificate: %s",
911 conf->verify_client_cert_cmd);
912 if (radius_exec_program(conf->verify_client_cert_cmd,
915 request->packet->vps,
917 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
920 RDEBUG("Client certificate CN %s passed external validation", common_name);
931 if (debug_flag > 0) {
932 RDEBUG2("chain-depth=%d, ", depth);
933 RDEBUG2("error=%d", err);
935 RDEBUG2("--> User-Name = %s", handler->identity);
936 RDEBUG2("--> BUF-Name = %s", common_name);
937 RDEBUG2("--> subject = %s", subject);
938 RDEBUG2("--> issuer = %s", issuer);
939 RDEBUG2("--> verify return:%d", my_ok);
946 * Free cached session data, which is always a list of VALUE_PAIRs
948 static void eaptls_session_free(UNUSED void *parent, void *data_ptr,
949 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
950 UNUSED long argl, UNUSED void *argp)
952 VALUE_PAIR *vp = data_ptr;
953 if (!data_ptr) return;
958 #ifdef HAVE_OPENSSL_OCSP_H
960 * Create Global X509 revocation store and use it to verify
963 * - Load the trusted CAs
964 * - Load the trusted issuer certificates
966 static X509_STORE *init_revocation_store(EAP_TLS_CONF *conf)
968 X509_STORE *store = NULL;
970 store = X509_STORE_new();
972 /* Load the CAs we trust */
973 if (conf->ca_file || conf->ca_path)
974 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
975 radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
976 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
980 #ifdef X509_V_FLAG_CRL_CHECK
982 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
986 #endif /* HAVE_OPENSSL_OCSP_H */
988 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
989 #ifndef OPENSSL_NO_ECDH
990 static int set_ecdh_curve(SSL_CTX *ctx, const char *ecdh_curve)
995 if (!ecdh_curve || !*ecdh_curve) return 0;
997 nid = OBJ_sn2nid(ecdh_curve);
999 radlog(L_ERR, "Unknown ecdh_curve \"%s\"", ecdh_curve);
1003 ecdh = EC_KEY_new_by_curve_name(nid);
1005 radlog(L_ERR, "Unable to create new curve \"%s\"", ecdh_curve);
1009 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1011 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1021 * Create Global context SSL and use it in every new session
1023 * - Load the trusted CAs
1024 * - Load the Private key & the certificate
1025 * - Set the Context options & Verify options
1027 static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
1031 X509_STORE *certstore;
1032 int verify_mode = SSL_VERIFY_NONE;
1033 int ctx_options = 0;
1038 * http://old.nabble.com/Backward-compatibility-of-private-key-files--td27937046.html
1040 OpenSSL_add_all_algorithms();
1043 * SHA256 is in all versions of OpenSSL, but isn't
1044 * initialized by default. It's needed for WiMAX
1047 #ifdef HAVE_OPENSSL_EVP_SHA256
1048 EVP_add_digest(EVP_sha256());
1051 meth = SSLv23_method(); /* which is really "all known SSL / TLS methods". Idiots. */
1052 ctx = SSL_CTX_new(meth);
1055 * Identify the type of certificates that needs to be loaded
1057 if (conf->file_type) {
1058 type = SSL_FILETYPE_PEM;
1060 type = SSL_FILETYPE_ASN1;
1064 * Set the password to load private key
1066 if (conf->private_key_password) {
1069 * We don't want to put the private key password in eap.conf, so check
1070 * for our special string which indicates we should get the password
1073 const char* special_string = "Apple:UseCertAdmin";
1074 if (strncmp(conf->private_key_password,
1076 strlen(special_string)) == 0)
1079 const long max_password_len = 128;
1080 snprintf(cmd, sizeof(cmd) - 1,
1081 "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
1082 conf->private_key_file);
1084 DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
1086 FILE* cmd_pipe = popen(cmd, "r");
1088 radlog(L_ERR, "rlm_eap: %s command failed. Unable to get private_key_password", cmd);
1089 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1093 free(conf->private_key_password);
1094 conf->private_key_password = malloc(max_password_len * sizeof(char));
1095 if (!conf->private_key_password) {
1096 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
1097 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1102 fgets(conf->private_key_password, max_password_len, cmd_pipe);
1105 /* Get rid of newline at end of password. */
1106 conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
1107 DEBUG2("rlm_eap: Password from command = \"%s\"", conf->private_key_password);
1110 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
1111 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
1115 * Load our keys and certificates
1117 * If certificates are of type PEM then we can make use
1118 * of cert chain authentication using openssl api call
1119 * SSL_CTX_use_certificate_chain_file. Please see how
1120 * the cert chain needs to be given in PEM from
1123 if (type == SSL_FILETYPE_PEM) {
1124 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
1125 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1126 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
1130 } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
1131 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1132 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
1136 /* Load the CAs we trust */
1137 if (conf->ca_file || conf->ca_path) {
1138 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
1139 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1140 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1144 if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
1145 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
1146 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1147 radlog(L_ERR, "rlm_eap_tls: Error reading private key file %s", conf->private_key_file);
1152 * Check if the loaded private key is the right one
1154 if (!SSL_CTX_check_private_key(ctx)) {
1155 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
1162 ctx_options |= SSL_OP_NO_SSLv2;
1163 ctx_options |= SSL_OP_NO_SSLv3;
1165 #ifdef SSL_OP_NO_TLSv1_1
1166 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
1168 #ifdef SSL_OP_NO_TLSv1_2
1169 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
1172 #ifdef SSL_OP_NO_TICKET
1173 ctx_options |= SSL_OP_NO_TICKET;
1177 * SSL_OP_SINGLE_DH_USE must be used in order to prevent
1178 * small subgroup attacks and forward secrecy. Always
1181 * SSL_OP_SINGLE_DH_USE has an impact on the computer
1182 * time needed during negotiation, but it is not very
1185 ctx_options |= SSL_OP_SINGLE_DH_USE;
1188 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
1189 * in Windows Vista client.
1190 * http://www.openssl.org/~bodo/tls-cbc.txt
1191 * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
1193 ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1195 SSL_CTX_set_options(ctx, ctx_options);
1198 * TODO: Set the RSA & DH
1199 * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
1200 * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
1204 * Set eliptical curve crypto configuration.
1206 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1207 #ifndef OPENSSL_NO_ECDH
1208 if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
1215 * set the message callback to identify the type of
1216 * message. For every new session, there can be a
1217 * different callback argument.
1219 * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
1222 /* Set Info callback */
1223 SSL_CTX_set_info_callback(ctx, cbtls_info);
1226 * Callbacks, etc. for session resumption.
1228 if (conf->session_cache_enable) {
1229 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
1230 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
1231 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
1233 SSL_CTX_set_quiet_shutdown(ctx, 1);
1237 * Check the certificates for revocation.
1239 #ifdef X509_V_FLAG_CRL_CHECK
1240 if (conf->check_crl) {
1241 certstore = SSL_CTX_get_cert_store(ctx);
1242 if (certstore == NULL) {
1243 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1244 radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
1247 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
1253 * Always verify the peer certificate
1255 verify_mode |= SSL_VERIFY_PEER;
1256 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1257 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1258 SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
1260 if (conf->verify_depth) {
1261 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
1264 /* Load randomness */
1265 if (conf->random_file) {
1266 if (!(RAND_load_file(conf->random_file, 1024*1024))) {
1267 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1268 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
1274 * Set the cipher list if we were told to
1276 if (conf->cipher_list) {
1277 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
1278 radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
1284 * Setup session caching
1286 if (conf->session_cache_enable) {
1288 * Create a unique context Id per EAP-TLS configuration.
1290 if (conf->session_id_name) {
1291 snprintf(conf->session_context_id,
1292 sizeof(conf->session_context_id),
1294 conf->session_id_name);
1296 snprintf(conf->session_context_id,
1297 sizeof(conf->session_context_id),
1302 * Cache it, and DON'T auto-clear it.
1304 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
1306 SSL_CTX_set_session_id_context(ctx,
1307 (unsigned char *) conf->session_context_id,
1308 (unsigned int) strlen(conf->session_context_id));
1311 * Our timeout is in hours, this is in seconds.
1313 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
1316 * Set the maximum number of entries in the
1319 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
1322 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1326 * Register the application indices. We can't use
1327 * hard-coded "0" and "1" as before, because we need to
1328 * set up a "free" handler for the cached session
1331 if (eaptls_handle_idx < 0) {
1332 eaptls_handle_idx = SSL_get_ex_new_index(0, "eaptls_handle_idx",
1336 if (eaptls_conf_idx < 0) {
1337 eaptls_conf_idx = SSL_get_ex_new_index(0, "eaptls_conf_idx",
1341 if (eaptls_store_idx < 0) {
1342 eaptls_store_idx = SSL_get_ex_new_index(0, "eaptls_store_idx",
1346 if (eaptls_session_idx < 0) {
1347 eaptls_session_idx = SSL_SESSION_get_ex_new_index(0, "eaptls_session_idx",
1349 eaptls_session_free);
1357 * Detach the EAP-TLS module.
1359 static int eaptls_detach(void *arg)
1364 inst = (eap_tls_t *) arg;
1365 conf = &(inst->conf);
1367 if (inst->ctx) SSL_CTX_free(inst->ctx);
1370 #ifdef HAVE_OPENSSL_OCSP_H
1371 if (inst->store) X509_STORE_free(inst->store);
1382 * Attach the EAP-TLS module.
1384 static int eaptls_attach(CONF_SECTION *cs, void **instance)
1389 /* Store all these values in the data structure for later references */
1390 inst = (eap_tls_t *)malloc(sizeof(*inst));
1392 radlog(L_ERR, "rlm_eap_tls: out of memory");
1395 memset(inst, 0, sizeof(*inst));
1396 conf = &(inst->conf);
1399 * Hack: conf is the first structure inside of inst. The
1400 * CONF_PARSER stuff above uses offsetof() and
1401 * EAP_TLS_CONF, which is technically wrong.
1403 if (cf_section_parse(cs, inst, module_config) < 0) {
1404 eaptls_detach(inst);
1409 * The EAP RFC's say 1020, but we're less picky.
1411 if (conf->fragment_size < 100) {
1412 radlog(L_ERR, "rlm_eap_tls: Fragment size is too small.");
1413 eaptls_detach(inst);
1418 * The maximum size for a RADIUS packet is 4096,
1419 * minus the header (20), Message-Authenticator (18),
1420 * and State (18), etc. results in about 4000 bytes of data
1421 * that can be devoted *solely* to EAP.
1423 if (conf->fragment_size > 4000) {
1424 radlog(L_ERR, "rlm_eap_tls: Fragment size is too large.");
1425 eaptls_detach(inst);
1430 * Account for the EAP header (4), and the EAP-TLS header
1431 * (6), as per Section 4.2 of RFC 2716. What's left is
1432 * the maximum amount of data we read from a TLS buffer.
1434 conf->fragment_size -= 10;
1437 * This magic makes the administrators life HUGELY easier
1438 * on initial deployments.
1440 * If the server starts up in debugging mode, AND the
1441 * bootstrap command is configured, AND it exists, AND
1442 * there is no server certificate
1444 if (conf->make_cert_command && (debug_flag >= 2)) {
1447 if ((stat(conf->make_cert_command, &buf) == 0) &&
1448 (stat(conf->certificate_file, &buf) < 0) &&
1449 (errno == ENOENT) &&
1450 (radius_exec_program(conf->make_cert_command, NULL, 1,
1451 NULL, 0, EXEC_TIMEOUT,
1452 NULL, NULL, 0) != 0)) {
1453 eaptls_detach(inst);
1462 inst->ctx = init_tls_ctx(conf);
1463 if (inst->ctx == NULL) {
1464 eaptls_detach(inst);
1468 #ifdef HAVE_OPENSSL_OCSP_H
1470 * Initialize OCSP Revocation Store
1472 if (conf->ocsp_enable) {
1473 inst->store = init_revocation_store(conf);
1474 if (inst->store == NULL) {
1475 eaptls_detach(inst);
1479 #endif /*HAVE_OPENSSL_OCSP_H*/
1481 if (load_dh_params(inst->ctx, conf->dh_file) < 0) {
1482 eaptls_detach(inst);
1486 if (generate_eph_rsa_key(inst->ctx) < 0) {
1487 eaptls_detach(inst);
1491 if (conf->verify_tmp_dir) {
1492 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
1493 radlog(L_ERR, "rlm_eap_tls: Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
1494 eaptls_detach(inst);
1499 if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
1500 radlog(L_ERR, "rlm_eap_tls: You MUST set the verify directory in order to use verify_client_cmd");
1501 eaptls_detach(inst);
1512 * Send an initial eap-tls request to the peer.
1514 * Frame eap reply packet.
1515 * len = header + type + tls_typedata
1516 * tls_typedata = flags(Start (S) bit set, and no data)
1518 * Once having received the peer's Identity, the EAP server MUST
1519 * respond with an EAP-TLS/Start packet, which is an
1520 * EAP-Request packet with EAP-Type=EAP-TLS, the Start (S) bit
1521 * set, and no data. The EAP-TLS conversation will then begin,
1522 * with the peer sending an EAP-Response packet with
1523 * EAP-Type = EAP-TLS. The data field of that packet will
1526 * Fragment length is Framed-MTU - 4.
1528 * http://mail.frascone.com/pipermail/public/eap/2003-July/001426.html
1530 static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
1536 int client_cert = TRUE;
1537 int verify_mode = 0;
1538 REQUEST *request = handler->request;
1540 inst = (eap_tls_t *)type_arg;
1542 handler->tls = TRUE;
1543 handler->finished = FALSE;
1546 * Manually flush the sessions every so often. If HALF
1547 * of the session lifetime has passed since we last
1548 * flushed, then flush it again.
1550 * FIXME: Also do it every N sessions?
1552 if (inst->conf.session_cache_enable &&
1553 ((inst->conf.session_last_flushed + (inst->conf.session_timeout * 1800)) <= request->timestamp)) {
1554 RDEBUG2("Flushing SSL sessions (of #%ld)",
1555 SSL_CTX_sess_number(inst->ctx));
1557 SSL_CTX_flush_sessions(inst->ctx, request->timestamp);
1558 inst->conf.session_last_flushed = request->timestamp;
1562 * If we're TTLS or PEAP, then do NOT require a client
1565 * FIXME: This should be more configurable.
1567 if (handler->eap_type != PW_EAP_TLS) {
1568 vp = pairfind(handler->request->config_items,
1569 PW_EAP_TLS_REQUIRE_CLIENT_CERT);
1571 client_cert = FALSE;
1573 client_cert = vp->vp_integer;
1578 * Every new session is started only from EAP-TLS-START.
1579 * Before Sending EAP-TLS-START, open a new SSL session.
1580 * Create all the required data structures & store them
1581 * in Opaque. So that we can use these data structures
1582 * when we get the response
1584 ssn = eaptls_new_session(inst->ctx, client_cert);
1590 * Verify the peer certificate, if asked.
1593 RDEBUG2("Requiring client certificate");
1594 verify_mode = SSL_VERIFY_PEER;
1595 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1596 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1598 SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
1601 * Create a structure for all the items required to be
1602 * verified for each client and set that as opaque data
1605 * NOTE: If we want to set each item sepearately then
1606 * this index should be global.
1608 SSL_set_ex_data(ssn->ssl, 0, (void *)handler);
1609 SSL_set_ex_data(ssn->ssl, 1, (void *)&(inst->conf));
1610 #ifdef HAVE_OPENSSL_OCSP_H
1611 SSL_set_ex_data(ssn->ssl, 2, (void *)inst->store);
1614 ssn->length_flag = inst->conf.include_length;
1617 * We use default fragment size, unless the Framed-MTU
1618 * tells us it's too big. Note that we do NOT account
1619 * for the EAP-TLS headers if conf->fragment_size is
1620 * large, because that config item looks to be confusing.
1622 * i.e. it should REALLY be called MTU, and the code here
1623 * should figure out what that means for TLS fragment size.
1624 * asking the administrator to know the internal details
1625 * of EAP-TLS in order to calculate fragment sizes is
1628 ssn->offset = inst->conf.fragment_size;
1629 vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU);
1630 if (vp && ((vp->vp_integer - 14) < ssn->offset)) {
1632 * Discount the Framed-MTU by:
1634 * 4 : EAP header (code + id + length)
1635 * 1 : EAP type == EAP-TLS
1637 * 4 : EAP-TLS Message length
1638 * (even if conf->include_length == 0,
1643 ssn->offset = vp->vp_integer - 14;
1646 handler->opaque = ((void *)ssn);
1647 handler->free_opaque = session_free;
1649 RDEBUG2("Initiate");
1652 * Set up type-specific information.
1654 switch (handler->eap_type) {
1657 ssn->prf_label = "client EAP encryption";
1661 ssn->prf_label = "ttls keying material";
1665 * PEAP-specific breakage.
1669 * As it is a poorly designed protocol, PEAP uses
1670 * bits in the TLS header to indicate PEAP
1671 * version numbers. For now, we only support
1672 * PEAP version 0, so it doesn't matter too much.
1673 * However, if we support later versions of PEAP,
1674 * we will need this flag to indicate which
1675 * version we're currently dealing with.
1677 ssn->peap_flag = 0x00;
1680 * PEAP version 0 requires 'include_length = no',
1681 * so rather than hoping the user figures it out,
1684 ssn->length_flag = 0;
1686 ssn->prf_label = "client EAP encryption";
1690 if (inst->conf.session_cache_enable) {
1691 ssn->allow_session_resumption = 1; /* otherwise it's zero */
1695 * TLS session initialization is over. Now handle TLS
1696 * related handshaking or application data.
1698 status = eaptls_start(handler->eap_ds, ssn->peap_flag);
1699 RDEBUG2("Start returned %d", status);
1704 * The next stage to process the packet.
1706 handler->stage = AUTHENTICATE;
1712 * Do authentication, by letting EAP-TLS do most of the work.
1714 static int eaptls_authenticate(void *arg, EAP_HANDLER *handler)
1716 eaptls_status_t status;
1717 tls_session_t *tls_session = (tls_session_t *) handler->opaque;
1718 REQUEST *request = handler->request;
1719 eap_tls_t *inst = (eap_tls_t *) arg;
1721 RDEBUG2("Authenticate");
1723 status = eaptls_process(handler);
1724 RDEBUG2("eaptls_process returned %d\n", status);
1727 * EAP-TLS handshake was successful, return an
1728 * EAP-TLS-Success packet here.
1730 case EAPTLS_SUCCESS:
1731 if (inst->conf.virtual_server) {
1735 /* create a fake request */
1736 fake = request_alloc_fake(request);
1737 rad_assert(fake->packet->vps == NULL);
1739 fake->packet->vps = paircopy(request->packet->vps);
1741 /* set the virtual server to use */
1742 if ((vp = pairfind(request->config_items,
1743 PW_VIRTUAL_SERVER)) != NULL) {
1744 fake->server = vp->vp_strvalue;
1746 fake->server = inst->conf.virtual_server;
1749 RDEBUG("Processing EAP-TLS Certificate check:");
1750 debug_pair_list(fake->packet->vps);
1752 RDEBUG("server %s {", fake->server);
1754 rad_virtual_server(fake);
1756 RDEBUG("} # server %s", fake->server);
1758 /* copy the reply vps back to our reply */
1759 pairadd(&request->reply->vps, fake->reply->vps);
1760 fake->reply->vps = NULL;
1762 /* reject if virtual server didn't return accept */
1763 if (fake->reply->code != PW_AUTHENTICATION_ACK) {
1764 RDEBUG2("Certifictes were rejected by the virtual server");
1765 request_free(&fake);
1766 eaptls_fail(handler, 0);
1770 request_free(&fake);
1776 * The TLS code is still working on the TLS
1777 * exchange, and it's a valid TLS request.
1780 case EAPTLS_HANDLED:
1784 * Handshake is done, proceed with decoding tunneled
1788 RDEBUG2("Received unexpected tunneled data after successful handshake.");
1790 if ((debug_flag > 2) && fr_log_fp) {
1792 unsigned int data_len;
1793 unsigned char buffer[1024];
1795 data_len = (tls_session->record_minus)(&tls_session->dirty_in,
1796 buffer, sizeof(buffer));
1797 log_debug(" Tunneled data (%u bytes)\n", data_len);
1798 for (i = 0; i < data_len; i++) {
1799 if ((i & 0x0f) == 0x00) fprintf(fr_log_fp, " %x: ", i);
1800 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
1802 fprintf(fr_log_fp, "%02x ", buffer[i]);
1804 fprintf(fr_log_fp, "\n");
1808 eaptls_fail(handler, 0);
1813 * Anything else: fail.
1815 * Also, remove the session from the cache so that
1816 * the client can't re-use it.
1819 if (inst->conf.session_cache_enable) {
1820 SSL_CTX_remove_session(inst->ctx,
1821 tls_session->ssl->session);
1828 * New sessions cause some additional information to be
1831 if (!SSL_session_reused(tls_session->ssl)) {
1833 * FIXME: Store miscellaneous data.
1835 RDEBUG2("Adding user data to cached session");
1838 SSL_SESSION_set_ex_data(tls_session->ssl->session,
1839 ssl_session_idx_user_session, session_data);
1843 * FIXME: Retrieve miscellaneous data.
1846 data = SSL_SESSION_get_ex_data(tls_session->ssl->session,
1847 ssl_session_idx_user_session);
1849 if (!session_data) {
1850 radlog_request(L_ERR, 0, request,
1851 "No user session data in cached session - "
1857 RDEBUG2("Retrieved session data from cached session");
1861 * Success: Automatically return MPPE keys.
1863 return eaptls_success(handler, 0);
1867 * The module name should be the only globally exported symbol.
1868 * That is, everything else should be 'static'.
1870 EAP_TYPE rlm_eap_tls = {
1872 eaptls_attach, /* attach */
1873 eaptls_initiate, /* Start the initial request */
1874 NULL, /* authorization */
1875 eaptls_authenticate, /* authentication */
1876 eaptls_detach /* detach */