More sanity checks on fragment size, and account for EAP-TLS
[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  *      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                 radlog(L_INFO, "chain-depth=%d, ", depth);
253                 radlog(L_INFO, "error=%d", err);
254
255                 radlog(L_INFO, "--> User-Name = %s", handler->identity);
256                 radlog(L_INFO, "--> BUF-Name = %s", common_name);
257                 radlog(L_INFO, "--> subject = %s", subject);
258                 radlog(L_INFO, "--> issuer  = %s", issuer);
259                 radlog(L_INFO, "--> 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                 radlog(L_INFO, "rlm_eap_tls: Loading the certificate file as a chain");
319                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
320                         radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
321                         radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
322                         return NULL;
323                 }
324
325         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
326                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
327                 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
328                 return NULL;
329         }
330
331         /* Load the CAs we trust */
332         if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
333                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
334                 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
335                 return NULL;
336         }
337         SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
338         if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
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 private key file %s", conf->private_key_file);
341                 return NULL;
342         }
343
344         /*
345          * Check if the loaded private key is the right one
346          */
347         if (!SSL_CTX_check_private_key(ctx)) {
348                 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
349                 return NULL;
350         }
351
352         /*
353          *      Set ctx_options
354          */
355         ctx_options |= SSL_OP_NO_SSLv2;
356         ctx_options |= SSL_OP_NO_SSLv3;
357
358         /*
359          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
360          *      small subgroup attacks and forward secrecy. Always
361          *      using
362          *
363          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
364          *      time needed during negotiation, but it is not very
365          *      large.
366          */
367         ctx_options |= SSL_OP_SINGLE_DH_USE;
368
369         /*
370          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
371          *      in Windows Vista client.
372          *      http://www.openssl.org/~bodo/tls-cbc.txt
373          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
374          */
375         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
376
377         SSL_CTX_set_options(ctx, ctx_options);
378
379         /*
380          *      TODO: Set the RSA & DH
381          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
382          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
383          */
384
385         /*
386          *      set the message callback to identify the type of
387          *      message.  For every new session, there can be a
388          *      different callback argument.
389          *
390          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
391          */
392
393         /* Set Info callback */
394         SSL_CTX_set_info_callback(ctx, cbtls_info);
395
396         /*
397          *      Check the certificates for revocation.
398          */
399 #ifdef X509_V_FLAG_CRL_CHECK
400         if (conf->check_crl) {
401           certstore = SSL_CTX_get_cert_store(ctx);
402           if (certstore == NULL) {
403             radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
404             radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
405             return NULL;
406           }
407           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
408         }
409 #endif
410
411         /*
412          *      Set verify modes
413          *      Always verify the peer certificate
414          */
415         verify_mode |= SSL_VERIFY_PEER;
416         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
417         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
418         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
419
420         if (conf->verify_depth) {
421                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
422         }
423
424         /* Load randomness */
425         if (!(RAND_load_file(conf->random_file, 1024*1024))) {
426                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
427                 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
428                 return NULL;
429         }
430
431         /*
432          * Set the cipher list if we were told to
433          */
434         if (conf->cipher_list) {
435                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
436                         radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
437                         return NULL;
438                 }
439         }
440
441         return ctx;
442 }
443
444
445 /*
446  *      Detach the EAP-TLS module.
447  */
448 static int eaptls_detach(void *arg)
449 {
450         EAP_TLS_CONF     *conf;
451         eap_tls_t        *inst;
452
453         inst = (eap_tls_t *) arg;
454         conf = inst->conf;
455
456         if (conf) {
457                 memset(conf, 0, sizeof(*conf));
458                 free(inst->conf);
459                 inst->conf = NULL;
460         }
461
462         if (inst->ctx) SSL_CTX_free(inst->ctx);
463         inst->ctx = NULL;
464
465         free(inst);
466
467         return 0;
468 }
469
470
471 /*
472  *      Attach the EAP-TLS module.
473  */
474 static int eaptls_attach(CONF_SECTION *cs, void **instance)
475 {
476         EAP_TLS_CONF     *conf;
477         eap_tls_t        *inst;
478
479         /* Store all these values in the data structure for later references */
480         inst = (eap_tls_t *)malloc(sizeof(*inst));
481         if (!inst) {
482                 radlog(L_ERR, "rlm_eap_tls: out of memory");
483                 return -1;
484         }
485         memset(inst, 0, sizeof(*inst));
486
487         /*
488          *      Parse the config file & get all the configured values
489          */
490         conf = (EAP_TLS_CONF *)malloc(sizeof(*conf));
491         if (conf == NULL) {
492                 free(inst);
493                 radlog(L_ERR, "rlm_eap_tls: out of memory");
494                 return -1;
495         }
496         memset(conf, 0, sizeof(*conf));
497
498         inst->conf = conf;
499         if (cf_section_parse(cs, conf, module_config) < 0) {
500                 eaptls_detach(inst);
501                 return -1;
502         }
503
504         /*
505          *      The EAP RFC's say 1020, but we're less picky.
506          */
507         if (conf->fragment_size < 100) {
508                 radlog(L_ERR, "rlm_eap_tls: Fragment size is too small.");
509                 eaptls_detach(inst);
510                 return -1;
511         }
512
513         /*
514          *      The maximum size for a RADIUS packet is 4096,
515          *      minus the header (20), Message-Authenticator (18),
516          *      and State (18), etc. results in about 4000 bytes of data
517          *      that can be devoted *solely* to EAP.
518          */
519         if (conf->fragment_size > 4000) {
520                 radlog(L_ERR, "rlm_eap_tls: Fragment size is too large.");
521                 eaptls_detach(inst);
522                 return -1;
523         }
524
525         /*
526          *      Account for the EAP header (4), and the EAP-TLS header
527          *      (6), as per Section 4.2 of RFC 2716.  What's left is
528          *      the maximum amount of data we read from a TLS buffer.
529          */
530         conf->fragment_size -= 10;
531
532         /*
533          *      This magic makes the administrators life HUGELY easier
534          *      on initial deployments.
535          *
536          *      If the server starts up in debugging mode, AND the
537          *      bootstrap command is configured, AND it exists, AND
538          *      there is no server certificate
539          */
540         if (conf->make_cert_command && (debug_flag >= 2)) {
541                 struct stat buf;
542
543                 if ((stat(conf->make_cert_command, &buf) == 0) &&
544                     (stat(conf->certificate_file, &buf) < 0) &&
545                     (errno == ENOENT) &&
546                     (radius_exec_program(conf->make_cert_command, NULL, 1,
547                                          NULL, 0, NULL, NULL, 0) != 0)) {
548                         eaptls_detach(inst);
549                         return -1;
550                 }
551         }
552
553
554         /*
555          *      Initialize TLS
556          */
557         inst->ctx = init_tls_ctx(conf);
558         if (inst->ctx == NULL) {
559                 eaptls_detach(inst);
560                 return -1;
561         }
562
563         if (load_dh_params(inst->ctx, conf->dh_file) < 0) {
564                 eaptls_detach(inst);
565                 return -1;
566         }
567
568         *instance = inst;
569
570         return 0;
571 }
572
573
574 /*
575  *      Send an initial eap-tls request to the peer.
576  *
577  *      Frame eap reply packet.
578  *      len = header + type + tls_typedata
579  *      tls_typedata = flags(Start (S) bit set, and no data)
580  *
581  *      Once having received the peer's Identity, the EAP server MUST
582  *      respond with an EAP-TLS/Start packet, which is an
583  *      EAP-Request packet with EAP-Type=EAP-TLS, the Start (S) bit
584  *      set, and no data.  The EAP-TLS conversation will then begin,
585  *      with the peer sending an EAP-Response packet with
586  *      EAP-Type = EAP-TLS.  The data field of that packet will
587  *      be the TLS data.
588  *
589  *      Fragment length is Framed-MTU - 4.
590  *
591  *      http://mail.frascone.com/pipermail/public/eap/2003-July/001426.html
592  */
593 static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
594 {
595         int             status;
596         tls_session_t   *ssn;
597         eap_tls_t       *inst;
598         VALUE_PAIR      *vp;
599         int             client_cert = TRUE;
600         int             verify_mode = 0;
601
602         inst = (eap_tls_t *)type_arg;
603
604         /*
605          *      If we're TTLS or PEAP, then do NOT require a client
606          *      certificate.
607          *
608          *      FIXME: This should be more configurable.
609          */
610         if (handler->eap_type != PW_EAP_TLS) {
611                 vp = pairfind(handler->request->config_items,
612                               PW_EAP_TLS_REQUIRE_CLIENT_CERT);
613                 if (!vp) {
614                         client_cert = FALSE;
615                 } else {
616                         client_cert = vp->vp_integer;
617                 }
618         }
619
620         /*
621          *      Every new session is started only from EAP-TLS-START.
622          *      Before Sending EAP-TLS-START, open a new SSL session.
623          *      Create all the required data structures & store them
624          *      in Opaque.  So that we can use these data structures
625          *      when we get the response
626          */
627         ssn = eaptls_new_session(inst->ctx, client_cert);
628         if (!ssn) {
629                 return 0;
630         }
631
632         /*
633          *      Verify the peer certificate, if asked.
634          */
635         if (client_cert) {
636                 DEBUG2(" rlm_eap_tls: Requiring client certificate");
637                 verify_mode = SSL_VERIFY_PEER;
638                 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
639                 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
640         }
641         SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
642
643         /*
644          *      Create a structure for all the items required to be
645          *      verified for each client and set that as opaque data
646          *      structure.
647          *
648          *      NOTE: If we want to set each item sepearately then
649          *      this index should be global.
650          */
651         SSL_set_ex_data(ssn->ssl, 0, (void *)handler);
652         SSL_set_ex_data(ssn->ssl, 1, (void *)inst->conf);
653
654         ssn->length_flag = inst->conf->include_length;
655
656         /*
657          *      We use default fragment size, unless the Framed-MTU
658          *      tells us it's too big.  Note that we do NOT account
659          *      for the EAP-TLS headers if conf->fragment_size is
660          *      large, because that config item looks to be confusing.
661          *
662          *      i.e. it should REALLY be called MTU, and the code here
663          *      should figure out what that means for TLS fragment size.
664          *      asking the administrator to know the internal details
665          *      of EAP-TLS in order to calculate fragment sizes is
666          *      just too much.
667          */
668         ssn->offset = inst->conf->fragment_size;
669         vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU);
670         if (vp && ((vp->vp_integer - 14) < ssn->offset)) {
671                 /*
672                  *      Discount the Framed-MTU by:
673                  *       4 : EAPOL header
674                  *       4 : EAP header (code + id + length)
675                  *       1 : EAP type == EAP-TLS
676                  *       1 : EAP-TLS Flags
677                  *       4 : EAP-TLS Message length
678                  *          (even if conf->include_length == 0,
679                  *           just to be lazy).
680                  *      ---
681                  *      14
682                  */
683                 ssn->offset = vp->vp_integer - 14;
684         }
685
686         handler->opaque = ((void *)ssn);
687         handler->free_opaque = session_free;
688
689         DEBUG2("  rlm_eap_tls: Initiate");
690
691         /*
692          *      PEAP-specific breakage.
693          */
694         if (handler->eap_type == PW_EAP_PEAP) {
695                 /*
696                  *      As it is a poorly designed protocol, PEAP uses
697                  *      bits in the TLS header to indicate PEAP
698                  *      version numbers.  For now, we only support
699                  *      PEAP version 0, so it doesn't matter too much.
700                  *      However, if we support later versions of PEAP,
701                  *      we will need this flag to indicate which
702                  *      version we're currently dealing with.
703                  */
704                 ssn->peap_flag = 0x00;
705
706                 /*
707                  *      PEAP version 0 requires 'include_length = no',
708                  *      so rather than hoping the user figures it out,
709                  *      we force it here.
710                  */
711                 ssn->length_flag = 0;
712         }
713
714         /*
715          *      TLS session initialization is over.  Now handle TLS
716          *      related handshaking or application data.
717          */
718         status = eaptls_start(handler->eap_ds, ssn->peap_flag);
719         DEBUG2("  rlm_eap_tls: Start returned %d", status);
720         if (status == 0)
721                 return 0;
722
723         /*
724          *      The next stage to process the packet.
725          */
726         handler->stage = AUTHENTICATE;
727
728         return 1;
729 }
730
731 /*
732  *      Do authentication, by letting EAP-TLS do most of the work.
733  */
734 static int eaptls_authenticate(void *arg UNUSED, EAP_HANDLER *handler)
735 {
736         eaptls_status_t status;
737         tls_session_t *tls_session = (tls_session_t *) handler->opaque;
738
739         DEBUG2("  rlm_eap_tls: Authenticate");
740
741         status = eaptls_process(handler);
742         DEBUG2("  eaptls_process returned %d\n", status);
743         switch (status) {
744                 /*
745                  *      EAP-TLS handshake was successful, return an
746                  *      EAP-TLS-Success packet here.
747                  */
748         case EAPTLS_SUCCESS:
749                 break;
750
751                 /*
752                  *      The TLS code is still working on the TLS
753                  *      exchange, and it's a valid TLS request.
754                  *      do nothing.
755                  */
756         case EAPTLS_HANDLED:
757                 return 1;
758
759                 /*
760                  *      Handshake is done, proceed with decoding tunneled
761                  *      data.
762                  */
763         case EAPTLS_OK:
764                 DEBUG2("  rlm_eap_tls: Received unexpected tunneled data after successful handshake.");
765 #ifndef NDEBUG
766                 if (debug_flag > 2) {
767                         unsigned int i;
768                         unsigned int data_len;
769                         unsigned char buffer[1024];
770
771                         data_len = (tls_session->record_minus)(&tls_session->dirty_in,
772                                                 buffer, sizeof(buffer));
773                         log_debug("  Tunneled data (%u bytes)\n", data_len);
774                         for (i = 0; i < data_len; i++) {
775                                 if ((i & 0x0f) == 0x00) printf("  %x: ", i);
776                                 if ((i & 0x0f) == 0x0f) printf("\n");
777
778                                 printf("%02x ", buffer[i]);
779                         }
780                         printf("\n");
781                 }
782 #endif
783
784                 eaptls_fail(handler->eap_ds, 0);
785                 return 0;
786                 break;
787
788                 /*
789                  *      Anything else: fail.
790                  */
791         default:
792                 return 0;
793         }
794
795         /*
796          *      Success: Return MPPE keys.
797          */
798         eaptls_success(handler->eap_ds, 0);
799         eaptls_gen_mppe_keys(&handler->request->reply->vps,
800                              tls_session->ssl,
801                              "client EAP encryption");
802         return 1;
803 }
804
805 /*
806  *      The module name should be the only globally exported symbol.
807  *      That is, everything else should be 'static'.
808  */
809 EAP_TYPE rlm_eap_tls = {
810         "eap_tls",
811         eaptls_attach,                  /* attach */
812         eaptls_initiate,                /* Start the initial request */
813         NULL,                           /* authorization */
814         eaptls_authenticate,            /* authentication */
815         eaptls_detach                   /* detach */
816 };