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