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