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