import from HEAD:
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Copyright 2001  hereUare Communications, Inc. <raghud@hereuare.com>
21  * Copyright 2003  Alan DeKok <aland@freeradius.org>
22  */
23
24 #include "autoconf.h"
25 #include "eap_tls.h"
26
27 #ifdef HAVE_OPENSSL_RAND_H
28 #include <openssl/rand.h>
29 #endif
30
31 static CONF_PARSER module_config[] = {
32         { "rsa_key_exchange", PW_TYPE_BOOLEAN,
33           offsetof(EAP_TLS_CONF, rsa_key), NULL, "no" },
34         { "dh_key_exchange", PW_TYPE_BOOLEAN,
35           offsetof(EAP_TLS_CONF, dh_key), NULL, "yes" },
36         { "rsa_key_length", PW_TYPE_INTEGER,
37           offsetof(EAP_TLS_CONF, rsa_key_length), NULL, "512" },
38         { "dh_key_length", PW_TYPE_INTEGER,
39           offsetof(EAP_TLS_CONF, dh_key_length), NULL, "512" },
40         { "verify_depth", PW_TYPE_INTEGER,
41           offsetof(EAP_TLS_CONF, verify_depth), NULL, "0" },
42         { "CA_path", PW_TYPE_STRING_PTR,
43           offsetof(EAP_TLS_CONF, ca_path), NULL, NULL },
44         { "pem_file_type", PW_TYPE_BOOLEAN,
45           offsetof(EAP_TLS_CONF, file_type), NULL, "yes" },
46         { "private_key_file", PW_TYPE_STRING_PTR,
47           offsetof(EAP_TLS_CONF, private_key_file), NULL, NULL },
48         { "certificate_file", PW_TYPE_STRING_PTR,
49           offsetof(EAP_TLS_CONF, certificate_file), NULL, NULL },
50         { "CA_file", PW_TYPE_STRING_PTR,
51           offsetof(EAP_TLS_CONF, ca_file), NULL, NULL },
52         { "private_key_password", PW_TYPE_STRING_PTR,
53           offsetof(EAP_TLS_CONF, private_key_password), NULL, NULL },
54         { "dh_file", PW_TYPE_STRING_PTR,
55           offsetof(EAP_TLS_CONF, dh_file), NULL, NULL },
56         { "random_file", PW_TYPE_STRING_PTR,
57           offsetof(EAP_TLS_CONF, random_file), NULL, NULL },
58         { "fragment_size", PW_TYPE_INTEGER,
59           offsetof(EAP_TLS_CONF, fragment_size), NULL, "1024" },
60         { "include_length", PW_TYPE_BOOLEAN,
61           offsetof(EAP_TLS_CONF, include_length), NULL, "yes" },
62         { "check_crl", PW_TYPE_BOOLEAN,
63           offsetof(EAP_TLS_CONF, check_crl), NULL, "no"},
64         { "check_cert_cn", PW_TYPE_STRING_PTR,
65           offsetof(EAP_TLS_CONF, check_cert_cn), NULL, NULL},
66
67         { NULL, -1, 0, NULL, NULL }           /* end the list */
68 };
69
70
71 /*
72  *      TODO: Check for the type of key exchange * like conf->dh_key
73  */
74 static int load_dh_params(SSL_CTX *ctx, char *file)
75 {
76         DH *dh = NULL;
77         BIO *bio;
78
79         if ((bio = BIO_new_file(file, "r")) == NULL) {
80                 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
81                 return -1;
82         }
83
84         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
85         BIO_free(bio);
86         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
87                 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
88                 DH_free(dh);
89                 return -1;
90         }
91
92         DH_free(dh);
93         return 0;
94 }
95
96 /*
97  *      Generte ephemeral RSA keys.
98  */
99 static int generate_eph_rsa_key(SSL_CTX *ctx)
100 {
101         RSA *rsa;
102
103         rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
104
105         if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
106                 radlog(L_ERR, "rlm_eap_tls: Couldn't set RSA key");
107                 return -1;
108         }
109
110         RSA_free(rsa);
111         return 0;
112 }
113
114
115 /*
116  *      Create Global context SSL and use it in every new session
117  *
118  *      - Load the trusted CAs
119  *      - Load the Private key & the certificate
120  *      - Set the Context options & Verify options
121  */
122 static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
123 {
124         SSL_METHOD *meth;
125         SSL_CTX *ctx;
126         X509_STORE *certstore;
127         int verify_mode = 0;
128         int ctx_options = 0;
129         int type;
130
131         /*
132          *      Add all the default ciphers and message digests
133          *      Create our context.
134          */
135         SSL_library_init();
136         SSL_load_error_strings();
137
138         meth = TLSv1_method();
139         ctx = SSL_CTX_new(meth);
140
141         /*
142          * Identify the type of certificates that needs to be loaded
143          */
144         if (conf->file_type) {
145                 type = SSL_FILETYPE_PEM;
146         } else {
147                 type = SSL_FILETYPE_ASN1;
148         }
149
150         /*
151          * Set the password to load private key
152          */
153         if (conf->private_key_password) {
154                 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
155                 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
156         }
157
158         /*
159          *      Load our keys and certificates
160          *
161          *      If certificates are of type PEM then we can make use
162          *      of cert chain authentication using openssl api call
163          *      SSL_CTX_use_certificate_chain_file.  Please see how
164          *      the cert chain needs to be given in PEM from
165          *      openSSL.org
166          */
167         if (type == SSL_FILETYPE_PEM) {
168                 radlog(L_INFO, "rlm_eap_tls: Loading the certificate file as a chain");
169                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
170                         ERR_print_errors_fp(stderr);
171                         radlog(L_ERR, "rlm_eap_tls: Error reading certificate file");
172                         return NULL;
173                 }
174
175         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
176                 ERR_print_errors_fp(stderr);
177                 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file");
178                 return NULL;
179         }
180
181
182         /* Load the CAs we trust */
183         if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
184                 ERR_print_errors_fp(stderr);
185                 radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list");
186                 return NULL;
187         }
188         SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
189
190         if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
191                 ERR_print_errors_fp(stderr);
192                 radlog(L_ERR, "rlm_eap_tls: Error reading private key file");
193                 return NULL;
194         }
195
196         /*
197          * Check if the loaded private key is the right one
198          */
199         if (!SSL_CTX_check_private_key(ctx)) {
200                 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
201                 return NULL;
202         }
203
204         /*
205          *      Set ctx_options
206          */
207         ctx_options |= SSL_OP_NO_SSLv2;
208         ctx_options |= SSL_OP_NO_SSLv3;
209
210         /*
211          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
212          *      small subgroup attacks and forward secrecy. Always
213          *      using
214          *
215          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
216          *      time needed during negotiation, but it is not very
217          *      large.
218          */
219         ctx_options |= SSL_OP_SINGLE_DH_USE;
220         SSL_CTX_set_options(ctx, ctx_options);
221
222         /*
223          *      TODO: Set the RSA & DH
224          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
225          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
226          */
227
228         /*
229          *      set the message callback to identify the type of
230          *      message.  For every new session, there can be a
231          *      different callback argument.
232          *
233          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
234          */
235
236         /* Set Info callback */
237         SSL_CTX_set_info_callback(ctx, cbtls_info);
238
239         /*
240          *      Check the certificates for revocation.
241          */
242 #ifdef X509_V_FLAG_CRL_CHECK
243         if (conf->check_crl) {
244           certstore = SSL_CTX_get_cert_store(ctx);
245           if (certstore == NULL) {
246             ERR_print_errors_fp(stderr);
247             radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
248             return NULL;
249           }
250           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
251         }
252 #endif
253
254         /*
255          *      Set verify modes
256          *      Always verify the peer certificate
257          */
258         verify_mode |= SSL_VERIFY_PEER;
259         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
260         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
261         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
262
263         if (conf->verify_depth) {
264                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
265         }
266
267         /* Load randomness */
268         if (!(RAND_load_file(conf->random_file, 1024*1024))) {
269                 ERR_print_errors_fp(stderr);
270                 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
271                 return NULL;
272         }
273
274         return ctx;
275 }
276
277
278 /*
279  *      Detach the EAP-TLS module.
280  */
281 static int eaptls_detach(void *arg)
282 {
283         EAP_TLS_CONF     *conf;
284         eap_tls_t        *inst;
285
286         inst = (eap_tls_t *) arg;
287         conf = inst->conf;
288
289         if (conf) {
290                 if (conf->dh_file) free(conf->dh_file);
291                 conf->dh_file = NULL;
292                 if (conf->certificate_file) free(conf->certificate_file);
293                 conf->certificate_file = NULL;
294                 if (conf->private_key_file) free(conf->private_key_file);
295                 conf->private_key_file = NULL;
296                 if (conf->private_key_password) free(conf->private_key_password);
297                 conf->private_key_password = NULL;
298                 if (conf->random_file) free(conf->random_file);
299                 conf->random_file = NULL;
300
301                 free(inst->conf);
302                 inst->conf = NULL;
303         }
304
305         if (inst->ctx) SSL_CTX_free(inst->ctx);
306         inst->ctx = NULL;
307
308         free(inst);
309
310         return 0;
311 }
312
313
314 /*
315  *      Attach the EAP-TLS module.
316  */
317 static int eaptls_attach(CONF_SECTION *cs, void **instance)
318 {
319         EAP_TLS_CONF     *conf;
320         eap_tls_t        *inst;
321
322         /* Store all these values in the data structure for later references */
323         inst = (eap_tls_t *)malloc(sizeof(*inst));
324         if (!inst) {
325                 radlog(L_ERR, "rlm_eap_tls: out of memory");
326                 return -1;
327         }
328         memset(inst, 0, sizeof(*inst));
329
330         /*
331          *      Parse the config file & get all the configured values
332          */
333         conf = (EAP_TLS_CONF *)malloc(sizeof(*conf));
334         if (conf == NULL) {
335                 radlog(L_ERR, "rlm_eap_tls: out of memory");
336                 return -1;
337         }
338         memset(conf, 0, sizeof(*conf));
339
340         inst->conf = conf;
341         if (cf_section_parse(cs, conf, module_config) < 0) {
342                 eaptls_detach(inst);
343                 return -1;
344         }
345
346
347         /*
348          *      Initialize TLS
349          */
350         inst->ctx = init_tls_ctx(conf);
351         if (inst->ctx == NULL) {
352                 eaptls_detach(inst);
353                 return -1;
354         }
355
356         if (load_dh_params(inst->ctx, conf->dh_file) < 0) {
357                 eaptls_detach(inst);
358                 return -1;
359         }
360         if (generate_eph_rsa_key(inst->ctx) < 0) {
361                 eaptls_detach(inst);
362                 return -1;
363         }
364
365         *instance = inst;
366
367         return 0;
368 }
369
370
371 /*
372  *      Send an initial eap-tls request to the peer.
373  *
374  *      Frame eap reply packet.
375  *      len = header + type + tls_typedata
376  *      tls_typedata = flags(Start (S) bit set, and no data)
377  *
378  *      Once having received the peer's Identity, the EAP server MUST
379  *      respond with an EAP-TLS/Start packet, which is an
380  *      EAP-Request packet with EAP-Type=EAP-TLS, the Start (S) bit
381  *      set, and no data.  The EAP-TLS conversation will then begin,
382  *      with the peer sending an EAP-Response packet with
383  *      EAP-Type = EAP-TLS.  The data field of that packet will
384  *      be the TLS data.
385  *
386  *      Fragment length is Framed-MTU - 4.
387  *
388  *      http://mail.frascone.com/pipermail/public/eap/2003-July/001426.html
389  */
390 static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
391 {
392         int             status;
393         tls_session_t   *ssn;
394         eap_tls_t       *inst;
395         VALUE_PAIR      *vp;
396         int             client_cert = TRUE;
397
398         inst = (eap_tls_t *)type_arg;
399
400         /*
401          *      If we're TTLS or PEAP, then do NOT require a client
402          *      certificate.
403          *
404          *      FIXME: This should be more configurable.
405          */
406         if (handler->eap_type != PW_EAP_TLS) {
407                 vp = pairfind(handler->request->config_items,
408                               PW_EAP_TLS_REQUIRE_CLIENT_CERT);
409                 if (!vp) {
410                         client_cert = FALSE;
411                 } else {
412                         client_cert = vp->lvalue;
413                 }
414         }
415
416         /*
417          *      Every new session is started only from EAP-TLS-START.
418          *      Before Sending EAP-TLS-START, open a new SSL session.
419          *      Create all the required data structures & store them
420          *      in Opaque.  So that we can use these data structures
421          *      when we get the response
422          */
423         ssn = eaptls_new_session(inst->ctx, client_cert);
424         if (!ssn) {
425                 return 0;
426         }
427
428         /*
429          *      Create a structure for all the items required to be
430          *      verified for each client and set that as opaque data
431          *      structure.
432          *
433          *      NOTE: If we want to set each item sepearately then
434          *      this index should be global.
435          */
436         SSL_set_ex_data(ssn->ssl, 0, (void *)handler);
437         SSL_set_ex_data(ssn->ssl, 1, (void *)inst->conf);
438
439         ssn->length_flag = inst->conf->include_length;
440
441         /*
442          *      We set a default fragment size, unless the Framed-MTU
443          *      tells us it's too big.
444          */
445         ssn->offset = inst->conf->fragment_size;
446         vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU);
447         if (vp && ((vp->lvalue - 4) < ssn->offset)) {
448                 ssn->offset = vp->lvalue - 4;
449         }
450
451         handler->opaque = ((void *)ssn);
452         handler->free_opaque = session_free;
453
454         DEBUG2("  rlm_eap_tls: Initiate");
455
456         /*
457          *      PEAP-specific breakage.
458          */
459         if (handler->eap_type == PW_EAP_PEAP) {
460                 /*
461                  *      As it is a poorly designed protocol, PEAP uses
462                  *      bits in the TLS header to indicate PEAP
463                  *      version numbers.  For now, we only support
464                  *      PEAP version 0, so it doesn't matter too much.
465                  *      However, if we support later versions of PEAP,
466                  *      we will need this flag to indicate which
467                  *      version we're currently dealing with.
468                  */
469                 ssn->peap_flag = 0x00;
470
471                 /*
472                  *      PEAP version 0 requires 'include_length = no',
473                  *      so rather than hoping the user figures it out,
474                  *      we force it here.
475                  */
476                 ssn->length_flag = 0;
477         }
478
479         /*
480          *      TLS session initialization is over.  Now handle TLS
481          *      related handshaking or application data.
482          */
483         status = eaptls_start(handler->eap_ds, ssn->peap_flag);
484         DEBUG2("  rlm_eap_tls: Start returned %d", status);
485         if (status == 0)
486                 return 0;
487
488         /*
489          *      The next stage to process the packet.
490          */
491         handler->stage = AUTHENTICATE;
492
493         return 1;
494 }
495
496 /*
497  *      Do authentication, by letting EAP-TLS do most of the work.
498  */
499 static int eaptls_authenticate(void *arg UNUSED, EAP_HANDLER *handler)
500 {
501         eaptls_status_t status;
502         tls_session_t *tls_session = (tls_session_t *) handler->opaque;
503
504         DEBUG2("  rlm_eap_tls: Authenticate");
505
506         status = eaptls_process(handler);
507         DEBUG2("  eaptls_process returned %d\n", status);
508         switch (status) {
509                 /*
510                  *      EAP-TLS handshake was successful, return an
511                  *      EAP-TLS-Success packet here.
512                  */
513         case EAPTLS_SUCCESS:
514                 break;
515
516                 /*
517                  *      The TLS code is still working on the TLS
518                  *      exchange, and it's a valid TLS request.
519                  *      do nothing.
520                  */
521         case EAPTLS_HANDLED:
522                 return 1;
523
524                 /*
525                  *      Handshake is done, proceed with decoding tunneled
526                  *      data.
527                  */
528         case EAPTLS_OK:
529                 DEBUG2("  rlm_eap_tls: Received unexpected tunneled data after successful handshake.");
530 #ifndef NDEBUG
531                 if (debug_flag > 2) {
532                         unsigned int i;
533                         unsigned int data_len;
534                         unsigned char buffer[1024];
535
536                         data_len = (tls_session->record_minus)(&tls_session->dirty_in,
537                                                 buffer, sizeof(buffer));
538                         log_debug("  Tunneled data (%u bytes)\n", data_len);
539                         for (i = 0; i < data_len; i++) {
540                                 if ((i & 0x0f) == 0x00) printf("  %x: ", i);
541                                 if ((i & 0x0f) == 0x0f) printf("\n");
542
543                                 printf("%02x ", buffer[i]);
544                         }
545                         printf("\n");
546                 }
547 #endif
548
549                 eaptls_fail(handler->eap_ds, 0);
550                 return 0;
551                 break;
552
553                 /*
554                  *      Anything else: fail.
555                  */
556         default:
557                 return 0;
558         }
559
560         /*
561          *      Success: Return MPPE keys.
562          */
563         eaptls_success(handler->eap_ds, 0);
564         eaptls_gen_mppe_keys(&handler->request->reply->vps,
565                              tls_session->ssl,
566                              "client EAP encryption");
567         return 1;
568 }
569
570 /*
571  *      The module name should be the only globally exported symbol.
572  *      That is, everything else should be 'static'.
573  */
574 EAP_TYPE rlm_eap_tls = {
575         "eap_tls",
576         eaptls_attach,                  /* attach */
577         eaptls_initiate,                /* Start the initial request */
578         NULL,                           /* authorization */
579         eaptls_authenticate,            /* authentication */
580         eaptls_detach                   /* detach */
581 };