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