dda85a7163a55a17eb825a778ca1750858b76126
[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 module_config[] = {
42         { "rsa_key_exchange", PW_TYPE_BOOLEAN,
43           offsetof(EAP_TLS_CONF, rsa_key), NULL, "no" },
44         { "dh_key_exchange", PW_TYPE_BOOLEAN,
45           offsetof(EAP_TLS_CONF, dh_key), NULL, "yes" },
46         { "rsa_key_length", PW_TYPE_INTEGER,
47           offsetof(EAP_TLS_CONF, rsa_key_length), NULL, "512" },
48         { "dh_key_length", PW_TYPE_INTEGER,
49           offsetof(EAP_TLS_CONF, dh_key_length), NULL, "512" },
50         { "verify_depth", PW_TYPE_INTEGER,
51           offsetof(EAP_TLS_CONF, verify_depth), NULL, "0" },
52         { "CA_path", PW_TYPE_FILENAME,
53           offsetof(EAP_TLS_CONF, ca_path), NULL, NULL },
54         { "pem_file_type", PW_TYPE_BOOLEAN,
55           offsetof(EAP_TLS_CONF, file_type), NULL, "yes" },
56         { "private_key_file", PW_TYPE_FILENAME,
57           offsetof(EAP_TLS_CONF, private_key_file), NULL, NULL },
58         { "certificate_file", PW_TYPE_FILENAME,
59           offsetof(EAP_TLS_CONF, certificate_file), NULL, NULL },
60         { "CA_file", PW_TYPE_FILENAME,
61           offsetof(EAP_TLS_CONF, ca_file), NULL, NULL },
62         { "private_key_password", PW_TYPE_STRING_PTR,
63           offsetof(EAP_TLS_CONF, private_key_password), NULL, NULL },
64         { "dh_file", PW_TYPE_STRING_PTR,
65           offsetof(EAP_TLS_CONF, dh_file), NULL, NULL },
66         { "random_file", PW_TYPE_STRING_PTR,
67           offsetof(EAP_TLS_CONF, random_file), NULL, NULL },
68         { "fragment_size", PW_TYPE_INTEGER,
69           offsetof(EAP_TLS_CONF, fragment_size), NULL, "1024" },
70         { "include_length", PW_TYPE_BOOLEAN,
71           offsetof(EAP_TLS_CONF, include_length), NULL, "yes" },
72         { "check_crl", PW_TYPE_BOOLEAN,
73           offsetof(EAP_TLS_CONF, check_crl), NULL, "no"},
74         { "check_cert_cn", PW_TYPE_STRING_PTR,
75           offsetof(EAP_TLS_CONF, check_cert_cn), NULL, NULL},
76         { "cipher_list", PW_TYPE_STRING_PTR,
77           offsetof(EAP_TLS_CONF, cipher_list), NULL, NULL},
78         { "check_cert_issuer", PW_TYPE_STRING_PTR,
79           offsetof(EAP_TLS_CONF, check_cert_issuer), NULL, NULL},
80         { "make_cert_command", PW_TYPE_STRING_PTR,
81           offsetof(EAP_TLS_CONF, make_cert_command), NULL, NULL},
82
83         { NULL, -1, 0, NULL, NULL }           /* end the list */
84 };
85
86
87 /*
88  *      TODO: Check for the type of key exchange * like conf->dh_key
89  */
90 static int load_dh_params(SSL_CTX *ctx, char *file)
91 {
92         DH *dh = NULL;
93         BIO *bio;
94
95         if ((bio = BIO_new_file(file, "r")) == NULL) {
96                 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
97                 return -1;
98         }
99
100         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
101         BIO_free(bio);
102         if (!dh) {
103                 radlog(L_INFO, "WARNING: rlm_eap_tls: Unable to set DH parameters.  DH cipher suites may not work!");
104                 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
105                 return 0;
106         }
107
108         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
109                 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
110                 DH_free(dh);
111                 return -1;
112         }
113
114         DH_free(dh);
115         return 0;
116 }
117
118 /*
119  *      Generte ephemeral RSA keys.
120  */
121 static int generate_eph_rsa_key(SSL_CTX *ctx)
122 {
123         RSA *rsa;
124
125         rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
126
127         if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
128                 radlog(L_ERR, "rlm_eap_tls: Couldn't set RSA key");
129                 return -1;
130         }
131
132         RSA_free(rsa);
133         return 0;
134 }
135
136
137 /*
138  *      Before trusting a certificate, you must make sure that the
139  *      certificate is 'valid'. There are several steps that your
140  *      application can take in determining if a certificate is
141  *      valid. Commonly used steps are:
142  *
143  *      1.Verifying the certificate's signature, and verifying that
144  *      the certificate has been issued by a trusted Certificate
145  *      Authority.
146  *
147  *      2.Verifying that the certificate is valid for the present date
148  *      (i.e. it is being presented within its validity dates).
149  *
150  *      3.Verifying that the certificate has not been revoked by its
151  *      issuing Certificate Authority, by checking with respect to a
152  *      Certificate Revocation List (CRL).
153  *
154  *      4.Verifying that the credentials presented by the certificate
155  *      fulfill additional requirements specific to the application,
156  *      such as with respect to access control lists or with respect
157  *      to OCSP (Online Certificate Status Processing).
158  *
159  *      NOTE: This callback will be called multiple times based on the
160  *      depth of the root certificate chain
161  */
162 static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
163 {
164         char subject[1024]; /* Used for the subject name */
165         char issuer[1024]; /* Used for the issuer name */
166         char common_name[1024];
167         char cn_str[1024];
168         EAP_HANDLER *handler = NULL;
169         X509 *client_cert;
170         SSL *ssl;
171         int err, depth;
172         EAP_TLS_CONF *conf;
173         int my_ok = ok;
174
175         client_cert = X509_STORE_CTX_get_current_cert(ctx);
176         err = X509_STORE_CTX_get_error(ctx);
177         depth = X509_STORE_CTX_get_error_depth(ctx);
178
179         if (!my_ok) {
180                 radlog(L_ERR,"--> verify error:num=%d:%s\n",err,
181                         X509_verify_cert_error_string(err));
182                 return my_ok;
183         }
184
185         /*
186          * Retrieve the pointer to the SSL of the connection currently treated
187          * and the application specific data stored into the SSL object.
188          */
189         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
190         handler = (EAP_HANDLER *)SSL_get_ex_data(ssl, 0);
191         conf = (EAP_TLS_CONF *)SSL_get_ex_data(ssl, 1);
192
193         /*
194          *      Get the Subject & Issuer
195          */
196         subject[0] = issuer[0] = '\0';
197         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
198                           sizeof(subject));
199         X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
200                           sizeof(issuer));
201
202         subject[sizeof(subject) - 1] = '\0';
203         issuer[sizeof(issuer) - 1] = '\0';
204
205         /*
206          *      Get the Common Name
207          */
208         X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
209                                   NID_commonName, common_name, sizeof(common_name));
210         common_name[sizeof(common_name) - 1] = '\0';
211
212         switch (ctx->error) {
213
214         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
215                 radlog(L_ERR, "issuer= %s\n", issuer);
216                 break;
217         case X509_V_ERR_CERT_NOT_YET_VALID:
218         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
219                 radlog(L_ERR, "notBefore=");
220 #if 0
221                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
222 #endif
223                 break;
224         case X509_V_ERR_CERT_HAS_EXPIRED:
225         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
226                 radlog(L_ERR, "notAfter=");
227 #if 0
228                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
229 #endif
230                 break;
231         }
232
233         /*
234          *      If we're at the actual client cert, apply additional
235          *      checks.
236          */
237         if (depth == 0) {
238                 /*
239                  *      If the conf tells us to, check cert issuer
240                  *      against the specified value and fail
241                  *      verification if they don't match.
242                  */
243                 if (conf->check_cert_issuer && 
244                     (strcmp(issuer, conf->check_cert_issuer) != 0)) {
245                         radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
246                         my_ok = 0;
247                 }
248
249                 /*
250                  *      If the conf tells us to, check the CN in the
251                  *      cert against xlat'ed value, but only if the
252                  *      previous checks passed.
253                  */
254                 if (my_ok && conf->check_cert_cn) {
255                         if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, handler->request, NULL)) {
256                                 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
257                                        conf->check_cert_cn);
258                                 /* if this fails, fail the verification */
259                                 my_ok = 0;
260                         } else {
261                                 DEBUG2("    rlm_eap_tls: checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
262                                 if (strcmp(cn_str, common_name) != 0) {
263                                         radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
264                                         my_ok = 0;
265                                 }
266                         }
267                 } /* check_cert_cn */
268         } /* depth == 0 */
269
270         if (debug_flag > 0) {
271                 radlog(L_INFO, "chain-depth=%d, ", depth);
272                 radlog(L_INFO, "error=%d", err);
273
274                 radlog(L_INFO, "--> User-Name = %s", handler->identity);
275                 radlog(L_INFO, "--> BUF-Name = %s", common_name);
276                 radlog(L_INFO, "--> subject = %s", subject);
277                 radlog(L_INFO, "--> issuer  = %s", issuer);
278                 radlog(L_INFO, "--> verify return:%d", my_ok);
279         }
280         return my_ok;
281 }
282
283
284 /*
285  *      Create Global context SSL and use it in every new session
286  *
287  *      - Load the trusted CAs
288  *      - Load the Private key & the certificate
289  *      - Set the Context options & Verify options
290  */
291 static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
292 {
293         SSL_METHOD *meth;
294         SSL_CTX *ctx;
295         X509_STORE *certstore;
296         int verify_mode = SSL_VERIFY_NONE;
297         int ctx_options = 0;
298         int type;
299
300         /*
301          *      Add all the default ciphers and message digests
302          *      Create our context.
303          */
304         SSL_library_init();
305         SSL_load_error_strings();
306
307         meth = TLSv1_method();
308         ctx = SSL_CTX_new(meth);
309
310         /*
311          * Identify the type of certificates that needs to be loaded
312          */
313         if (conf->file_type) {
314                 type = SSL_FILETYPE_PEM;
315         } else {
316                 type = SSL_FILETYPE_ASN1;
317         }
318
319         /*
320          * Set the password to load private key
321          */
322         if (conf->private_key_password) {
323                 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
324                 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
325         }
326
327         /*
328          *      Load our keys and certificates
329          *
330          *      If certificates are of type PEM then we can make use
331          *      of cert chain authentication using openssl api call
332          *      SSL_CTX_use_certificate_chain_file.  Please see how
333          *      the cert chain needs to be given in PEM from
334          *      openSSL.org
335          */
336         if (type == SSL_FILETYPE_PEM) {
337                 radlog(L_INFO, "rlm_eap_tls: Loading the certificate file as a chain");
338                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
339                         radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
340                         radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
341                         return NULL;
342                 }
343
344         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
345                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
346                 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
347                 return NULL;
348         }
349
350         /* Load the CAs we trust */
351         if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
352                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
353                 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
354                 return NULL;
355         }
356         SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
357         if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
358                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
359                 radlog(L_ERR, "rlm_eap_tls: Error reading private key file %s", conf->private_key_file);
360                 return NULL;
361         }
362
363         /*
364          * Check if the loaded private key is the right one
365          */
366         if (!SSL_CTX_check_private_key(ctx)) {
367                 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
368                 return NULL;
369         }
370
371         /*
372          *      Set ctx_options
373          */
374         ctx_options |= SSL_OP_NO_SSLv2;
375         ctx_options |= SSL_OP_NO_SSLv3;
376
377         /*
378          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
379          *      small subgroup attacks and forward secrecy. Always
380          *      using
381          *
382          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
383          *      time needed during negotiation, but it is not very
384          *      large.
385          */
386         ctx_options |= SSL_OP_SINGLE_DH_USE;
387
388         /*       
389          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
390          *      in Windows Vista client.
391          *      http://www.openssl.org/~bodo/tls-cbc.txt
392          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
393          */
394         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
395
396         SSL_CTX_set_options(ctx, ctx_options);
397
398         /*
399          *      TODO: Set the RSA & DH
400          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
401          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
402          */
403
404         /*
405          *      set the message callback to identify the type of
406          *      message.  For every new session, there can be a
407          *      different callback argument.
408          *
409          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
410          */
411
412         /* Set Info callback */
413         SSL_CTX_set_info_callback(ctx, cbtls_info);
414
415         /*
416          *      Check the certificates for revocation.
417          */
418 #ifdef X509_V_FLAG_CRL_CHECK
419         if (conf->check_crl) {
420           certstore = SSL_CTX_get_cert_store(ctx);
421           if (certstore == NULL) {
422             radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
423             radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
424             return NULL;
425           }
426           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
427         }
428 #endif
429
430         /*
431          *      Set verify modes
432          *      Always verify the peer certificate
433          */
434         verify_mode |= SSL_VERIFY_PEER;
435         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
436         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
437         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
438
439         if (conf->verify_depth) {
440                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
441         }
442
443         /* Load randomness */
444         if (!(RAND_load_file(conf->random_file, 1024*1024))) {
445                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
446                 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
447                 return NULL;
448         }
449
450         /*
451          * Set the cipher list if we were told to
452          */
453         if (conf->cipher_list) {
454                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
455                         radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
456                         return NULL;
457                 }
458         }
459
460         return ctx;
461 }
462
463
464 /*
465  *      Detach the EAP-TLS module.
466  */
467 static int eaptls_detach(void *arg)
468 {
469         EAP_TLS_CONF     *conf;
470         eap_tls_t        *inst;
471
472         inst = (eap_tls_t *) arg;
473         conf = inst->conf;
474
475         if (conf) {
476                 memset(conf, 0, sizeof(*conf));
477                 free(inst->conf);
478                 inst->conf = NULL;
479         }
480
481         if (inst->ctx) SSL_CTX_free(inst->ctx);
482         inst->ctx = NULL;
483
484         free(inst);
485
486         return 0;
487 }
488
489
490 /*
491  *      Attach the EAP-TLS module.
492  */
493 static int eaptls_attach(CONF_SECTION *cs, void **instance)
494 {
495         EAP_TLS_CONF     *conf;
496         eap_tls_t        *inst;
497
498         /* Store all these values in the data structure for later references */
499         inst = (eap_tls_t *)malloc(sizeof(*inst));
500         if (!inst) {
501                 radlog(L_ERR, "rlm_eap_tls: out of memory");
502                 return -1;
503         }
504         memset(inst, 0, sizeof(*inst));
505
506         /*
507          *      Parse the config file & get all the configured values
508          */
509         conf = (EAP_TLS_CONF *)malloc(sizeof(*conf));
510         if (conf == NULL) {
511                 radlog(L_ERR, "rlm_eap_tls: out of memory");
512                 return -1;
513         }
514         memset(conf, 0, sizeof(*conf));
515
516         inst->conf = conf;
517         if (cf_section_parse(cs, conf, module_config) < 0) {
518                 eaptls_detach(inst);
519                 return -1;
520         }
521
522         /*
523          *      This magic makes the administrators life HUGELY easier
524          *      on initial deployments.
525          *
526          *      If the server starts up in debugging mode, AND the
527          *      bootstrap command is configured, AND it exists, AND
528          *      there is no server certificate
529          */
530         if ((conf->make_cert_command && (debug_flag >= 2)) {
531                 struct stat buf;
532                 
533                 if ((stat(conf->make_cert_command, &buf) == 0) &&
534                     (stat(conf->certificate_file, &buf) < 0) &&
535                     (errno == ENOENT) &&
536                     (radius_exec_program(conf->make_cert_command, NULL, 1,
537                                          NULL, 0, NULL, NULL, 0) != 0)) {
538                         eaptls_detach(inst);
539                         return -1;
540                 }
541         }
542
543
544         /*
545          *      Initialize TLS
546          */
547         inst->ctx = init_tls_ctx(conf);
548         if (inst->ctx == NULL) {
549                 eaptls_detach(inst);
550                 return -1;
551         }
552
553         if (load_dh_params(inst->ctx, conf->dh_file) < 0) {
554                 eaptls_detach(inst);
555                 return -1;
556         }
557         if (generate_eph_rsa_key(inst->ctx) < 0) {
558                 eaptls_detach(inst);
559                 return -1;
560         }
561
562         *instance = inst;
563
564         return 0;
565 }
566
567
568 /*
569  *      Send an initial eap-tls request to the peer.
570  *
571  *      Frame eap reply packet.
572  *      len = header + type + tls_typedata
573  *      tls_typedata = flags(Start (S) bit set, and no data)
574  *
575  *      Once having received the peer's Identity, the EAP server MUST
576  *      respond with an EAP-TLS/Start packet, which is an
577  *      EAP-Request packet with EAP-Type=EAP-TLS, the Start (S) bit
578  *      set, and no data.  The EAP-TLS conversation will then begin,
579  *      with the peer sending an EAP-Response packet with
580  *      EAP-Type = EAP-TLS.  The data field of that packet will
581  *      be the TLS data.
582  *
583  *      Fragment length is Framed-MTU - 4.
584  *
585  *      http://mail.frascone.com/pipermail/public/eap/2003-July/001426.html
586  */
587 static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
588 {
589         int             status;
590         tls_session_t   *ssn;
591         eap_tls_t       *inst;
592         VALUE_PAIR      *vp;
593         int             client_cert = TRUE;
594         int             verify_mode = 0;
595
596         inst = (eap_tls_t *)type_arg;
597
598         /*
599          *      If we're TTLS or PEAP, then do NOT require a client
600          *      certificate.
601          *
602          *      FIXME: This should be more configurable.
603          */
604         if (handler->eap_type != PW_EAP_TLS) {
605                 vp = pairfind(handler->request->config_items,
606                               PW_EAP_TLS_REQUIRE_CLIENT_CERT);
607                 if (!vp) {
608                         client_cert = FALSE;
609                 } else {
610                         client_cert = vp->vp_integer;
611                 }
612         }
613
614         /*
615          *      Every new session is started only from EAP-TLS-START.
616          *      Before Sending EAP-TLS-START, open a new SSL session.
617          *      Create all the required data structures & store them
618          *      in Opaque.  So that we can use these data structures
619          *      when we get the response
620          */
621         ssn = eaptls_new_session(inst->ctx, client_cert);
622         if (!ssn) {
623                 return 0;
624         }
625
626         /*
627          *      Verify the peer certificate, if asked.
628          */
629         if (client_cert) {
630                 DEBUG2(" rlm_eap_tls: Requiring client certificate");
631                 verify_mode = SSL_VERIFY_PEER;
632                 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
633                 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
634         }
635         SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
636
637         /*
638          *      Create a structure for all the items required to be
639          *      verified for each client and set that as opaque data
640          *      structure.
641          *
642          *      NOTE: If we want to set each item sepearately then
643          *      this index should be global.
644          */
645         SSL_set_ex_data(ssn->ssl, 0, (void *)handler);
646         SSL_set_ex_data(ssn->ssl, 1, (void *)inst->conf);
647
648         ssn->length_flag = inst->conf->include_length;
649
650         /*
651          *      We use default fragment size, unless the Framed-MTU
652          *      tells us it's too big.  Note that we do NOT account
653          *      for the EAP-TLS headers if conf->fragment_size is
654          *      large, because that config item looks to be confusing.
655          *
656          *      i.e. it should REALLY be called MTU, and the code here
657          *      should figure out what that means for TLS fragment size.
658          *      asking the administrator to know the internal details
659          *      of EAP-TLS in order to calculate fragment sizes is
660          *      just too much.
661          */
662         ssn->offset = inst->conf->fragment_size;
663         vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU);
664         if (vp && ((vp->vp_integer - 14) < ssn->offset)) {
665                 /*
666                  *      Discount the Framed-MTU by:
667                  *       4 : EAPOL header
668                  *       4 : EAP header (code + id + length)
669                  *       1 : EAP type == EAP-TLS
670                  *       1 : EAP-TLS Flags
671                  *       4 : EAP-TLS Message length
672                  *          (even if conf->include_length == 0,
673                  *           just to be lazy).
674                  *      ---
675                  *      14
676                  */
677                 ssn->offset = vp->vp_integer - 14;
678         }
679
680         handler->opaque = ((void *)ssn);
681         handler->free_opaque = session_free;
682
683         DEBUG2("  rlm_eap_tls: Initiate");
684
685         /*
686          *      PEAP-specific breakage.
687          */
688         if (handler->eap_type == PW_EAP_PEAP) {
689                 /*
690                  *      As it is a poorly designed protocol, PEAP uses
691                  *      bits in the TLS header to indicate PEAP
692                  *      version numbers.  For now, we only support
693                  *      PEAP version 0, so it doesn't matter too much.
694                  *      However, if we support later versions of PEAP,
695                  *      we will need this flag to indicate which
696                  *      version we're currently dealing with.
697                  */
698                 ssn->peap_flag = 0x00;
699
700                 /*
701                  *      PEAP version 0 requires 'include_length = no',
702                  *      so rather than hoping the user figures it out,
703                  *      we force it here.
704                  */
705                 ssn->length_flag = 0;
706         }
707
708         /*
709          *      TLS session initialization is over.  Now handle TLS
710          *      related handshaking or application data.
711          */
712         status = eaptls_start(handler->eap_ds, ssn->peap_flag);
713         DEBUG2("  rlm_eap_tls: Start returned %d", status);
714         if (status == 0)
715                 return 0;
716
717         /*
718          *      The next stage to process the packet.
719          */
720         handler->stage = AUTHENTICATE;
721
722         return 1;
723 }
724
725 /*
726  *      Do authentication, by letting EAP-TLS do most of the work.
727  */
728 static int eaptls_authenticate(void *arg UNUSED, EAP_HANDLER *handler)
729 {
730         eaptls_status_t status;
731         tls_session_t *tls_session = (tls_session_t *) handler->opaque;
732
733         DEBUG2("  rlm_eap_tls: Authenticate");
734
735         status = eaptls_process(handler);
736         DEBUG2("  eaptls_process returned %d\n", status);
737         switch (status) {
738                 /*
739                  *      EAP-TLS handshake was successful, return an
740                  *      EAP-TLS-Success packet here.
741                  */
742         case EAPTLS_SUCCESS:
743                 break;
744
745                 /*
746                  *      The TLS code is still working on the TLS
747                  *      exchange, and it's a valid TLS request.
748                  *      do nothing.
749                  */
750         case EAPTLS_HANDLED:
751                 return 1;
752
753                 /*
754                  *      Handshake is done, proceed with decoding tunneled
755                  *      data.
756                  */
757         case EAPTLS_OK:
758                 DEBUG2("  rlm_eap_tls: Received unexpected tunneled data after successful handshake.");
759 #ifndef NDEBUG
760                 if (debug_flag > 2) {
761                         unsigned int i;
762                         unsigned int data_len;
763                         unsigned char buffer[1024];
764
765                         data_len = (tls_session->record_minus)(&tls_session->dirty_in,
766                                                 buffer, sizeof(buffer));
767                         log_debug("  Tunneled data (%u bytes)\n", data_len);
768                         for (i = 0; i < data_len; i++) {
769                                 if ((i & 0x0f) == 0x00) printf("  %x: ", i);
770                                 if ((i & 0x0f) == 0x0f) printf("\n");
771
772                                 printf("%02x ", buffer[i]);
773                         }
774                         printf("\n");
775                 }
776 #endif
777
778                 eaptls_fail(handler->eap_ds, 0);
779                 return 0;
780                 break;
781
782                 /*
783                  *      Anything else: fail.
784                  */
785         default:
786                 return 0;
787         }
788
789         /*
790          *      Success: Return MPPE keys.
791          */
792         eaptls_success(handler->eap_ds, 0);
793         eaptls_gen_mppe_keys(&handler->request->reply->vps,
794                              tls_session->ssl,
795                              "client EAP encryption");
796         return 1;
797 }
798
799 /*
800  *      The module name should be the only globally exported symbol.
801  *      That is, everything else should be 'static'.
802  */
803 EAP_TYPE rlm_eap_tls = {
804         "eap_tls",
805         eaptls_attach,                  /* attach */
806         eaptls_initiate,                /* Start the initial request */
807         NULL,                           /* authorization */
808         eaptls_authenticate,            /* authentication */
809         eaptls_detach                   /* detach */
810 };