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