Cleanups for OCSP support
[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 "rlm_eap_tls.h"
40 #include "config.h"
41
42 #ifdef HAVE_SYS_STAT_H
43 #include <sys/stat.h>
44 #endif
45
46 #ifdef HAVE_OPENSSL_OCSP_H
47 #include <openssl/ocsp.h>
48 #endif
49
50 static CONF_PARSER cache_config[] = {
51         { "enable", PW_TYPE_BOOLEAN,
52           offsetof(EAP_TLS_CONF, session_cache_enable), NULL, "no" },
53         { "lifetime", PW_TYPE_INTEGER,
54           offsetof(EAP_TLS_CONF, session_timeout), NULL, "24" },
55         { "max_entries", PW_TYPE_INTEGER,
56           offsetof(EAP_TLS_CONF, session_cache_size), NULL, "255" },
57         { "name", PW_TYPE_STRING_PTR,
58           offsetof(EAP_TLS_CONF, session_id_name), NULL, NULL},
59         { NULL, -1, 0, NULL, NULL }           /* end the list */
60 };
61
62 static CONF_PARSER verify_config[] = {
63         { "tmpdir", PW_TYPE_STRING_PTR,
64           offsetof(EAP_TLS_CONF, verify_tmp_dir), NULL, NULL},
65         { "client", PW_TYPE_STRING_PTR,
66           offsetof(EAP_TLS_CONF, verify_client_cert_cmd), NULL, NULL},
67         { NULL, -1, 0, NULL, NULL }           /* end the list */
68 };
69
70 #ifdef HAVE_OPENSSL_OCSP_H
71 static CONF_PARSER ocsp_config[] = {
72         { "override_cert_url", PW_TYPE_BOOLEAN,
73           offsetof(EAP_TLS_CONF, ocsp_override_url), NULL, "no"},
74         { "url", PW_TYPE_STRING_PTR,
75           offsetof(EAP_TLS_CONF, ocsp_url), NULL, NULL },
76         { NULL, -1, 0, NULL, NULL }           /* end the list */
77 };
78 #endif
79
80 static CONF_PARSER module_config[] = {
81         { "rsa_key_exchange", PW_TYPE_BOOLEAN,
82           offsetof(EAP_TLS_CONF, rsa_key), NULL, "no" },
83         { "dh_key_exchange", PW_TYPE_BOOLEAN,
84           offsetof(EAP_TLS_CONF, dh_key), NULL, "yes" },
85         { "rsa_key_length", PW_TYPE_INTEGER,
86           offsetof(EAP_TLS_CONF, rsa_key_length), NULL, "512" },
87         { "dh_key_length", PW_TYPE_INTEGER,
88           offsetof(EAP_TLS_CONF, dh_key_length), NULL, "512" },
89         { "verify_depth", PW_TYPE_INTEGER,
90           offsetof(EAP_TLS_CONF, verify_depth), NULL, "0" },
91         { "CA_path", PW_TYPE_FILENAME,
92           offsetof(EAP_TLS_CONF, ca_path), NULL, NULL },
93         { "pem_file_type", PW_TYPE_BOOLEAN,
94           offsetof(EAP_TLS_CONF, file_type), NULL, "yes" },
95         { "private_key_file", PW_TYPE_FILENAME,
96           offsetof(EAP_TLS_CONF, private_key_file), NULL, NULL },
97         { "certificate_file", PW_TYPE_FILENAME,
98           offsetof(EAP_TLS_CONF, certificate_file), NULL, NULL },
99         { "CA_file", PW_TYPE_FILENAME,
100           offsetof(EAP_TLS_CONF, ca_file), NULL, NULL },
101         { "private_key_password", PW_TYPE_STRING_PTR,
102           offsetof(EAP_TLS_CONF, private_key_password), NULL, NULL },
103         { "dh_file", PW_TYPE_STRING_PTR,
104           offsetof(EAP_TLS_CONF, dh_file), NULL, NULL },
105         { "random_file", PW_TYPE_STRING_PTR,
106           offsetof(EAP_TLS_CONF, random_file), NULL, NULL },
107         { "fragment_size", PW_TYPE_INTEGER,
108           offsetof(EAP_TLS_CONF, fragment_size), NULL, "1024" },
109         { "include_length", PW_TYPE_BOOLEAN,
110           offsetof(EAP_TLS_CONF, include_length), NULL, "yes" },
111         { "check_crl", PW_TYPE_BOOLEAN,
112           offsetof(EAP_TLS_CONF, check_crl), NULL, "no"},
113         { "check_cert_cn", PW_TYPE_STRING_PTR,
114           offsetof(EAP_TLS_CONF, check_cert_cn), NULL, NULL},
115         { "cipher_list", PW_TYPE_STRING_PTR,
116           offsetof(EAP_TLS_CONF, cipher_list), NULL, NULL},
117         { "check_cert_issuer", PW_TYPE_STRING_PTR,
118           offsetof(EAP_TLS_CONF, check_cert_issuer), NULL, NULL},
119         { "make_cert_command", PW_TYPE_STRING_PTR,
120           offsetof(EAP_TLS_CONF, make_cert_command), NULL, NULL},
121
122         { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
123
124         { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
125
126 #ifdef HAVE_OPENSSL_OCSP_H
127         { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
128 #endif
129
130         { NULL, -1, 0, NULL, NULL }           /* end the list */
131 };
132
133
134 /*
135  *      TODO: Check for the type of key exchange * like conf->dh_key
136  */
137 static int load_dh_params(SSL_CTX *ctx, char *file)
138 {
139         DH *dh = NULL;
140         BIO *bio;
141
142         if ((bio = BIO_new_file(file, "r")) == NULL) {
143                 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
144                 return -1;
145         }
146
147         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
148         BIO_free(bio);
149         if (!dh) {
150                 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters.  DH cipher suites may not work!");
151                 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
152                 return 0;
153         }
154
155         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
156                 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
157                 DH_free(dh);
158                 return -1;
159         }
160
161         DH_free(dh);
162         return 0;
163 }
164
165
166 /*
167  *      Generate ephemeral RSA keys.
168  */
169 static int generate_eph_rsa_key(SSL_CTX *ctx)
170 {
171         RSA *rsa;
172
173         rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
174
175         if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
176                 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
177                 return -1;
178         }
179
180         RSA_free(rsa);
181         return 0;
182 }
183
184
185 /*
186  *      These functions don't do anything other than print debugging
187  *      messages.
188  *
189  *      FIXME: Write sessions to some long-term storage, so that
190  *             session resumption can still occur after the server
191  *             restarts.
192  */
193 #define MAX_SESSION_SIZE (256)
194
195 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
196 {
197         size_t size;
198         char buffer[2 * MAX_SESSION_SIZE + 1];
199
200         size = sess->session_id_length;
201         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
202
203         fr_bin2hex(sess->session_id, buffer, size);
204
205         DEBUG2("  SSL: Removing session %s from the cache", buffer);
206         SSL_SESSION_free(sess);
207
208         return;
209 }
210
211 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
212 {
213         size_t size;
214         char buffer[2 * MAX_SESSION_SIZE + 1];
215
216         size = sess->session_id_length;
217         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
218
219         fr_bin2hex(sess->session_id, buffer, size);
220
221         DEBUG2("  SSL: adding session %s to cache", buffer);
222
223         return 1;
224 }
225
226 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
227                                       unsigned char *data, int len,
228                                       UNUSED int *copy)
229 {
230         size_t size;
231         char buffer[2 * MAX_SESSION_SIZE + 1];
232
233         size = len;
234         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
235
236         fr_bin2hex(data, buffer, size);
237
238         DEBUG2("  SSL: Client requested nonexistent cached session %s",
239                buffer);
240
241         return NULL;
242 }
243
244 #ifdef HAVE_OPENSSL_OCSP_H
245 /*
246  * This function extracts the OCSP Responder URL 
247  * from an existing x509 certificate.
248  */
249 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
250                                char **ppath, int *pssl)
251 {
252         int i;
253         
254         AUTHORITY_INFO_ACCESS *aia;
255         ACCESS_DESCRIPTION *ad;
256         
257         aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
258
259         for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
260                 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
261                 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
262                         if (ad->location->type == GEN_URI) {
263                                 if(OCSP_parse_url(ad->location->d.ia5->data, 
264                                         phost, pport, ppath, pssl))
265                                         return 1;
266                         }
267                 }
268         }
269         return 0;
270 }
271
272 /*
273  * This function sends a OCSP request to a defined OCSP responder
274  * and checks the OCSP response for correctness.
275  */
276 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
277                       EAP_TLS_CONF *conf)
278 {
279         OCSP_CERTID *certid;
280         OCSP_REQUEST *req;
281         OCSP_RESPONSE *resp;
282         OCSP_BASICRESP *bresp = NULL;
283         char *host = NULL;
284         char *port = NULL;
285         char *path = NULL;
286         int use_ssl = -1;
287         BIO *cbio;
288         int ocsp_ok;
289         int status;
290
291         /* 
292          * Create OCSP Request 
293          */
294         certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
295         req = OCSP_REQUEST_new();
296         OCSP_request_add0_id(req, certid);
297         OCSP_request_add1_nonce(req, NULL, 8);
298
299         /* 
300          * Send OCSP Request and get OCSP Response
301          */
302
303         /* Get OCSP responder URL */ 
304         if(conf->ocsp_override_url) {
305                 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
306         }
307         else {
308                 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
309         }
310         
311         DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
312
313         /* Setup BIO socket to OCSP responder */
314         cbio = BIO_new_connect(host);
315         BIO_set_conn_port(cbio, port);
316         BIO_do_connect(cbio);
317
318         /* Send OCSP request and wait for response */
319         resp = OCSP_sendreq_bio(cbio, path, req);
320         if(resp==0) {
321                 radlog(L_ERR, "Error: Couldn't get OCSP response");
322                 ocsp_ok = 0;
323                 goto ocsp_end;
324         }
325
326         /* Verify OCSP response */
327         status = OCSP_response_status(resp);
328         if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
329                 radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status));
330                 ocsp_ok = 0;
331                 goto ocsp_end;
332         }
333         bresp = OCSP_response_get1_basic(resp);
334         if(OCSP_check_nonce(req, bresp)!=1) {
335                 radlog(L_ERR, "Error: OCSP response has wrong nonce value");
336                 ocsp_ok = 0;
337                 goto ocsp_end;
338         }
339         if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
340                 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
341                 ocsp_ok = 0;
342                 goto ocsp_end;
343         }
344         
345         ocsp_ok = 1; 
346
347 ocsp_end:
348         /* Free OCSP Stuff */
349         OCSP_REQUEST_free(req);
350         OCSP_RESPONSE_free(resp);
351         free(host);
352         free(port);
353         free(path);
354         BIO_free_all(cbio);
355         OCSP_BASICRESP_free(bresp);
356
357         if(ocsp_ok)
358                 DEBUG2("[ocsp] --> Certificate is valid!");
359         else
360                 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
361
362         return ocsp_ok;
363 }
364 #endif  /* HAVE_OPENSSL_OCSP_H */
365
366 /*
367  *      For creating certificate attributes.
368  */
369 static const char *cert_attr_names[5][2] = {
370   { "TLS-Client-Cert-Serial",           "TLS-Cert-Serial" },
371   { "TLS-Client-Cert-Expiration",       "TLS-Cert-Expiration" },
372   { "TLS-Client-Cert-Subject",          "TLS-Cert-Subject" },
373   { "TLS-Client-Cert-Issuer",           "TLS-Cert-Issuer" },
374   { "TLS-Client-Cert-Common-Name",      "TLS-Cert-Common-Name" }
375 };
376
377 #define EAPTLS_SERIAL           (0)
378 #define EAPTLS_EXPIRATION       (1)
379 #define EAPTLS_SUBJECT          (2)
380 #define EAPTLS_ISSUER           (3)
381 #define EAPTLS_CN               (4)
382
383 /*
384  *      Before trusting a certificate, you must make sure that the
385  *      certificate is 'valid'. There are several steps that your
386  *      application can take in determining if a certificate is
387  *      valid. Commonly used steps are:
388  *
389  *      1.Verifying the certificate's signature, and verifying that
390  *      the certificate has been issued by a trusted Certificate
391  *      Authority.
392  *
393  *      2.Verifying that the certificate is valid for the present date
394  *      (i.e. it is being presented within its validity dates).
395  *
396  *      3.Verifying that the certificate has not been revoked by its
397  *      issuing Certificate Authority, by checking with respect to a
398  *      Certificate Revocation List (CRL).
399  *
400  *      4.Verifying that the credentials presented by the certificate
401  *      fulfill additional requirements specific to the application,
402  *      such as with respect to access control lists or with respect
403  *      to OCSP (Online Certificate Status Processing).
404  *
405  *      NOTE: This callback will be called multiple times based on the
406  *      depth of the root certificate chain
407  */
408 static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
409 {
410         char subject[1024]; /* Used for the subject name */
411         char issuer[1024]; /* Used for the issuer name */
412         char common_name[1024];
413         char cn_str[1024];
414         char buf[64];
415         EAP_HANDLER *handler = NULL;
416         X509 *client_cert;
417         X509 *issuer_cert;
418         SSL *ssl;
419         int err, depth, lookup;
420         EAP_TLS_CONF *conf;
421         int my_ok = ok;
422         REQUEST *request;
423         ASN1_INTEGER *sn = NULL;
424         ASN1_TIME *asn_time = NULL;
425 #ifdef HAVE_OPENSSL_OCSP_H
426         X509_STORE *ocsp_store = NULL;
427 #endif
428
429         client_cert = X509_STORE_CTX_get_current_cert(ctx);
430         err = X509_STORE_CTX_get_error(ctx);
431         depth = X509_STORE_CTX_get_error_depth(ctx);
432
433         lookup = depth;
434
435         /*
436          *      Log client/issuing cert.  If there's an error, log
437          *      issuing cert.
438          */
439         if ((lookup > 1) && !my_ok) lookup = 1;
440
441         /*
442          * Retrieve the pointer to the SSL of the connection currently treated
443          * and the application specific data stored into the SSL object.
444          */
445         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
446         handler = (EAP_HANDLER *)SSL_get_ex_data(ssl, 0);
447         request = handler->request;
448         conf = (EAP_TLS_CONF *)SSL_get_ex_data(ssl, 1);
449 #ifdef HAVE_OPENSSL_OCSP_H
450         ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, 2);
451 #endif
452
453
454         /*
455          *      Get the Serial Number
456          */
457         buf[0] = '\0';
458         sn = X509_get_serialNumber(client_cert);
459
460         /*
461          *      For this next bit, we create the attributes *only* if
462          *      we're at the client or issuing certificate.
463          */
464         if ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {
465                 char *p = buf;
466                 int i;
467
468                 for (i = 0; i < sn->length; i++) {
469                         sprintf(p, "%02x", (unsigned int)sn->data[i]);
470                         p += 2;
471                 }
472                 pairadd(&handler->certs,
473                         pairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));
474         }
475
476
477         /*
478          *      Get the Expiration Date
479          */
480         buf[0] = '\0';
481         asn_time = X509_get_notAfter(client_cert);
482         if ((lookup <= 1) && asn_time && (asn_time->length < MAX_STRING_LEN)) {
483                 memcpy(buf, (char*) asn_time->data, asn_time->length);
484                 buf[asn_time->length] = '\0';
485                 pairadd(&handler->certs,
486                         pairmake(cert_attr_names[EAPTLS_EXPIRATION][lookup], buf, T_OP_SET));
487         }
488
489         /*
490          *      Get the Subject & Issuer
491          */
492         subject[0] = issuer[0] = '\0';
493         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
494                           sizeof(subject));
495         subject[sizeof(subject) - 1] = '\0';
496         if ((lookup <= 1) && subject[0] && (strlen(subject) < MAX_STRING_LEN)) {
497                 pairadd(&handler->certs,
498                         pairmake(cert_attr_names[EAPTLS_SUBJECT][lookup], subject, T_OP_SET));
499         }
500
501         X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
502                           sizeof(issuer));
503         issuer[sizeof(issuer) - 1] = '\0';
504         if ((lookup <= 1) && issuer[0] && (strlen(issuer) < MAX_STRING_LEN)) {
505                 pairadd(&handler->certs,
506                         pairmake(cert_attr_names[EAPTLS_ISSUER][lookup], issuer, T_OP_SET));
507         }
508
509         /*
510          *      Get the Common Name
511          */
512         X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
513                                   NID_commonName, common_name, sizeof(common_name));
514         common_name[sizeof(common_name) - 1] = '\0';
515         if ((lookup <= 1) && common_name[0] && (strlen(common_name) < MAX_STRING_LEN)) {
516                 pairadd(&handler->certs,
517                         pairmake(cert_attr_names[EAPTLS_CN][lookup], common_name, T_OP_SET));
518         }
519
520         if (!my_ok) {
521                 const char *p = X509_verify_cert_error_string(err);
522                 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
523                 radius_pairmake(request, &request->packet->vps,
524                                 "Module-Failure-Message", p, T_OP_SET);
525                 return my_ok;
526         }
527
528         switch (ctx->error) {
529
530         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
531                 radlog(L_ERR, "issuer= %s\n", issuer);
532                 break;
533         case X509_V_ERR_CERT_NOT_YET_VALID:
534         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
535                 radlog(L_ERR, "notBefore=");
536 #if 0
537                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
538 #endif
539                 break;
540         case X509_V_ERR_CERT_HAS_EXPIRED:
541         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
542                 radlog(L_ERR, "notAfter=");
543 #if 0
544                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
545 #endif
546                 break;
547         }
548
549         /*
550          *      If we're at the actual client cert, apply additional
551          *      checks.
552          */
553         if (depth == 0) {
554                 /*
555                  *      If the conf tells us to, check cert issuer
556                  *      against the specified value and fail
557                  *      verification if they don't match.
558                  */
559                 if (conf->check_cert_issuer &&
560                     (strcmp(issuer, conf->check_cert_issuer) != 0)) {
561                         radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
562                         my_ok = 0;
563                 }
564
565                 /*
566                  *      If the conf tells us to, check the CN in the
567                  *      cert against xlat'ed value, but only if the
568                  *      previous checks passed.
569                  */
570                 if (my_ok && conf->check_cert_cn) {
571                         if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, handler->request, NULL)) {
572                                 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
573                                        conf->check_cert_cn);
574                                 /* if this fails, fail the verification */
575                                 my_ok = 0;
576                         } else {
577                                 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
578                                 if (strcmp(cn_str, common_name) != 0) {
579                                         radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
580                                         my_ok = 0;
581                                 }
582                         }
583                 } /* check_cert_cn */
584
585 #ifdef HAVE_OPENSSL_OCSP_H
586                 if (my_ok && conf->check_ocsp){
587                         RDEBUG2("--> Starting OCSP Request");
588                         if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
589                                 radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
590                         }
591                         my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
592                 }
593 #endif
594
595                 while (conf->verify_client_cert_cmd) {
596                         char filename[256];
597                         FILE *fp;
598
599                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
600                                  conf->verify_tmp_dir, progname);
601                         if (mkstemp(filename) < 0) {
602                                 RDEBUG("Failed creating file in %s: %s",
603                                        conf->verify_tmp_dir, strerror(errno));
604                                 break;                                 
605                         }
606
607                         fp = fopen(filename, "w");
608                         if (!fp) {
609                                 RDEBUG("Failed opening file %s: %s",
610                                        filename, strerror(errno));
611                                 break;
612                         }
613
614                         if (!PEM_write_X509(fp, client_cert)) {
615                                 fclose(fp);
616                                 RDEBUG("Failed writing certificate to file");
617                                 goto do_unlink;
618                         }
619                         fclose(fp);
620
621                         if (!radius_pairmake(request, &request->packet->vps,
622                                              "TLS-Client-Cert-Filename",
623                                              filename, T_OP_SET)) {
624                                 RDEBUG("Failed creating TLS-Client-Cert-Filename");
625                                 
626                                 goto do_unlink;
627                         }
628
629                         RDEBUG("Verifying client certificate: %s",
630                                conf->verify_client_cert_cmd);
631                         if (radius_exec_program(conf->verify_client_cert_cmd,
632                                                 request, 1, NULL, 0, 
633                                                 request->packet->vps,
634                                                 NULL, 1) != 0) {
635                                 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
636                                 my_ok = 0;
637                         } else {
638                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
639                         }
640
641                 do_unlink:
642                         unlink(filename);
643                         break;
644                 }
645
646
647         } /* depth == 0 */
648
649         if (debug_flag > 0) {
650                 RDEBUG2("chain-depth=%d, ", depth);
651                 RDEBUG2("error=%d", err);
652
653                 RDEBUG2("--> User-Name = %s", handler->identity);
654                 RDEBUG2("--> BUF-Name = %s", common_name);
655                 RDEBUG2("--> subject = %s", subject);
656                 RDEBUG2("--> issuer  = %s", issuer);
657                 RDEBUG2("--> verify return:%d", my_ok);
658         }
659         return my_ok;
660 }
661
662
663 /*
664  *      Free cached session data, which is always a list of VALUE_PAIRs
665  */
666 static void eaptls_session_free(UNUSED void *parent, void *data_ptr,
667                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
668                                 UNUSED long argl, UNUSED void *argp)
669 {
670         VALUE_PAIR *vp = data_ptr;
671         if (!data_ptr) return;
672
673         pairfree(&vp);
674 }
675
676 #ifdef HAVE_OPENSSL_OCSP_H
677 /*
678  *      Create Global X509 revocation store and use it to verify
679  *      OCSP responses
680  *
681  *      - Load the trusted CAs
682  *      - Load the trusted issuer certificates
683  */
684 static X509_STORE *init_revocation_store(EAP_TLS_CONF *conf)
685 {
686         X509_STORE *store = NULL;
687         
688         store = X509_STORE_new();
689
690         /* Load the CAs we trust */
691         if (conf->ca_file || conf->ca_path)
692                 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
693                         radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
694                         radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
695                         return NULL;
696                 }
697
698 #ifdef X509_V_FLAG_CRL_CHECK
699         if (conf->check_crl) 
700                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
701 #endif
702         return store;
703 }
704 #endif  /* HAVE_OPENSSL_OCSP_H */
705
706 /*
707  *      Create Global context SSL and use it in every new session
708  *
709  *      - Load the trusted CAs
710  *      - Load the Private key & the certificate
711  *      - Set the Context options & Verify options
712  */
713 static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
714 {
715         SSL_METHOD *meth;
716         SSL_CTX *ctx;
717         X509_STORE *certstore;
718         int verify_mode = SSL_VERIFY_NONE;
719         int ctx_options = 0;
720         int type;
721
722         /*
723          *      Add all the default ciphers and message digests
724          *      Create our context.
725          */
726         SSL_library_init();
727         SSL_load_error_strings();
728
729         /*
730          *      SHA256 is in all versions of OpenSSL, but isn't
731          *      initialized by default.  It's needed for WiMAX
732          *      certificates.
733          */
734 #ifdef HAVE_OPENSSL_EVP_SHA256
735         EVP_add_digest(EVP_sha256());
736 #endif
737
738         meth = TLSv1_method();
739         ctx = SSL_CTX_new(meth);
740
741         /*
742          * Identify the type of certificates that needs to be loaded
743          */
744         if (conf->file_type) {
745                 type = SSL_FILETYPE_PEM;
746         } else {
747                 type = SSL_FILETYPE_ASN1;
748         }
749
750         /*
751          * Set the password to load private key
752          */
753         if (conf->private_key_password) {
754 #ifdef __APPLE__
755                 /*
756                  * We don't want to put the private key password in eap.conf, so  check
757                  * for our special string which indicates we should get the password
758                  * programmatically. 
759                  */
760                 const char* special_string = "Apple:UseCertAdmin";
761                 if (strncmp(conf->private_key_password,
762                                         special_string,
763                                         strlen(special_string)) == 0)
764                 {
765                         char cmd[256];
766                         const long max_password_len = 128;
767                         snprintf(cmd, sizeof(cmd) - 1,
768                                          "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
769                                          conf->private_key_file);
770
771                         DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
772
773                         FILE* cmd_pipe = popen(cmd, "r");
774                         if (!cmd_pipe) {
775                                 radlog(L_ERR, "rlm_eap: %s command failed.      Unable to get private_key_password", cmd);
776                                 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
777                                 return NULL;
778                         }
779
780                         free(conf->private_key_password);
781                         conf->private_key_password = malloc(max_password_len * sizeof(char));
782                         if (!conf->private_key_password) {
783                                 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
784                                 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
785                                 pclose(cmd_pipe);
786                                 return NULL;
787                         }
788
789                         fgets(conf->private_key_password, max_password_len, cmd_pipe);
790                         pclose(cmd_pipe);
791
792                         /* Get rid of newline at end of password. */
793                         conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
794                         DEBUG2("rlm_eap:  Password from command = \"%s\"", conf->private_key_password);
795                 }
796 #endif
797                 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
798                 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
799         }
800
801         /*
802          *      Load our keys and certificates
803          *
804          *      If certificates are of type PEM then we can make use
805          *      of cert chain authentication using openssl api call
806          *      SSL_CTX_use_certificate_chain_file.  Please see how
807          *      the cert chain needs to be given in PEM from
808          *      openSSL.org
809          */
810         if (type == SSL_FILETYPE_PEM) {
811                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
812                         radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
813                         radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
814                         return NULL;
815                 }
816
817         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
818                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
819                 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
820                 return NULL;
821         }
822
823         /* Load the CAs we trust */
824         if (conf->ca_file || conf->ca_path) {
825                 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
826                         radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
827                         radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
828                         return NULL;
829                 }
830         }
831         if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
832         if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
833                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
834                 radlog(L_ERR, "rlm_eap_tls: Error reading private key file %s", conf->private_key_file);
835                 return NULL;
836         }
837
838         /*
839          * Check if the loaded private key is the right one
840          */
841         if (!SSL_CTX_check_private_key(ctx)) {
842                 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
843                 return NULL;
844         }
845
846         /*
847          *      Set ctx_options
848          */
849         ctx_options |= SSL_OP_NO_SSLv2;
850         ctx_options |= SSL_OP_NO_SSLv3;
851 #ifdef SSL_OP_NO_TICKET
852         ctx_options |= SSL_OP_NO_TICKET ;
853 #endif
854
855         /*
856          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
857          *      small subgroup attacks and forward secrecy. Always
858          *      using
859          *
860          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
861          *      time needed during negotiation, but it is not very
862          *      large.
863          */
864         ctx_options |= SSL_OP_SINGLE_DH_USE;
865
866         /*
867          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
868          *      in Windows Vista client.
869          *      http://www.openssl.org/~bodo/tls-cbc.txt
870          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
871          */
872         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
873
874         SSL_CTX_set_options(ctx, ctx_options);
875
876         /*
877          *      TODO: Set the RSA & DH
878          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
879          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
880          */
881
882         /*
883          *      set the message callback to identify the type of
884          *      message.  For every new session, there can be a
885          *      different callback argument.
886          *
887          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
888          */
889
890         /* Set Info callback */
891         SSL_CTX_set_info_callback(ctx, cbtls_info);
892
893         /*
894          *      Callbacks, etc. for session resumption.
895          */                                                   
896         if (conf->session_cache_enable) {
897                 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
898                 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
899                 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
900
901                 SSL_CTX_set_quiet_shutdown(ctx, 1);
902         }
903
904         /*
905          *      Check the certificates for revocation.
906          */
907 #ifdef X509_V_FLAG_CRL_CHECK
908         if (conf->check_crl) {
909           certstore = SSL_CTX_get_cert_store(ctx);
910           if (certstore == NULL) {
911             radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
912             radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
913             return NULL;
914           }
915           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
916         }
917 #endif
918
919         /*
920          *      Set verify modes
921          *      Always verify the peer certificate
922          */
923         verify_mode |= SSL_VERIFY_PEER;
924         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
925         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
926         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
927
928         if (conf->verify_depth) {
929                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
930         }
931
932         /* Load randomness */
933         if (!(RAND_load_file(conf->random_file, 1024*1024))) {
934                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
935                 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
936                 return NULL;
937         }
938
939         /*
940          * Set the cipher list if we were told to
941          */
942         if (conf->cipher_list) {
943                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
944                         radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
945                         return NULL;
946                 }
947         }
948
949         /*
950          *      Setup session caching
951          */
952         if (conf->session_cache_enable) {
953                 /*
954                  *      Create a unique context Id per EAP-TLS configuration.
955                  */
956                 if (conf->session_id_name) {
957                         snprintf(conf->session_context_id,
958                                  sizeof(conf->session_context_id),
959                                  "FreeRADIUS EAP-TLS %s",
960                                  conf->session_id_name);
961                 } else {
962                         snprintf(conf->session_context_id,
963                                  sizeof(conf->session_context_id),
964                                  "FreeRADIUS EAP-TLS %p", conf);
965                 }
966
967                 /*
968                  *      Cache it, and DON'T auto-clear it.
969                  */
970                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
971                                                
972                 SSL_CTX_set_session_id_context(ctx,
973                                                (unsigned char *) conf->session_context_id,
974                                                (unsigned int) strlen(conf->session_context_id));
975
976                 /*
977                  *      Our timeout is in hours, this is in seconds.
978                  */
979                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
980                 
981                 /*
982                  *      Set the maximum number of entries in the
983                  *      session cache.
984                  */
985                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
986
987         } else {
988                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
989         }
990
991         /*
992          *      Register the application indices.  We can't use
993          *      hard-coded "0" and "1" as before, because we need to
994          *      set up a "free" handler for the cached session
995          *      information.
996          */
997         if (eaptls_handle_idx < 0) {
998                 eaptls_handle_idx = SSL_get_ex_new_index(0, &eaptls_handle_idx,
999                                                          NULL, NULL, NULL);
1000         }
1001         
1002         if (eaptls_conf_idx < 0) {
1003                 eaptls_conf_idx = SSL_get_ex_new_index(0, &eaptls_conf_idx,
1004                                                           NULL, NULL, NULL);
1005         }
1006
1007         if (eaptls_store_idx < 0) {
1008                 eaptls_store_idx = SSL_get_ex_new_index(0, "eaptls_store_idx",
1009                                                           NULL, NULL, NULL);
1010         }
1011
1012         if (eaptls_session_idx < 0) {
1013                 eaptls_session_idx = SSL_get_ex_new_index(0, &eaptls_session_idx,
1014                                                           NULL, NULL,
1015                                                           eaptls_session_free);
1016         }
1017
1018         return ctx;
1019 }
1020
1021
1022 /*
1023  *      Detach the EAP-TLS module.
1024  */
1025 static int eaptls_detach(void *arg)
1026 {
1027         EAP_TLS_CONF     *conf;
1028         eap_tls_t        *inst;
1029
1030         inst = (eap_tls_t *) arg;
1031         conf = inst->conf;
1032
1033         if (conf) {
1034                 memset(conf, 0, sizeof(*conf));
1035                 free(inst->conf);
1036                 inst->conf = NULL;
1037         }
1038
1039         if (inst->ctx) SSL_CTX_free(inst->ctx);
1040         inst->ctx = NULL;
1041
1042         if (inst->store) X509_STORE_free(inst->store);
1043         inst->store = NULL;
1044
1045         free(inst);
1046
1047         return 0;
1048 }
1049
1050
1051 /*
1052  *      Attach the EAP-TLS module.
1053  */
1054 static int eaptls_attach(CONF_SECTION *cs, void **instance)
1055 {
1056         EAP_TLS_CONF     *conf;
1057         eap_tls_t        *inst;
1058
1059         /* Store all these values in the data structure for later references */
1060         inst = (eap_tls_t *)malloc(sizeof(*inst));
1061         if (!inst) {
1062                 radlog(L_ERR, "rlm_eap_tls: out of memory");
1063                 return -1;
1064         }
1065         memset(inst, 0, sizeof(*inst));
1066
1067         /*
1068          *      Parse the config file & get all the configured values
1069          */
1070         conf = (EAP_TLS_CONF *)malloc(sizeof(*conf));
1071         if (conf == NULL) {
1072                 free(inst);
1073                 radlog(L_ERR, "rlm_eap_tls: out of memory");
1074                 return -1;
1075         }
1076         memset(conf, 0, sizeof(*conf));
1077
1078         inst->conf = conf;
1079         if (cf_section_parse(cs, conf, module_config) < 0) {
1080                 eaptls_detach(inst);
1081                 return -1;
1082         }
1083
1084         /*
1085          *      The EAP RFC's say 1020, but we're less picky.
1086          */
1087         if (conf->fragment_size < 100) {
1088                 radlog(L_ERR, "rlm_eap_tls: Fragment size is too small.");
1089                 eaptls_detach(inst);
1090                 return -1;
1091         }
1092
1093         /*
1094          *      The maximum size for a RADIUS packet is 4096,
1095          *      minus the header (20), Message-Authenticator (18),
1096          *      and State (18), etc. results in about 4000 bytes of data
1097          *      that can be devoted *solely* to EAP.
1098          */
1099         if (conf->fragment_size > 4000) {
1100                 radlog(L_ERR, "rlm_eap_tls: Fragment size is too large.");
1101                 eaptls_detach(inst);
1102                 return -1;
1103         }
1104
1105         /*
1106          *      Account for the EAP header (4), and the EAP-TLS header
1107          *      (6), as per Section 4.2 of RFC 2716.  What's left is
1108          *      the maximum amount of data we read from a TLS buffer.
1109          */
1110         conf->fragment_size -= 10;
1111
1112         /*
1113          *      This magic makes the administrators life HUGELY easier
1114          *      on initial deployments.
1115          *
1116          *      If the server starts up in debugging mode, AND the
1117          *      bootstrap command is configured, AND it exists, AND
1118          *      there is no server certificate
1119          */
1120         if (conf->make_cert_command && (debug_flag >= 2)) {
1121                 struct stat buf;
1122
1123                 if ((stat(conf->make_cert_command, &buf) == 0) &&
1124                     (stat(conf->certificate_file, &buf) < 0) &&
1125                     (errno == ENOENT) &&
1126                     (radius_exec_program(conf->make_cert_command, NULL, 1,
1127                                          NULL, 0, NULL, NULL, 0) != 0)) {
1128                         eaptls_detach(inst);
1129                         return -1;
1130                 }
1131         }
1132
1133
1134         /*
1135          *      Initialize TLS
1136          */
1137         inst->ctx = init_tls_ctx(conf);
1138         if (inst->ctx == NULL) {
1139                 eaptls_detach(inst);
1140                 return -1;
1141         }
1142
1143 #ifdef HAVE_OPENSSL_OCSP_H
1144         /*
1145          *      Initialize OCSP Revocation Store
1146          */
1147         if (!conf->ocsp_url && !conf->ocsp_override_url) {
1148                 conf->check_ocsp = FALSE;
1149         } else {
1150                 inst->store = init_revocation_store(conf);
1151                 if (inst->store == NULL) {
1152                         eaptls_detach(inst);
1153                         return -1;
1154                 }
1155         }
1156 #endif HAVE_OPENSSL_OCSP_H
1157
1158         if (load_dh_params(inst->ctx, conf->dh_file) < 0) {
1159                 eaptls_detach(inst);
1160                 return -1;
1161         }
1162
1163         if (generate_eph_rsa_key(inst->ctx) < 0) {
1164                 eaptls_detach(inst);
1165                 return -1;
1166         }
1167
1168         if (conf->verify_tmp_dir) {
1169                 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
1170                         radlog(L_ERR, "rlm_eap_tls: Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
1171                         eaptls_detach(inst);
1172                         return -1;
1173                 }
1174         }
1175
1176         if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
1177                 radlog(L_ERR, "rlm_eap_tls: You MUST set the verify directory in order to use verify_client_cmd");
1178                 eaptls_detach(inst);
1179                 return -1;
1180         }
1181
1182         *instance = inst;
1183
1184         return 0;
1185 }
1186
1187
1188 /*
1189  *      Send an initial eap-tls request to the peer.
1190  *
1191  *      Frame eap reply packet.
1192  *      len = header + type + tls_typedata
1193  *      tls_typedata = flags(Start (S) bit set, and no data)
1194  *
1195  *      Once having received the peer's Identity, the EAP server MUST
1196  *      respond with an EAP-TLS/Start packet, which is an
1197  *      EAP-Request packet with EAP-Type=EAP-TLS, the Start (S) bit
1198  *      set, and no data.  The EAP-TLS conversation will then begin,
1199  *      with the peer sending an EAP-Response packet with
1200  *      EAP-Type = EAP-TLS.  The data field of that packet will
1201  *      be the TLS data.
1202  *
1203  *      Fragment length is Framed-MTU - 4.
1204  *
1205  *      http://mail.frascone.com/pipermail/public/eap/2003-July/001426.html
1206  */
1207 static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
1208 {
1209         int             status;
1210         tls_session_t   *ssn;
1211         eap_tls_t       *inst;
1212         VALUE_PAIR      *vp;
1213         int             client_cert = TRUE;
1214         int             verify_mode = 0;
1215         REQUEST         *request = handler->request;
1216
1217         inst = (eap_tls_t *)type_arg;
1218
1219         handler->tls = TRUE;
1220         handler->finished = FALSE;
1221
1222         /*
1223          *      Manually flush the sessions every so often.  If HALF
1224          *      of the session lifetime has passed since we last
1225          *      flushed, then flush it again.
1226          *
1227          *      FIXME: Also do it every N sessions?
1228          */
1229         if (inst->conf->session_cache_enable &&
1230             ((inst->conf->session_last_flushed + (inst->conf->session_timeout * 1800)) <= request->timestamp)) {
1231                 RDEBUG2("Flushing SSL sessions (of #%ld)",
1232                         SSL_CTX_sess_number(inst->ctx));
1233
1234                 SSL_CTX_flush_sessions(inst->ctx, request->timestamp);
1235                 inst->conf->session_last_flushed = request->timestamp;
1236         }
1237
1238         /*
1239          *      If we're TTLS or PEAP, then do NOT require a client
1240          *      certificate.
1241          *
1242          *      FIXME: This should be more configurable.
1243          */
1244         if (handler->eap_type != PW_EAP_TLS) {
1245                 vp = pairfind(handler->request->config_items,
1246                               PW_EAP_TLS_REQUIRE_CLIENT_CERT, 0);
1247                 if (!vp) {
1248                         client_cert = FALSE;
1249                 } else {
1250                         client_cert = vp->vp_integer;
1251                 }
1252         }
1253
1254         /*
1255          *      Every new session is started only from EAP-TLS-START.
1256          *      Before Sending EAP-TLS-START, open a new SSL session.
1257          *      Create all the required data structures & store them
1258          *      in Opaque.  So that we can use these data structures
1259          *      when we get the response
1260          */
1261         ssn = eaptls_new_session(inst->ctx, client_cert);
1262         if (!ssn) {
1263                 return 0;
1264         }
1265
1266         /*
1267          *      Verify the peer certificate, if asked.
1268          */
1269         if (client_cert) {
1270                 RDEBUG2("Requiring client certificate");
1271                 verify_mode = SSL_VERIFY_PEER;
1272                 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1273                 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1274         }
1275         SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
1276
1277         /*
1278          *      Create a structure for all the items required to be
1279          *      verified for each client and set that as opaque data
1280          *      structure.
1281          *
1282          *      NOTE: If we want to set each item sepearately then
1283          *      this index should be global.
1284          */
1285         SSL_set_ex_data(ssn->ssl, 0, (void *)handler);
1286         SSL_set_ex_data(ssn->ssl, 1, (void *)inst->conf);
1287         SSL_set_ex_data(ssn->ssl, 2, (void *)inst->store);
1288
1289         ssn->length_flag = inst->conf->include_length;
1290
1291         /*
1292          *      We use default fragment size, unless the Framed-MTU
1293          *      tells us it's too big.  Note that we do NOT account
1294          *      for the EAP-TLS headers if conf->fragment_size is
1295          *      large, because that config item looks to be confusing.
1296          *
1297          *      i.e. it should REALLY be called MTU, and the code here
1298          *      should figure out what that means for TLS fragment size.
1299          *      asking the administrator to know the internal details
1300          *      of EAP-TLS in order to calculate fragment sizes is
1301          *      just too much.
1302          */
1303         ssn->offset = inst->conf->fragment_size;
1304         vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU, 0);
1305         if (vp && ((vp->vp_integer - 14) < ssn->offset)) {
1306                 /*
1307                  *      Discount the Framed-MTU by:
1308                  *       4 : EAPOL header
1309                  *       4 : EAP header (code + id + length)
1310                  *       1 : EAP type == EAP-TLS
1311                  *       1 : EAP-TLS Flags
1312                  *       4 : EAP-TLS Message length
1313                  *          (even if conf->include_length == 0,
1314                  *           just to be lazy).
1315                  *      ---
1316                  *      14
1317                  */
1318                 ssn->offset = vp->vp_integer - 14;
1319         }
1320
1321         handler->opaque = ((void *)ssn);
1322         handler->free_opaque = session_free;
1323
1324         RDEBUG2("Initiate");
1325
1326         /*
1327          *      Set up type-specific information.
1328          */
1329         switch (handler->eap_type) {
1330         case PW_EAP_TLS:
1331         default:
1332                 ssn->prf_label = "client EAP encryption";
1333                 break;
1334
1335         case PW_EAP_TTLS:
1336                 ssn->prf_label = "ttls keying material";
1337                 break;
1338
1339                 /*
1340                  *      PEAP-specific breakage.
1341                  */
1342         case PW_EAP_PEAP:
1343                 /*
1344                  *      As it is a poorly designed protocol, PEAP uses
1345                  *      bits in the TLS header to indicate PEAP
1346                  *      version numbers.  For now, we only support
1347                  *      PEAP version 0, so it doesn't matter too much.
1348                  *      However, if we support later versions of PEAP,
1349                  *      we will need this flag to indicate which
1350                  *      version we're currently dealing with.
1351                  */
1352                 ssn->peap_flag = 0x00;
1353
1354                 /*
1355                  *      PEAP version 0 requires 'include_length = no',
1356                  *      so rather than hoping the user figures it out,
1357                  *      we force it here.
1358                  */
1359                 ssn->length_flag = 0;
1360
1361                 ssn->prf_label = "client EAP encryption";
1362                 break;
1363         }
1364
1365         if (inst->conf->session_cache_enable) {
1366                 ssn->allow_session_resumption = 1; /* otherwise it's zero */
1367         }
1368
1369         /*
1370          *      TLS session initialization is over.  Now handle TLS
1371          *      related handshaking or application data.
1372          */
1373         status = eaptls_start(handler->eap_ds, ssn->peap_flag);
1374         RDEBUG2("Start returned %d", status);
1375         if (status == 0)
1376                 return 0;
1377
1378         /*
1379          *      The next stage to process the packet.
1380          */
1381         handler->stage = AUTHENTICATE;
1382
1383         return 1;
1384 }
1385
1386 /*
1387  *      Do authentication, by letting EAP-TLS do most of the work.
1388  */
1389 static int eaptls_authenticate(void *arg, EAP_HANDLER *handler)
1390 {
1391         eaptls_status_t status;
1392         tls_session_t *tls_session = (tls_session_t *) handler->opaque;
1393         REQUEST *request = handler->request;
1394         eap_tls_t *inst = (eap_tls_t *) arg;
1395
1396         RDEBUG2("Authenticate");
1397
1398         status = eaptls_process(handler);
1399         RDEBUG2("eaptls_process returned %d\n", status);
1400         switch (status) {
1401                 /*
1402                  *      EAP-TLS handshake was successful, return an
1403                  *      EAP-TLS-Success packet here.
1404                  */
1405         case EAPTLS_SUCCESS:
1406                 break;
1407
1408                 /*
1409                  *      The TLS code is still working on the TLS
1410                  *      exchange, and it's a valid TLS request.
1411                  *      do nothing.
1412                  */
1413         case EAPTLS_HANDLED:
1414                 return 1;
1415
1416                 /*
1417                  *      Handshake is done, proceed with decoding tunneled
1418                  *      data.
1419                  */
1420         case EAPTLS_OK:
1421                 RDEBUG2("Received unexpected tunneled data after successful handshake.");
1422 #ifndef NDEBUG
1423                 if ((debug_flag > 2) && fr_log_fp) {
1424                         unsigned int i;
1425                         unsigned int data_len;
1426                         unsigned char buffer[1024];
1427
1428                         data_len = (tls_session->record_minus)(&tls_session->dirty_in,
1429                                                 buffer, sizeof(buffer));
1430                         log_debug("  Tunneled data (%u bytes)\n", data_len);
1431                         for (i = 0; i < data_len; i++) {
1432                                 if ((i & 0x0f) == 0x00) fprintf(fr_log_fp, "  %x: ", i);
1433                                 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
1434
1435                                 fprintf(fr_log_fp, "%02x ", buffer[i]);
1436                         }
1437                         fprintf(fr_log_fp, "\n");
1438                 }
1439 #endif
1440
1441                 eaptls_fail(handler, 0);
1442                 return 0;
1443                 break;
1444
1445                 /*
1446                  *      Anything else: fail.
1447                  *
1448                  *      Also, remove the session from the cache so that
1449                  *      the client can't re-use it.
1450                  */
1451         default:
1452                 if (inst->conf->session_cache_enable) { 
1453                         SSL_CTX_remove_session(inst->ctx,
1454                                                tls_session->ssl->session);
1455                 }
1456
1457                 return 0;
1458         }
1459
1460         /*
1461          *      New sessions cause some additional information to be
1462          *      cached.
1463          */
1464         if (!SSL_session_reused(tls_session->ssl)) {
1465                 /*
1466                  *      FIXME: Store miscellaneous data.
1467                  */
1468                 RDEBUG2("Adding user data to cached session");
1469                 
1470 #if 0
1471                 SSL_SESSION_set_ex_data(tls_session->ssl->session,
1472                                         ssl_session_idx_user_session, session_data);
1473 #endif
1474         } else {
1475                 /*
1476                  *      FIXME: Retrieve miscellaneous data.
1477                  */
1478 #if 0
1479                 data = SSL_SESSION_get_ex_data(tls_session->ssl->session,
1480                                                ssl_session_idx_user_session);
1481
1482                 if (!session_data) {
1483                         radlog_request(L_ERR, 0, request,
1484                                        "No user session data in cached session - "
1485                                        " REJECTING");
1486                         return 0;
1487                 }
1488 #endif
1489
1490                 RDEBUG2("Retrieved session data from cached session");
1491         }
1492
1493         /*
1494          *      Success: Automatically return MPPE keys.
1495          */
1496         return eaptls_success(handler, 0);
1497 }
1498
1499 /*
1500  *      The module name should be the only globally exported symbol.
1501  *      That is, everything else should be 'static'.
1502  */
1503 EAP_TYPE rlm_eap_tls = {
1504         "eap_tls",
1505         eaptls_attach,                  /* attach */
1506         eaptls_initiate,                /* Start the initial request */
1507         NULL,                           /* authorization */
1508         eaptls_authenticate,            /* authentication */
1509         eaptls_detach                   /* detach */
1510 };