Use SSL_export_keying_material for TLSv1.2 PRF derivation
[freeradius.git] / src / modules / rlm_eap / types / rlm_eap_tls / rlm_eap_tls.c
1 /*
2  * rlm_eap_tls.c  contains the interfaces that are called from eap
3  *
4  * Version:     $Id$
5  *
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.
10  *
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.
15  *
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
19  *
20  * Copyright 2001  hereUare Communications, Inc. <raghud@hereuare.com>
21  * Copyright 2003  Alan DeKok <aland@freeradius.org>
22  * Copyright 2006  The FreeRADIUS server project
23  *
24  */
25
26 #include <freeradius-devel/ident.h>
27 RCSID("$Id$")
28
29 #include <freeradius-devel/autoconf.h>
30
31 #ifdef HAVE_OPENSSL_RAND_H
32 #include <openssl/rand.h>
33 #endif
34
35 #ifdef HAVE_OPENSSL_EVP_H
36 #include <openssl/evp.h>
37 #endif
38
39 #include <openssl/x509.h>
40
41 #include "rlm_eap_tls.h"
42 #include "config.h"
43
44 #ifdef HAVE_SYS_STAT_H
45 #include <sys/stat.h>
46 #endif
47
48 #ifdef HAVE_OPENSSL_OCSP_H
49 #include <openssl/ocsp.h>
50 #endif
51
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 */
62 };
63
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 */
70 };
71
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 */
87 };
88 #endif
89
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 },
135
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"},
140 #endif
141 #endif
142
143 #ifdef SSL_OP_NO_TLSv1_1
144         { "disable_tlsv1_1", PW_TYPE_BOOLEAN,
145           offsetof(EAP_TLS_CONF, disable_tlsv1_1), NULL, NULL },
146 #endif
147
148         /*
149          * @fixme Disabled because using TLS1.2 seems to cause MPPE key issues with eapol_test
150          * need to fix FreeRADIUS or wpa_supplicant.
151          */
152 #ifdef SSL_OP_NO_TLSv1_2
153         { "disable_tlsv1_2", PW_TYPE_BOOLEAN,
154           offsetof(EAP_TLS_CONF, disable_tlsv1_2), NULL, "yes" },
155 #endif
156
157         { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
158
159         { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
160
161 #ifdef HAVE_OPENSSL_OCSP_H
162         { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
163 #endif
164
165         { NULL, -1, 0, NULL, NULL }           /* end the list */
166 };
167
168
169 /*
170  *      TODO: Check for the type of key exchange * like conf->dh_key
171  */
172 static int load_dh_params(SSL_CTX *ctx, char *file)
173 {
174         DH *dh = NULL;
175         BIO *bio;
176
177         if (!ctx || !file) return 0;
178
179         if ((bio = BIO_new_file(file, "r")) == NULL) {
180                 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
181                 return -1;
182         }
183
184         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
185         BIO_free(bio);
186         if (!dh) {
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");
189                 return 0;
190         }
191
192         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
193                 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
194                 DH_free(dh);
195                 return -1;
196         }
197
198         DH_free(dh);
199         return 0;
200 }
201
202
203 /*
204  *      Generate ephemeral RSA keys.
205  */
206 static int generate_eph_rsa_key(SSL_CTX *ctx)
207 {
208         RSA *rsa;
209
210         if (!SSL_CTX_need_tmp_RSA(ctx)) return 0;
211
212         rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
213
214         if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
215                 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
216                 return -1;
217         }
218
219         RSA_free(rsa);
220         return 0;
221 }
222
223
224 /*
225  *      FIXME: Write sessions to some long-term storage, so that
226  *             session resumption can still occur after the server
227  *             restarts.
228  */
229 #define MAX_SESSION_SIZE (256)
230
231 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
232 {
233         size_t size;
234         char buffer[2 * MAX_SESSION_SIZE + 1];
235
236         size = sess->session_id_length;
237         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
238
239         fr_bin2hex(sess->session_id, buffer, size);
240
241         DEBUG2("  SSL: Removing session %s from the cache", buffer);
242         SSL_SESSION_free(sess);
243
244         return;
245 }
246
247 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
248 {
249         size_t size;
250         char buffer[2 * MAX_SESSION_SIZE + 1];
251
252         size = sess->session_id_length;
253         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
254
255         fr_bin2hex(sess->session_id, buffer, size);
256
257         DEBUG2("  SSL: adding session %s to cache", buffer);
258
259         return 1;
260 }
261
262 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
263                                       unsigned char *data, int len,
264                                       UNUSED int *copy)
265 {
266         size_t size;
267         char buffer[2 * MAX_SESSION_SIZE + 1];
268
269         size = len;
270         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
271
272         fr_bin2hex(data, buffer, size);
273
274         DEBUG2("  SSL: Client requested nonexistent cached session %s",
275                buffer);
276
277         return NULL;
278 }
279
280 #ifdef HAVE_OPENSSL_OCSP_H
281 /*
282  * This function extracts the OCSP Responder URL
283  * from an existing x509 certificate.
284  */
285 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
286                                char **ppath, int *pssl)
287 {
288         int i;
289
290         AUTHORITY_INFO_ACCESS *aia;
291         ACCESS_DESCRIPTION *ad;
292
293         aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
294
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))
301                                         return 1;
302                         }
303                 }
304         }
305         return 0;
306 }
307
308 /*
309  * This function sends a OCSP request to a defined OCSP responder
310  * and checks the OCSP response for correctness.
311  */
312
313 /* Maximum leeway in validity period: default 5 minutes */
314 #define MAX_VALIDITY_PERIOD     (5 * 60)
315
316 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
317                       EAP_TLS_CONF *conf)
318 {
319         OCSP_CERTID *certid;
320         OCSP_REQUEST *req;
321         OCSP_RESPONSE *resp = NULL;
322         OCSP_BASICRESP *bresp = NULL;
323         char *host = NULL;
324         char *port = NULL;
325         char *path = NULL;
326         int use_ssl = -1;
327         long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
328         BIO *cbio, *bio_out;
329         int ocsp_ok = 0;
330         int status ;
331         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
332         int reason;
333 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
334         OCSP_REQ_CTX *ctx;
335         int rc;
336         struct timeval now;
337         struct timeval when;
338 #endif
339
340         /*
341          * Create OCSP Request
342          */
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);
348         }
349
350         /*
351          * Send OCSP Request and get OCSP Response
352          */
353
354         /* Get OCSP responder URL */
355         if(conf->ocsp_override_url) {
356                 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
357         }
358         else {
359                 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
360         }
361
362         if (!host || !port || !path) {
363                 DEBUG2("[ocsp] - Host / port / path missing.  Not doing OCSP.");
364                 ocsp_ok = 2;
365                 goto ocsp_skip;
366         }
367
368         DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
369
370         /* Setup BIO socket to OCSP responder */
371         cbio = BIO_new_connect(host);
372
373         /*
374          *      Only print debugging information if we're in debugging
375          *      mode.
376          */
377         if (debug_flag) {
378                 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
379         } else {
380                 bio_out = NULL;
381         }
382
383         BIO_set_conn_port(cbio, port);
384 #if OPENSSL_VERSION_NUMBER < 0x1000003f
385         BIO_do_connect(cbio);
386
387         /* Send OCSP request and wait for response */
388         resp = OCSP_sendreq_bio(cbio, path, req);
389         if (!resp) {
390                 radlog(L_ERR, "Error: Couldn't get OCSP response");
391                 ocsp_ok = 2;
392                 goto ocsp_end;
393         }
394 #else
395         if (conf->ocsp_timeout)
396                 BIO_set_nbio(cbio, 1);
397
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");
401                 ocsp_ok = 2;
402                 goto ocsp_end;
403         }
404
405         ctx = OCSP_sendreq_new(cbio, path, req, -1);
406         if (!ctx) {
407                 radlog(L_ERR, "Error: Couldn't send OCSP request");
408                 ocsp_ok = 2;
409                 goto ocsp_end;
410         }
411
412         gettimeofday(&when, NULL);
413         when.tv_sec += conf->ocsp_timeout;
414
415         do {
416                 rc = OCSP_sendreq_nbio(&resp, ctx);
417                 if (conf->ocsp_timeout) {
418                         gettimeofday(&now, NULL);
419                         if (!timercmp(&now, &when, <))
420                                 break;
421                 }
422         } while ((rc == -1) && BIO_should_retry(cbio));
423
424         if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
425                 radlog(L_ERR, "Error: OCSP response timed out");
426                 ocsp_ok = 2;
427                 goto ocsp_end;
428         }
429
430         OCSP_REQ_CTX_free(ctx);
431
432         if (rc == 0) {
433                 radlog(L_ERR, "Error: Couldn't get OCSP response");
434                 ocsp_ok = 2;
435                 goto ocsp_end;
436         }
437 #endif
438
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));
444                 goto ocsp_end;
445         }
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");
449                 goto ocsp_end;
450         }
451         if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
452                 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
453                 goto ocsp_end;
454         }
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");
459                 goto ocsp_end;
460         }
461
462         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
463                 if (bio_out) {
464                         BIO_puts(bio_out, "WARNING: Status times invalid.\n");
465                         ERR_print_errors(bio_out);
466                 }
467                 goto ocsp_end;
468         }
469
470         if (bio_out) {
471                 BIO_puts(bio_out, "\tThis Update: ");
472                 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
473                 BIO_puts(bio_out, "\n");
474                 if (nextupd) {
475                         BIO_puts(bio_out, "\tNext Update: ");
476                         ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
477                         BIO_puts(bio_out, "\n");
478                 }
479         }
480
481         switch (status) {
482         case V_OCSP_CERTSTATUS_GOOD:
483                 DEBUG2("[oscp] --> Cert status: good");
484                 ocsp_ok = 1;
485                 break;
486
487         default:
488                 /* REVOKED / UNKNOWN */
489                 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
490                 if (reason != -1)
491                         DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
492
493                 if (bio_out) {
494                         BIO_puts(bio_out, "\tRevocation Time: ");
495                         ASN1_GENERALIZEDTIME_print(bio_out, rev);
496                         BIO_puts(bio_out, "\n");
497                 }
498                 break;
499         }
500
501 ocsp_end:
502         /* Free OCSP Stuff */
503         OCSP_REQUEST_free(req);
504         OCSP_RESPONSE_free(resp);
505         free(host);
506         free(port);
507         free(path);
508         BIO_free_all(cbio);
509         if (bio_out) BIO_free(bio_out);
510         OCSP_BASICRESP_free(bresp);
511
512 ocsp_skip:
513         switch (ocsp_ok) {
514         case 1:
515                 DEBUG2("[ocsp] --> Certificate is valid!");
516                 break;
517         case 2:
518                 if (conf->ocsp_softfail) {
519                         DEBUG2("[ocsp] --> Unable to check certificate; assuming valid.");
520                         DEBUG2("[ocsp] --> Warning! This may be insecure.");
521                         ocsp_ok = 1;
522                 } else {
523                         DEBUG2("[ocsp] --> Unable to check certificate; failing!");
524                         ocsp_ok = 0;
525                 }
526                 break;
527         default:
528                 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
529                 break;
530         }
531
532         return ocsp_ok;
533 }
534 #endif  /* HAVE_OPENSSL_OCSP_H */
535
536 /*
537  *      For creating certificate attributes.
538  */
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" }
546 };
547
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)
554
555 /*
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:
560  *
561  *      1.Verifying the certificate's signature, and verifying that
562  *      the certificate has been issued by a trusted Certificate
563  *      Authority.
564  *
565  *      2.Verifying that the certificate is valid for the present date
566  *      (i.e. it is being presented within its validity dates).
567  *
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).
571  *
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).
576  *
577  *      NOTE: This callback will be called multiple times based on the
578  *      depth of the root certificate chain
579  */
580 static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
581 {
582         char subject[1024]; /* Used for the subject name */
583         char issuer[1024]; /* Used for the issuer name */
584         char attribute[1024];
585         char value[1024];
586         char common_name[1024];
587         char cn_str[1024];
588         char buf[64];
589         EAP_HANDLER *handler = NULL;
590         X509 *client_cert;
591         X509_CINF *client_inf;
592         STACK_OF(X509_EXTENSION) *ext_list;
593         X509 *issuer_cert;
594         SSL *ssl;
595         int err, depth, lookup, loc;
596         EAP_TLS_CONF *conf;
597         int my_ok = ok;
598         REQUEST *request;
599         ASN1_INTEGER *sn = NULL;
600         ASN1_TIME *asn_time = NULL;
601 #ifdef HAVE_OPENSSL_OCSP_H
602         X509_STORE *ocsp_store = NULL;
603 #endif
604
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);
608
609         lookup = depth;
610
611         /*
612          *      Log client/issuing cert.  If there's an error, log
613          *      issuing cert.
614          */
615         if ((lookup > 1) && !my_ok) lookup = 1;
616
617         /*
618          * Retrieve the pointer to the SSL of the connection currently treated
619          * and the application specific data stored into the SSL object.
620          */
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);
627 #endif
628
629
630         /*
631          *      Get the Serial Number
632          */
633         buf[0] = '\0';
634         sn = X509_get_serialNumber(client_cert);
635
636         /*
637          *      For this next bit, we create the attributes *only* if
638          *      we're at the client or issuing certificate.
639          */
640         if ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {
641                 char *p = buf;
642                 int i;
643
644                 for (i = 0; i < sn->length; i++) {
645                         sprintf(p, "%02x", (unsigned int)sn->data[i]);
646                         p += 2;
647                 }
648                 pairadd(&handler->certs,
649                         pairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));
650         }
651
652
653         /*
654          *      Get the Expiration Date
655          */
656         buf[0] = '\0';
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));
663         }
664
665         /*
666          *      Get the Subject & Issuer
667          */
668         subject[0] = issuer[0] = '\0';
669         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
670                           sizeof(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));
675         }
676
677         X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
678                           sizeof(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));
683         }
684
685         /*
686          *      Get the Common Name, if there is a subject.
687          */
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));
694         }
695
696 #ifdef GEN_EMAIL
697         /*
698          *      Get the RFC822 Subject Alternative Name
699          */
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;
704                 int i;
705
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);
710
711                                 switch (name->type) {
712                                 case GEN_EMAIL:
713                                         if (ASN1_STRING_length(name->d.rfc822Name) >= MAX_STRING_LEN)
714                                                 break;
715
716                                         pairadd(&handler->certs,
717                                                 pairmake(cert_attr_names[EAPTLS_SAN_EMAIL][lookup],
718                                                          (char *)ASN1_STRING_data(name->d.rfc822Name), T_OP_SET));
719                                         break;
720                                 default:
721                                         /* XXX TODO handle other SAN types */
722                                         break;
723                                 }
724                         }
725                 }
726                 if (names != NULL)
727                         sk_GENERAL_NAME_free(names);
728         }
729 #endif  /* GEN_EMAIL */
730
731         /*
732          *      If the CRL has expired, that might still be OK.
733          */
734         if (!my_ok &&
735             (conf->allow_expired_crl) &&
736             (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
737                 my_ok = 1;
738                 X509_STORE_CTX_set_error( ctx, 0 );
739         }
740
741         if (!my_ok) {
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);
746                 return my_ok;
747         }
748
749         if (lookup == 0) {
750                 client_inf = client_cert->cert_info;
751                 ext_list = client_inf->extensions;
752         } else {
753                 ext_list = NULL;
754         }
755
756         /*
757          *      Grab the X509 extensions, and create attributes out of them.
758          *      For laziness, we re-use the OpenSSL names
759          */
760         if (sk_X509_EXTENSION_num(ext_list) > 0) {
761                 int i, len;
762                 char *p;
763                 BIO *out;
764
765                 out = BIO_new(BIO_s_mem());
766                 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
767
768                 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
769                         ASN1_OBJECT *obj;
770                         X509_EXTENSION *ext;
771                         VALUE_PAIR *vp;
772
773                         ext = sk_X509_EXTENSION_value(ext_list, i);
774
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;
779
780                         attribute[16 + len] = '\0';
781
782                         X509V3_EXT_print(out, ext, 0, 0);
783                         len = BIO_read(out, value, sizeof(value) - 1);
784                         if (len <= 0) continue;
785
786                         value[len] = '\0';
787
788                         /*
789                          *      Mash the OpenSSL name to our name, and
790                          *      create the attribute.
791                          */
792                         for (p = attribute + 16; *p != '\0'; p++) {
793                                 if (*p == ' ') *p = '-';
794                         }
795
796                         vp = pairmake(attribute, value, T_OP_ADD);
797                         if (vp) {
798                                 pairadd(&handler->certs, vp);
799                                 debug_pair_list(vp);
800                         }
801                 }
802
803                 BIO_free_all(out);
804         }
805
806         switch (ctx->error) {
807
808         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
809                 radlog(L_ERR, "issuer= %s\n", issuer);
810                 break;
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=");
814 #if 0
815                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
816 #endif
817                 break;
818         case X509_V_ERR_CERT_HAS_EXPIRED:
819         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
820                 radlog(L_ERR, "notAfter=");
821 #if 0
822                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
823 #endif
824                 break;
825         }
826
827         /*
828          *      If we're at the actual client cert, apply additional
829          *      checks.
830          */
831         if (depth == 0) {
832                 /*
833                  *      If the conf tells us to, check cert issuer
834                  *      against the specified value and fail
835                  *      verification if they don't match.
836                  */
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);
840                         my_ok = 0;
841                 }
842
843                 /*
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.
847                  */
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 */
853                                 my_ok = 0;
854                         } else {
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);
858                                         my_ok = 0;
859                                 }
860                         }
861                 } /* check_cert_cn */
862
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);
868                         } else {
869                                 my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
870                         }
871                 }
872 #endif
873
874                 while (conf->verify_client_cert_cmd) {
875                         char filename[256];
876                         int fd;
877                         FILE *fp;
878
879                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
880                                  conf->verify_tmp_dir, progname);
881                         fd = mkstemp(filename);
882                         if (fd < 0) {
883                                 RDEBUG("Failed creating file in %s: %s",
884                                        conf->verify_tmp_dir, strerror(errno));
885                                 break;
886                         }
887
888                         fp = fdopen(fd, "w");
889                         if (!fp) {
890                                 RDEBUG("Failed opening file %s: %s",
891                                        filename, strerror(errno));
892                                 break;
893                         }
894
895                         if (!PEM_write_X509(fp, client_cert)) {
896                                 fclose(fp);
897                                 RDEBUG("Failed writing certificate to file");
898                                 goto do_unlink;
899                         }
900                         fclose(fp);
901
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");
906
907                                 goto do_unlink;
908                         }
909
910                         RDEBUG("Verifying client certificate: %s",
911                                conf->verify_client_cert_cmd);
912                         if (radius_exec_program(conf->verify_client_cert_cmd,
913                                                 request, 1, NULL, 0,
914                                                 EXEC_TIMEOUT,
915                                                 request->packet->vps,
916                                                 NULL, 1) != 0) {
917                                 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
918                                 my_ok = 0;
919                         } else {
920                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
921                         }
922
923                 do_unlink:
924                         unlink(filename);
925                         break;
926                 }
927
928
929         } /* depth == 0 */
930
931         if (debug_flag > 0) {
932                 RDEBUG2("chain-depth=%d, ", depth);
933                 RDEBUG2("error=%d", err);
934
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);
940         }
941         return my_ok;
942 }
943
944
945 /*
946  *      Free cached session data, which is always a list of VALUE_PAIRs
947  */
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)
951 {
952         VALUE_PAIR *vp = data_ptr;
953         if (!data_ptr) return;
954
955         pairfree(&vp);
956 }
957
958 #ifdef HAVE_OPENSSL_OCSP_H
959 /*
960  *      Create Global X509 revocation store and use it to verify
961  *      OCSP responses
962  *
963  *      - Load the trusted CAs
964  *      - Load the trusted issuer certificates
965  */
966 static X509_STORE *init_revocation_store(EAP_TLS_CONF *conf)
967 {
968         X509_STORE *store = NULL;
969
970         store = X509_STORE_new();
971
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 );
977                         return NULL;
978                 }
979
980 #ifdef X509_V_FLAG_CRL_CHECK
981         if (conf->check_crl)
982                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
983 #endif
984         return store;
985 }
986 #endif  /* HAVE_OPENSSL_OCSP_H */
987
988 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
989 #ifndef OPENSSL_NO_ECDH
990 static int set_ecdh_curve(SSL_CTX *ctx, const char *ecdh_curve)
991 {
992         int      nid;
993         EC_KEY  *ecdh;
994
995         if (!ecdh_curve || !*ecdh_curve) return 0;
996
997         nid = OBJ_sn2nid(ecdh_curve);
998         if (!nid) {
999                 radlog(L_ERR, "Unknown ecdh_curve \"%s\"", ecdh_curve);
1000                 return -1;
1001         }
1002
1003         ecdh = EC_KEY_new_by_curve_name(nid);
1004         if (!ecdh) {
1005                 radlog(L_ERR, "Unable to create new curve \"%s\"", ecdh_curve);
1006                 return -1;
1007         }
1008
1009         SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1010
1011         SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1012
1013         EC_KEY_free(ecdh);
1014
1015         return 0;
1016 }
1017 #endif
1018 #endif
1019
1020 /*
1021  *      Create Global context SSL and use it in every new session
1022  *
1023  *      - Load the trusted CAs
1024  *      - Load the Private key & the certificate
1025  *      - Set the Context options & Verify options
1026  */
1027 static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
1028 {
1029         SSL_METHOD *meth;
1030         SSL_CTX *ctx;
1031         X509_STORE *certstore;
1032         int verify_mode = SSL_VERIFY_NONE;
1033         int ctx_options = 0;
1034         int type;
1035
1036         /*
1037          *      Bug fix
1038          *      http://old.nabble.com/Backward-compatibility-of-private-key-files--td27937046.html
1039          */
1040         OpenSSL_add_all_algorithms();
1041
1042         /*
1043          *      SHA256 is in all versions of OpenSSL, but isn't
1044          *      initialized by default.  It's needed for WiMAX
1045          *      certificates.
1046          */
1047 #ifdef HAVE_OPENSSL_EVP_SHA256
1048         EVP_add_digest(EVP_sha256());
1049 #endif
1050
1051         meth = SSLv23_method(); /* which is really "all known SSL / TLS methods".  Idiots. */
1052         ctx = SSL_CTX_new(meth);
1053
1054         /*
1055          * Identify the type of certificates that needs to be loaded
1056          */
1057         if (conf->file_type) {
1058                 type = SSL_FILETYPE_PEM;
1059         } else {
1060                 type = SSL_FILETYPE_ASN1;
1061         }
1062
1063         /*
1064          * Set the password to load private key
1065          */
1066         if (conf->private_key_password) {
1067 #ifdef __APPLE__
1068                 /*
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
1071                  * programmatically.
1072                  */
1073                 const char* special_string = "Apple:UseCertAdmin";
1074                 if (strncmp(conf->private_key_password,
1075                                         special_string,
1076                                         strlen(special_string)) == 0)
1077                 {
1078                         char cmd[256];
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);
1083
1084                         DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
1085
1086                         FILE* cmd_pipe = popen(cmd, "r");
1087                         if (!cmd_pipe) {
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);
1090                                 return NULL;
1091                         }
1092
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);
1098                                 pclose(cmd_pipe);
1099                                 return NULL;
1100                         }
1101
1102                         fgets(conf->private_key_password, max_password_len, cmd_pipe);
1103                         pclose(cmd_pipe);
1104
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);
1108                 }
1109 #endif
1110                 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
1111                 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
1112         }
1113
1114         /*
1115          *      Load our keys and certificates
1116          *
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
1121          *      openSSL.org
1122          */
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);
1127                         return NULL;
1128                 }
1129
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);
1133                 return NULL;
1134         }
1135
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 );
1141                         return NULL;
1142                 }
1143         }
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);
1148                 return NULL;
1149         }
1150
1151         /*
1152          * Check if the loaded private key is the right one
1153          */
1154         if (!SSL_CTX_check_private_key(ctx)) {
1155                 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
1156                 return NULL;
1157         }
1158
1159         /*
1160          *      Set ctx_options
1161          */
1162         ctx_options |= SSL_OP_NO_SSLv2;
1163         ctx_options |= SSL_OP_NO_SSLv3;
1164
1165 #ifdef SSL_OP_NO_TLSv1_1
1166         if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
1167 #endif
1168 #ifdef SSL_OP_NO_TLSv1_2
1169         if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
1170 #endif
1171
1172 #ifdef SSL_OP_NO_TICKET
1173         ctx_options |= SSL_OP_NO_TICKET;
1174 #endif
1175
1176         /*
1177          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
1178          *      small subgroup attacks and forward secrecy. Always
1179          *      using
1180          *
1181          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
1182          *      time needed during negotiation, but it is not very
1183          *      large.
1184          */
1185         ctx_options |= SSL_OP_SINGLE_DH_USE;
1186
1187         /*
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
1192          */
1193         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1194
1195         SSL_CTX_set_options(ctx, ctx_options);
1196
1197         /*
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);
1201          */
1202
1203         /*
1204          *      Set eliptical curve crypto configuration.
1205          */
1206 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1207 #ifndef OPENSSL_NO_ECDH
1208         if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
1209                 return NULL;
1210         }
1211 #endif
1212 #endif
1213
1214         /*
1215          *      set the message callback to identify the type of
1216          *      message.  For every new session, there can be a
1217          *      different callback argument.
1218          *
1219          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
1220          */
1221
1222         /* Set Info callback */
1223         SSL_CTX_set_info_callback(ctx, cbtls_info);
1224
1225         /*
1226          *      Callbacks, etc. for session resumption.
1227          */
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);
1232
1233                 SSL_CTX_set_quiet_shutdown(ctx, 1);
1234         }
1235
1236         /*
1237          *      Check the certificates for revocation.
1238          */
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");
1245             return NULL;
1246           }
1247           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
1248         }
1249 #endif
1250
1251         /*
1252          *      Set verify modes
1253          *      Always verify the peer certificate
1254          */
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);
1259
1260         if (conf->verify_depth) {
1261                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
1262         }
1263
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");
1269                         return NULL;
1270                 }
1271         }
1272
1273         /*
1274          * Set the cipher list if we were told to
1275          */
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");
1279                         return NULL;
1280                 }
1281         }
1282
1283         /*
1284          *      Setup session caching
1285          */
1286         if (conf->session_cache_enable) {
1287                 /*
1288                  *      Create a unique context Id per EAP-TLS configuration.
1289                  */
1290                 if (conf->session_id_name) {
1291                         snprintf(conf->session_context_id,
1292                                  sizeof(conf->session_context_id),
1293                                  "FR eap %s",
1294                                  conf->session_id_name);
1295                 } else {
1296                         snprintf(conf->session_context_id,
1297                                  sizeof(conf->session_context_id),
1298                                  "FR eap %p", conf);
1299                 }
1300
1301                 /*
1302                  *      Cache it, and DON'T auto-clear it.
1303                  */
1304                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
1305
1306                 SSL_CTX_set_session_id_context(ctx,
1307                                                (unsigned char *) conf->session_context_id,
1308                                                (unsigned int) strlen(conf->session_context_id));
1309
1310                 /*
1311                  *      Our timeout is in hours, this is in seconds.
1312                  */
1313                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
1314
1315                 /*
1316                  *      Set the maximum number of entries in the
1317                  *      session cache.
1318                  */
1319                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
1320
1321         } else {
1322                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1323         }
1324
1325         /*
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
1329          *      information.
1330          */
1331         if (eaptls_handle_idx < 0) {
1332                 eaptls_handle_idx = SSL_get_ex_new_index(0, "eaptls_handle_idx",
1333                                                           NULL, NULL, NULL);
1334         }
1335
1336         if (eaptls_conf_idx < 0) {
1337                 eaptls_conf_idx = SSL_get_ex_new_index(0, "eaptls_conf_idx",
1338                                                           NULL, NULL, NULL);
1339         }
1340
1341         if (eaptls_store_idx < 0) {
1342                 eaptls_store_idx = SSL_get_ex_new_index(0, "eaptls_store_idx",
1343                                                           NULL, NULL, NULL);
1344         }
1345
1346         if (eaptls_session_idx < 0) {
1347                 eaptls_session_idx = SSL_SESSION_get_ex_new_index(0, "eaptls_session_idx",
1348                                                           NULL, NULL,
1349                                                           eaptls_session_free);
1350         }
1351
1352         return ctx;
1353 }
1354
1355
1356 /*
1357  *      Detach the EAP-TLS module.
1358  */
1359 static int eaptls_detach(void *arg)
1360 {
1361         EAP_TLS_CONF     *conf;
1362         eap_tls_t        *inst;
1363
1364         inst = (eap_tls_t *) arg;
1365         conf = &(inst->conf);
1366
1367         if (inst->ctx) SSL_CTX_free(inst->ctx);
1368         inst->ctx = NULL;
1369
1370 #ifdef HAVE_OPENSSL_OCSP_H
1371         if (inst->store) X509_STORE_free(inst->store);
1372         inst->store = NULL;
1373 #endif
1374
1375         free(inst);
1376
1377         return 0;
1378 }
1379
1380
1381 /*
1382  *      Attach the EAP-TLS module.
1383  */
1384 static int eaptls_attach(CONF_SECTION *cs, void **instance)
1385 {
1386         EAP_TLS_CONF     *conf;
1387         eap_tls_t        *inst;
1388
1389         /* Store all these values in the data structure for later references */
1390         inst = (eap_tls_t *)malloc(sizeof(*inst));
1391         if (!inst) {
1392                 radlog(L_ERR, "rlm_eap_tls: out of memory");
1393                 return -1;
1394         }
1395         memset(inst, 0, sizeof(*inst));
1396         conf = &(inst->conf);
1397
1398         /*
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.
1402          */
1403         if (cf_section_parse(cs, inst, module_config) < 0) {
1404                 eaptls_detach(inst);
1405                 return -1;
1406         }
1407
1408         /*
1409          *      The EAP RFC's say 1020, but we're less picky.
1410          */
1411         if (conf->fragment_size < 100) {
1412                 radlog(L_ERR, "rlm_eap_tls: Fragment size is too small.");
1413                 eaptls_detach(inst);
1414                 return -1;
1415         }
1416
1417         /*
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.
1422          */
1423         if (conf->fragment_size > 4000) {
1424                 radlog(L_ERR, "rlm_eap_tls: Fragment size is too large.");
1425                 eaptls_detach(inst);
1426                 return -1;
1427         }
1428
1429         /*
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.
1433          */
1434         conf->fragment_size -= 10;
1435
1436         /*
1437          *      This magic makes the administrators life HUGELY easier
1438          *      on initial deployments.
1439          *
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
1443          */
1444         if (conf->make_cert_command && (debug_flag >= 2)) {
1445                 struct stat buf;
1446
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);
1454                         return -1;
1455                 }
1456         }
1457
1458
1459         /*
1460          *      Initialize TLS
1461          */
1462         inst->ctx = init_tls_ctx(conf);
1463         if (inst->ctx == NULL) {
1464                 eaptls_detach(inst);
1465                 return -1;
1466         }
1467
1468 #ifdef HAVE_OPENSSL_OCSP_H
1469         /*
1470          *      Initialize OCSP Revocation Store
1471          */
1472         if (conf->ocsp_enable) {
1473                 inst->store = init_revocation_store(conf);
1474                 if (inst->store == NULL) {
1475                         eaptls_detach(inst);
1476                   return -1;
1477                 }
1478         }
1479 #endif /*HAVE_OPENSSL_OCSP_H*/
1480
1481         if (load_dh_params(inst->ctx, conf->dh_file) < 0) {
1482                 eaptls_detach(inst);
1483                 return -1;
1484         }
1485
1486         if (generate_eph_rsa_key(inst->ctx) < 0) {
1487                 eaptls_detach(inst);
1488                 return -1;
1489         }
1490
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);
1495                         return -1;
1496                 }
1497         }
1498
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);
1502                 return -1;
1503         }
1504
1505         *instance = inst;
1506
1507         return 0;
1508 }
1509
1510
1511 /*
1512  *      Send an initial eap-tls request to the peer.
1513  *
1514  *      Frame eap reply packet.
1515  *      len = header + type + tls_typedata
1516  *      tls_typedata = flags(Start (S) bit set, and no data)
1517  *
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
1524  *      be the TLS data.
1525  *
1526  *      Fragment length is Framed-MTU - 4.
1527  *
1528  *      http://mail.frascone.com/pipermail/public/eap/2003-July/001426.html
1529  */
1530 static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
1531 {
1532         int             status;
1533         tls_session_t   *ssn;
1534         eap_tls_t       *inst;
1535         VALUE_PAIR      *vp;
1536         int             client_cert = TRUE;
1537         int             verify_mode = 0;
1538         REQUEST         *request = handler->request;
1539
1540         inst = (eap_tls_t *)type_arg;
1541
1542         handler->tls = TRUE;
1543         handler->finished = FALSE;
1544
1545         /*
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.
1549          *
1550          *      FIXME: Also do it every N sessions?
1551          */
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));
1556
1557                 SSL_CTX_flush_sessions(inst->ctx, request->timestamp);
1558                 inst->conf.session_last_flushed = request->timestamp;
1559         }
1560
1561         /*
1562          *      If we're TTLS or PEAP, then do NOT require a client
1563          *      certificate.
1564          *
1565          *      FIXME: This should be more configurable.
1566          */
1567         if (handler->eap_type != PW_EAP_TLS) {
1568                 vp = pairfind(handler->request->config_items,
1569                               PW_EAP_TLS_REQUIRE_CLIENT_CERT);
1570                 if (!vp) {
1571                         client_cert = FALSE;
1572                 } else {
1573                         client_cert = vp->vp_integer;
1574                 }
1575         }
1576
1577         /*
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
1583          */
1584         ssn = eaptls_new_session(inst->ctx, client_cert);
1585         if (!ssn) {
1586                 return 0;
1587         }
1588
1589         /*
1590          *      Verify the peer certificate, if asked.
1591          */
1592         if (client_cert) {
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;
1597         }
1598         SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
1599
1600         /*
1601          *      Create a structure for all the items required to be
1602          *      verified for each client and set that as opaque data
1603          *      structure.
1604          *
1605          *      NOTE: If we want to set each item sepearately then
1606          *      this index should be global.
1607          */
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);
1612 #endif
1613
1614         ssn->length_flag = inst->conf.include_length;
1615
1616         /*
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.
1621          *
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
1626          *      just too much.
1627          */
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)) {
1631                 /*
1632                  *      Discount the Framed-MTU by:
1633                  *       4 : EAPOL header
1634                  *       4 : EAP header (code + id + length)
1635                  *       1 : EAP type == EAP-TLS
1636                  *       1 : EAP-TLS Flags
1637                  *       4 : EAP-TLS Message length
1638                  *          (even if conf->include_length == 0,
1639                  *           just to be lazy).
1640                  *      ---
1641                  *      14
1642                  */
1643                 ssn->offset = vp->vp_integer - 14;
1644         }
1645
1646         handler->opaque = ((void *)ssn);
1647         handler->free_opaque = session_free;
1648
1649         RDEBUG2("Initiate");
1650
1651         /*
1652          *      Set up type-specific information.
1653          */
1654         switch (handler->eap_type) {
1655         case PW_EAP_TLS:
1656         default:
1657                 ssn->prf_label = "client EAP encryption";
1658                 break;
1659
1660         case PW_EAP_TTLS:
1661                 ssn->prf_label = "ttls keying material";
1662                 break;
1663
1664                 /*
1665                  *      PEAP-specific breakage.
1666                  */
1667         case PW_EAP_PEAP:
1668                 /*
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.
1676                  */
1677                 ssn->peap_flag = 0x00;
1678
1679                 /*
1680                  *      PEAP version 0 requires 'include_length = no',
1681                  *      so rather than hoping the user figures it out,
1682                  *      we force it here.
1683                  */
1684                 ssn->length_flag = 0;
1685
1686                 ssn->prf_label = "client EAP encryption";
1687                 break;
1688         }
1689
1690         if (inst->conf.session_cache_enable) {
1691                 ssn->allow_session_resumption = 1; /* otherwise it's zero */
1692         }
1693
1694         /*
1695          *      TLS session initialization is over.  Now handle TLS
1696          *      related handshaking or application data.
1697          */
1698         status = eaptls_start(handler->eap_ds, ssn->peap_flag);
1699         RDEBUG2("Start returned %d", status);
1700         if (status == 0)
1701                 return 0;
1702
1703         /*
1704          *      The next stage to process the packet.
1705          */
1706         handler->stage = AUTHENTICATE;
1707
1708         return 1;
1709 }
1710
1711 /*
1712  *      Do authentication, by letting EAP-TLS do most of the work.
1713  */
1714 static int eaptls_authenticate(void *arg, EAP_HANDLER *handler)
1715 {
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;
1720
1721         RDEBUG2("Authenticate");
1722
1723         status = eaptls_process(handler);
1724         RDEBUG2("eaptls_process returned %d\n", status);
1725         switch (status) {
1726                 /*
1727                  *      EAP-TLS handshake was successful, return an
1728                  *      EAP-TLS-Success packet here.
1729                  */
1730         case EAPTLS_SUCCESS:
1731                 if (inst->conf.virtual_server) {
1732                         VALUE_PAIR *vp;
1733                         REQUEST *fake;
1734
1735                         /* create a fake request */
1736                         fake = request_alloc_fake(request);
1737                         rad_assert(fake->packet->vps == NULL);
1738
1739                         fake->packet->vps = paircopy(request->packet->vps);
1740
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;
1745                         } else {
1746                                 fake->server = inst->conf.virtual_server;
1747                         }
1748
1749                         RDEBUG("Processing EAP-TLS Certificate check:");
1750                         debug_pair_list(fake->packet->vps);
1751
1752                         RDEBUG("server %s {", fake->server);
1753
1754                         rad_virtual_server(fake);
1755
1756                         RDEBUG("} # server %s", fake->server);
1757
1758                         /* copy the reply vps back to our reply */
1759                         pairadd(&request->reply->vps, fake->reply->vps);
1760                         fake->reply->vps = NULL;
1761
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);
1767                                 return 0;
1768                         }
1769
1770                         request_free(&fake);
1771                         /* success */
1772                 }
1773                 break;
1774
1775                 /*
1776                  *      The TLS code is still working on the TLS
1777                  *      exchange, and it's a valid TLS request.
1778                  *      do nothing.
1779                  */
1780         case EAPTLS_HANDLED:
1781                 return 1;
1782
1783                 /*
1784                  *      Handshake is done, proceed with decoding tunneled
1785                  *      data.
1786                  */
1787         case EAPTLS_OK:
1788                 RDEBUG2("Received unexpected tunneled data after successful handshake.");
1789 #ifndef NDEBUG
1790                 if ((debug_flag > 2) && fr_log_fp) {
1791                         unsigned int i;
1792                         unsigned int data_len;
1793                         unsigned char buffer[1024];
1794
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");
1801
1802                                 fprintf(fr_log_fp, "%02x ", buffer[i]);
1803                         }
1804                         fprintf(fr_log_fp, "\n");
1805                 }
1806 #endif
1807
1808                 eaptls_fail(handler, 0);
1809                 return 0;
1810                 break;
1811
1812                 /*
1813                  *      Anything else: fail.
1814                  *
1815                  *      Also, remove the session from the cache so that
1816                  *      the client can't re-use it.
1817                  */
1818         default:
1819                 if (inst->conf.session_cache_enable) {
1820                         SSL_CTX_remove_session(inst->ctx,
1821                                                tls_session->ssl->session);
1822                 }
1823
1824                 return 0;
1825         }
1826
1827         /*
1828          *      New sessions cause some additional information to be
1829          *      cached.
1830          */
1831         if (!SSL_session_reused(tls_session->ssl)) {
1832                 /*
1833                  *      FIXME: Store miscellaneous data.
1834                  */
1835                 RDEBUG2("Adding user data to cached session");
1836
1837 #if 0
1838                 SSL_SESSION_set_ex_data(tls_session->ssl->session,
1839                                         ssl_session_idx_user_session, session_data);
1840 #endif
1841         } else {
1842                 /*
1843                  *      FIXME: Retrieve miscellaneous data.
1844                  */
1845 #if 0
1846                 data = SSL_SESSION_get_ex_data(tls_session->ssl->session,
1847                                                ssl_session_idx_user_session);
1848
1849                 if (!session_data) {
1850                         radlog_request(L_ERR, 0, request,
1851                                        "No user session data in cached session - "
1852                                        " REJECTING");
1853                         return 0;
1854                 }
1855 #endif
1856
1857                 RDEBUG2("Retrieved session data from cached session");
1858         }
1859
1860         /*
1861          *      Success: Automatically return MPPE keys.
1862          */
1863         return eaptls_success(handler, 0);
1864 }
1865
1866 /*
1867  *      The module name should be the only globally exported symbol.
1868  *      That is, everything else should be 'static'.
1869  */
1870 EAP_TYPE rlm_eap_tls = {
1871         "eap_tls",
1872         eaptls_attach,                  /* attach */
1873         eaptls_initiate,                /* Start the initial request */
1874         NULL,                           /* authorization */
1875         eaptls_authenticate,            /* authentication */
1876         eaptls_detach                   /* detach */
1877 };
1878