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