Merge pull request #15 from pobept/dictionary-redback
[freeradius.git] / src / modules / rlm_eap / libeap / eap_tls.c
1 /*
2  * eap_tls.c
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  *
27  *  TLS Packet Format in EAP
28  *  --- ------ ------ -- ---
29  * 0                   1                   2                   3
30  * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
31  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32  * |     Code      |   Identifier  |            Length             |
33  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
34  * |     Type      |     Flags     |      TLS Message Length
35  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
36  * |     TLS Message Length        |       TLS Data...
37  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
38  *
39  */
40
41 #include <freeradius-devel/ident.h>
42 RCSID("$Id$")
43
44 #include <freeradius-devel/autoconf.h>
45 #include <assert.h>
46 #include "eap_tls.h"
47
48 /*
49  *      Allocate a new TLS_PACKET
50  */
51 EAPTLS_PACKET *eaptls_alloc(void)
52 {
53         EAPTLS_PACKET   *rp;
54
55         if ((rp = malloc(sizeof(EAPTLS_PACKET))) == NULL) {
56                 radlog(L_ERR, "rlm_eap_tls: out of memory");
57                 return NULL;
58         }
59         memset(rp, 0, sizeof(EAPTLS_PACKET));
60         return rp;
61 }
62
63 /*
64  *      Free EAPTLS_PACKET
65  */
66 void eaptls_free(EAPTLS_PACKET **eaptls_packet_ptr)
67 {
68         EAPTLS_PACKET *eaptls_packet;
69
70         if (!eaptls_packet_ptr) return;
71         eaptls_packet = *eaptls_packet_ptr;
72         if (eaptls_packet == NULL) return;
73
74         if (eaptls_packet->data) {
75                 free(eaptls_packet->data);
76                 eaptls_packet->data = NULL;
77         }
78
79         free(eaptls_packet);
80         *eaptls_packet_ptr = NULL;
81 }
82
83 /*
84  *      Send an initial eap-tls request to the peer.
85  *
86  *      Frame eap reply packet.
87  *      len = header + type + tls_typedata
88  *      tls_typedata = flags(Start (S) bit set, and no data)
89  *
90  *      Once having received the peer's Identity, the EAP server MUST
91  *      respond with an EAP-TLS/Start packet, which is an
92  *      EAP-Request packet with EAP-Type=EAP-TLS, the Start (S) bit
93  *      set, and no data.  The EAP-TLS conversation will then begin,
94  *      with the peer sending an EAP-Response packet with
95  *      EAP-Type = EAP-TLS.  The data field of that packet will
96  *      be the TLS data.
97  *
98  *      Fragment length is Framed-MTU - 4.
99  */
100 tls_session_t *eaptls_session(fr_tls_server_conf_t *tls_conf, EAP_HANDLER *handler, int client_cert)
101 {
102         tls_session_t   *ssn;
103         int             verify_mode = 0;
104         REQUEST         *request = handler->request;
105
106         handler->tls = TRUE;
107         handler->finished = FALSE;
108
109         /*
110          *      Every new session is started only from EAP-TLS-START.
111          *      Before Sending EAP-TLS-START, open a new SSL session.
112          *      Create all the required data structures & store them
113          *      in Opaque.  So that we can use these data structures
114          *      when we get the response
115          */
116         ssn = tls_new_session(tls_conf, request, client_cert);
117         if (!ssn) {
118                 return NULL;
119         }
120
121         /*
122          *      Verify the peer certificate, if asked.
123          */
124         if (client_cert) {
125                 RDEBUG2("Requiring client certificate");
126                 verify_mode = SSL_VERIFY_PEER;
127                 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
128                 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
129         }
130         SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
131
132         /*
133          *      Create a structure for all the items required to be
134          *      verified for each client and set that as opaque data
135          *      structure.
136          *
137          *      NOTE: If we want to set each item sepearately then
138          *      this index should be global.
139          */
140         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_HANDLER, (void *)handler);
141         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)tls_conf);
142         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS, (void *)&(handler->certs));
143         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_IDENTITY, (void *)&(handler->identity));
144 #ifdef HAVE_OPENSSL_OCSP_H
145         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_STORE, (void *)tls_conf->ocsp_store);
146 #endif
147
148         return ssn;
149 }
150
151 /*
152    The S flag is set only within the EAP-TLS start message
153    sent from the EAP server to the peer.
154 */
155 int eaptls_start(EAP_DS *eap_ds, int peap_flag)
156 {
157         EAPTLS_PACKET   reply;
158
159         reply.code = FR_TLS_START;
160         reply.length = TLS_HEADER_LEN + 1/*flags*/;
161
162         reply.flags = peap_flag;
163         reply.flags = SET_START(reply.flags);
164
165         reply.data = NULL;
166         reply.dlen = 0;
167
168         eaptls_compose(eap_ds, &reply);
169
170         return 1;
171 }
172
173 int eaptls_success(EAP_HANDLER *handler, int peap_flag)
174 {
175         EAPTLS_PACKET   reply;
176         REQUEST *request = handler->request;
177         tls_session_t *tls_session = handler->opaque;
178
179         handler->finished = TRUE;
180         reply.code = FR_TLS_SUCCESS;
181         reply.length = TLS_HEADER_LEN;
182         reply.flags = peap_flag;
183         reply.data = NULL;
184         reply.dlen = 0;
185
186         tls_success(tls_session, request);
187
188         /*
189          *      Call compose AFTER checking for cached data.
190          */
191         eaptls_compose(handler->eap_ds, &reply);
192
193         /*
194          *      Automatically generate MPPE keying material.
195          */
196         if (tls_session->prf_label) {
197                 eaptls_gen_mppe_keys(&handler->request->reply->vps,
198                                      tls_session->ssl, tls_session->prf_label);
199         } else {
200                 RDEBUG("WARNING: Not adding MPPE keys because there is no PRF label");
201         }
202
203         return 1;
204 }
205
206 int eaptls_fail(EAP_HANDLER *handler, int peap_flag)
207 {
208         EAPTLS_PACKET   reply;
209         tls_session_t *tls_session = handler->opaque;
210
211         handler->finished = TRUE;
212         reply.code = FR_TLS_FAIL;
213         reply.length = TLS_HEADER_LEN;
214         reply.flags = peap_flag;
215         reply.data = NULL;
216         reply.dlen = 0;
217
218         tls_fail(tls_session);
219
220         eaptls_compose(handler->eap_ds, &reply);
221
222         return 1;
223 }
224
225 /*
226    A single TLS record may be up to 16384 octets in length, but a TLS
227    message may span multiple TLS records, and a TLS certificate message
228    may in principle be as long as 16MB.
229 */
230
231 /*
232  *      Frame the Dirty data that needs to be send to the client in an
233  *      EAP-Request.  We always embed the TLS-length in all EAP-TLS
234  *      packets that we send, for easy reference purpose.  Handle
235  *      fragmentation and sending the next fragment etc.
236  */
237 int eaptls_request(EAP_DS *eap_ds, tls_session_t *ssn)
238 {
239         EAPTLS_PACKET   reply;
240         unsigned int    size;
241         unsigned int    nlen;
242         unsigned int    lbit = 0;
243
244         /* This value determines whether we set (L)ength flag for
245                 EVERY packet we send and add corresponding
246                 "TLS Message Length" field.
247
248         length_flag = TRUE;
249                 This means we include L flag and "TLS Msg Len" in EVERY
250                 packet we send out.
251
252         length_flag = FALSE;
253                 This means we include L flag and "TLS Msg Len" **ONLY**
254                 in First packet of a fragment series. We do not use
255                 it anywhere else.
256
257                 Having L flag in every packet is prefered.
258
259         */
260         if (ssn->length_flag) {
261                 lbit = 4;
262         }
263         if (ssn->fragment == 0) {
264                 ssn->tls_msg_len = ssn->dirty_out.used;
265         }
266
267         reply.code = FR_TLS_REQUEST;
268         reply.flags = ssn->peap_flag;
269
270         /* Send data, NOT more than the FRAGMENT size */
271         if (ssn->dirty_out.used > ssn->offset) {
272                 size = ssn->offset;
273                 reply.flags = SET_MORE_FRAGMENTS(reply.flags);
274                 /* Length MUST be included if it is the First Fragment */
275                 if (ssn->fragment == 0) {
276                         lbit = 4;
277                 }
278                 ssn->fragment = 1;
279         } else {
280                 size = ssn->dirty_out.used;
281                 ssn->fragment = 0;
282         }
283
284         reply.dlen = lbit + size;
285         reply.length = TLS_HEADER_LEN + 1/*flags*/ + reply.dlen;
286
287         reply.data = malloc(reply.dlen);
288         if (lbit) {
289                 nlen = htonl(ssn->tls_msg_len);
290                 memcpy(reply.data, &nlen, lbit);
291                 reply.flags = SET_LENGTH_INCLUDED(reply.flags);
292         }
293         (ssn->record_minus)(&ssn->dirty_out, reply.data + lbit, size);
294
295         eaptls_compose(eap_ds, &reply);
296         free(reply.data);
297         reply.data = NULL;
298
299         return 1;
300 }
301
302
303 /*
304  *      Similarly, when the EAP server receives an EAP-Response with
305  *      the M bit set, it MUST respond with an EAP-Request with
306  *      EAP-Type=EAP-TLS and no data. This serves as a fragment ACK.
307  *
308  *      In order to prevent errors in the processing of fragments, the
309  *      EAP server MUST use increment the Identifier value for each
310  *      fragment ACK contained within an EAP-Request, and the peer
311  *      MUST include this Identifier value in the subsequent fragment
312  *      contained within an EAP- Reponse.
313  *
314  *      EAP server sends an ACK when it determines there are More
315  *      fragments to receive to make the complete
316  *      TLS-record/TLS-Message
317  */
318 static int eaptls_send_ack(EAP_DS *eap_ds, int peap_flag)
319 {
320         EAPTLS_PACKET   reply;
321
322         reply.code = FR_TLS_ACK;
323         reply.length = TLS_HEADER_LEN + 1/*flags*/;
324         reply.flags = peap_flag;
325         reply.data = NULL;
326         reply.dlen = 0;
327
328         eaptls_compose(eap_ds, &reply);
329
330         return 1;
331 }
332
333 /*
334  *      The S flag is set only within the EAP-TLS start message sent
335  *      from the EAP server to the peer.
336  *
337  *      Similarly, when the EAP server receives an EAP-Response with
338  *      the M bit set, it MUST respond with an EAP-Request with
339  *      EAP-Type=EAP-TLS and no data. This serves as a fragment
340  *      ACK. The EAP peer MUST wait.
341  */
342 static fr_tls_status_t eaptls_verify(EAP_HANDLER *handler)
343 {
344         EAP_DS *eap_ds = handler->eap_ds;
345         EAP_DS *prev_eap_ds = handler->prev_eapds;
346         eaptls_packet_t *eaptls_packet, *eaptls_prev = NULL;
347         REQUEST *request = handler->request;
348
349         /*
350          *      We don't check ANY of the input parameters.  It's all
351          *      code which works together, so if something is wrong,
352          *      we SHOULD core dump.
353          *
354          *      e.g. if eap_ds is NULL, of if eap_ds->response is
355          *      NULL, of if it's NOT an EAP-Response, or if the packet
356          *      is too short.  See eap_validation()., in ../../eap.c
357          *
358          *      Also, eaptype_select() takes care of selecting the
359          *      appropriate type, so we don't need to check
360          *      eap_ds->response->type.type == PW_EAP_TLS, or anything
361          *      else.
362          */
363         eaptls_packet = (eaptls_packet_t *)eap_ds->response->type.data;
364         if (prev_eap_ds && prev_eap_ds->response)
365                 eaptls_prev = (eaptls_packet_t *)prev_eap_ds->response->type.data;
366
367         /*
368          *      check for ACK
369          *
370          *      If there's no TLS data, or there's 1 byte of TLS data,
371          *      with the flags set to zero, then it's an ACK.
372          *
373          *      Find if this is a reply to the previous request sent
374          */
375         if ((eaptls_packet == NULL) ||
376             ((eap_ds->response->length == EAP_HEADER_LEN + 2) &&
377              ((eaptls_packet->flags & 0xc0) == 0x00))) {
378
379                 if (prev_eap_ds &&
380                     (prev_eap_ds->request->id == eap_ds->response->id)) {
381                         /*
382                          *      Run the ACK handler directly from here.
383                          */
384                         RDEBUG2("Received TLS ACK");
385                         return tls_ack_handler(handler->opaque, request);
386                 } else {
387                         radlog_request(L_ERR, 0, request, "Received Invalid TLS ACK");
388                         return FR_TLS_INVALID;
389                 }
390         }
391
392         /*
393          *      We send TLS_START, but do not receive it.
394          */
395         if (TLS_START(eaptls_packet->flags)) {
396                 RDEBUG("Received unexpected EAP-TLS Start message");
397                 return FR_TLS_INVALID;
398         }
399
400         /*
401          *      The L bit (length included) is set to indicate the
402          *      presence of the four octet TLS Message Length field,
403          *      and MUST be set for the first fragment of a fragmented
404          *      TLS message or set of messages.
405          *
406          *      The M bit (more fragments) is set on all but the last
407          *      fragment.
408          *
409          *      The S bit (EAP-TLS start) is set in an EAP-TLS Start
410          *      message. This differentiates the EAP-TLS Start message
411          *      from a fragment acknowledgement.
412          */
413         if (TLS_LENGTH_INCLUDED(eaptls_packet->flags)) {
414                 DEBUG2("  TLS Length %d",
415                        eaptls_packet->data[2] * 256 | eaptls_packet->data[3]);
416                 if (TLS_MORE_FRAGMENTS(eaptls_packet->flags)) {
417                         /*
418                          * FIRST_FRAGMENT is identified
419                          * 1. If there is no previous EAP-response received.
420                          * 2. If EAP-response received, then its M bit not set.
421                          *      (It is because Last fragment will not have M bit set)
422                          */
423                         if (!prev_eap_ds ||
424                             (prev_eap_ds->response == NULL) ||
425                             (eaptls_prev == NULL) ||
426                             !TLS_MORE_FRAGMENTS(eaptls_prev->flags)) {
427
428                                 RDEBUG2("Received EAP-TLS First Fragment of the message");
429                                 return FR_TLS_FIRST_FRAGMENT;
430                         } else {
431
432                                 RDEBUG2("More Fragments with length included");
433                                 return FR_TLS_MORE_FRAGMENTS_WITH_LENGTH;
434                         }
435                 } else {
436                         RDEBUG2("Length Included");
437                         return FR_TLS_LENGTH_INCLUDED;
438                 }
439         }
440
441         if (TLS_MORE_FRAGMENTS(eaptls_packet->flags)) {
442                 RDEBUG2("More fragments to follow");
443                 return FR_TLS_MORE_FRAGMENTS;
444         }
445
446         /*
447          *      None of the flags are set, but it's still a valid
448          *      EAPTLS packet.
449          */
450         return FR_TLS_OK;
451 }
452
453 /*
454  * EAPTLS_PACKET
455  * code   =  EAP-code
456  * id     =  EAP-id
457  * length = code + id + length + flags + tlsdata
458  *        =  1   +  1 +   2    +  1    +  X
459  * length = EAP-length - 1(EAP-Type = 1 octet)
460  * flags  = EAP-typedata[0] (1 octet)
461  * dlen   = EAP-typedata[1-4] (4 octets), if L flag set
462  *        = length - 5(code+id+length+flags), otherwise
463  * data   = EAP-typedata[5-n], if L flag set
464  *        = EAP-typedata[1-n], otherwise
465  * packet = EAP-typedata (complete typedata)
466  *
467  * Points to consider during EAP-TLS data extraction
468  * 1. In the received packet, No data will be present incase of ACK-NAK
469  * 2. Incase if more fragments need to be received then ACK after retreiving this fragment.
470  *
471  *  RFC 2716 Section 4.2.  PPP EAP TLS Request Packet
472  *
473  *  0                   1                   2                   3
474  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
475  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
476  *  |     Code      |   Identifier  |            Length             |
477  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
478  *  |     Type      |     Flags     |      TLS Message Length
479  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
480  *  |     TLS Message Length        |       TLS Data...
481  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
482  *
483  *  The Length field is two octets and indicates the length of the EAP
484  *  packet including the Code, Identifir, Length, Type, and TLS data
485  *  fields.
486  */
487 static EAPTLS_PACKET *eaptls_extract(REQUEST *request, EAP_DS *eap_ds, fr_tls_status_t status)
488 {
489         EAPTLS_PACKET   *tlspacket;
490         uint32_t        data_len = 0;
491         uint32_t        len = 0;
492         uint8_t         *data = NULL;
493
494         if (status  == FR_TLS_INVALID)
495                 return NULL;
496
497         /*
498          *      The main EAP code & eaptls_verify() take care of
499          *      ensuring that the packet is OK, and that we can
500          *      extract the various fields we want.
501          *
502          *      e.g. a TLS packet with zero data is allowed as an ACK,
503          *      but we will never see it here, as we will simply
504          *      send another fragment, instead of trying to extract
505          *      the data.
506          *
507          *      MUST have TLS type octet, followed by flags, followed
508          *      by data.
509          */
510         assert(eap_ds->response->length > 2);
511
512         tlspacket = eaptls_alloc();
513         if (tlspacket == NULL) return NULL;
514
515         /*
516          *      Code & id for EAPTLS & EAP are same
517          *      but eaptls_length = eap_length - 1(EAP-Type = 1 octet)
518          *
519          *      length = code + id + length + type + tlsdata
520          *             =  1   +  1 +   2    +  1    +  X
521          */
522         tlspacket->code = eap_ds->response->code;
523         tlspacket->id = eap_ds->response->id;
524         tlspacket->length = eap_ds->response->length - 1; /* EAP type */
525         tlspacket->flags = eap_ds->response->type.data[0];
526
527         /*
528          *      A quick sanity check of the flags.  If we've been told
529          *      that there's a length, and there isn't one, then stop.
530          */
531         if (TLS_LENGTH_INCLUDED(tlspacket->flags) &&
532             (tlspacket->length < 5)) { /* flags + TLS message length */
533                 RDEBUG("Invalid EAP-TLS packet received.  (Length bit is set, but no length was found.)");
534                 eaptls_free(&tlspacket);
535                 return NULL;
536         }
537
538         /*
539          *      If the final TLS packet is larger than we can handle, die
540          *      now.
541          *
542          *      Likewise, if the EAP packet says N bytes, and the TLS
543          *      packet says there's fewer bytes, it's a problem.
544          *
545          *      FIXME: Try to ensure that the claimed length is
546          *      consistent across multiple TLS fragments.
547          */
548         if (TLS_LENGTH_INCLUDED(tlspacket->flags)) {
549                 memcpy(&data_len, &eap_ds->response->type.data[1], 4);
550                 data_len = ntohl(data_len);
551                 if (data_len > MAX_RECORD_SIZE) {
552                         RDEBUG("The EAP-TLS packet will contain more data than we can process.");
553                         eaptls_free(&tlspacket);
554                         return NULL;
555                 }
556
557 #if 0
558                 DEBUG2(" TLS: %d %d\n", data_len, tlspacket->length);
559
560                 if (data_len < tlspacket->length) {
561                         RDEBUG("EAP-TLS packet claims to be smaller than the encapsulating EAP packet.");
562                         eaptls_free(&tlspacket);
563                         return NULL;
564                 }
565 #endif
566         }
567
568         switch (status) {
569         /*
570          *      The TLS Message Length field is four octets, and
571          *      provides the total length of the TLS message or set of
572          *      messages that is being fragmented; this simplifies
573          *      buffer allocation.
574          *
575          *      Dynamic allocation of buffers as & when we know the
576          *      length should solve the problem.
577          */
578         case FR_TLS_FIRST_FRAGMENT:
579         case FR_TLS_LENGTH_INCLUDED:
580         case FR_TLS_MORE_FRAGMENTS_WITH_LENGTH:
581                 if (tlspacket->length < 5) { /* flags + TLS message length */
582                         RDEBUG("Invalid EAP-TLS packet received.  (Expected length, got none.)");
583                         eaptls_free(&tlspacket);
584                         return NULL;
585                 }
586
587                 /*
588                  *      Extract all the TLS fragments from the
589                  *      previous eap_ds Start appending this
590                  *      fragment to the above ds
591                  */
592                 memcpy(&data_len, &eap_ds->response->type.data[1], sizeof(uint32_t));
593                 data_len = ntohl(data_len);
594                 data = (eap_ds->response->type.data + 5/*flags+TLS-Length*/);
595                 len = eap_ds->response->type.length - 5/*flags+TLS-Length*/;
596
597                 /*
598                  *      Hmm... this should be an error, too.
599                  */
600                 if (data_len > len) {
601                         data_len = len;
602                 }
603                 break;
604
605                 /*
606                  *      Data length is implicit, from the EAP header.
607                  */
608         case FR_TLS_MORE_FRAGMENTS:
609         case FR_TLS_OK:
610                 data_len = eap_ds->response->type.length - 1/*flags*/;
611                 data = eap_ds->response->type.data + 1/*flags*/;
612                 break;
613
614         default:
615                 RDEBUG("Invalid EAP-TLS packet received");
616                 eaptls_free(&tlspacket);
617                 return NULL;
618         }
619
620         tlspacket->dlen = data_len;
621         if (data_len) {
622                 tlspacket->data = (unsigned char *)malloc(data_len);
623                 if (tlspacket->data == NULL) {
624                         RDEBUG("out of memory");
625                         eaptls_free(&tlspacket);
626                         return NULL;
627                 }
628                 memcpy(tlspacket->data, data, data_len);
629         }
630
631         return tlspacket;
632 }
633
634
635
636 /*
637  * To process the TLS,
638  *  INCOMING DATA:
639  *      1. EAP-TLS should get the compelete TLS data from the peer.
640  *      2. Store that data in a data structure with any other required info
641  *      3. Handle that data structure to the TLS module.
642  *      4. TLS module will perform its operations on the data and
643  *      handle back to EAP-TLS
644  *
645  *  OUTGOING DATA:
646  *      1. EAP-TLS if necessary will fragment it and send it to the
647  *      destination.
648  *
649  *      During EAP-TLS initialization, TLS Context object will be
650  *      initialized and stored.  For every new authentication
651  *      requests, TLS will open a new session object and that session
652  *      object should be maintained even after the session is
653  *      completed for session resumption. (Probably later as a feature
654  *      as we donot know who maintains these session objects ie,
655  *      SSL_CTX (internally) or TLS module(explicitly). If TLS module,
656  *      then how to let SSL API know about these sessions.)
657  */
658 static fr_tls_status_t eaptls_operation(fr_tls_status_t status,
659                                         EAP_HANDLER *handler)
660 {
661         tls_session_t *tls_session;
662
663         tls_session = (tls_session_t *)handler->opaque;
664
665         if ((status == FR_TLS_MORE_FRAGMENTS) ||
666             (status == FR_TLS_MORE_FRAGMENTS_WITH_LENGTH) ||
667             (status == FR_TLS_FIRST_FRAGMENT)) {
668                 /*
669                  *      Send the ACK.
670                  */
671                 eaptls_send_ack(handler->eap_ds, tls_session->peap_flag);
672                 return FR_TLS_HANDLED;
673
674         }
675
676         /*
677          *      We have the complete TLS-data or TLS-message.
678          *
679          *      Clean the dirty message.
680          *
681          *      Authenticate the user and send
682          *      Success/Failure.
683          *
684          *      If more info
685          *      is required then send another request.
686          */
687         if (!tls_handshake_recv(handler->request, tls_session)) {
688                 DEBUG2("TLS receive handshake failed during operation");
689                 eaptls_fail(handler, tls_session->peap_flag);
690                 return FR_TLS_FAIL;
691         }
692
693         /*
694          *      FIXME: return success/fail.
695          *
696          *      TLS proper can decide what to do, then.
697          */
698         if (tls_session->dirty_out.used > 0) {
699                 eaptls_request(handler->eap_ds, tls_session);
700                 return FR_TLS_HANDLED;
701         }
702                 
703         /* 
704          *      If there is no data to send i.e
705          *      dirty_out.used <=0 and if the SSL
706          *      handshake is finished, then return a
707          *      EPTLS_SUCCESS
708          */
709         
710         if (SSL_is_init_finished(tls_session->ssl)) {
711                 /*
712                  *      Init is finished.  The rest is
713                  *      application data.
714                  */
715                 tls_session->info.content_type = application_data; 
716                 return FR_TLS_SUCCESS;
717         }
718         
719         /*
720          *      Who knows what happened...
721          */
722         DEBUG2("TLS failed during operation");
723         return FR_TLS_FAIL;
724 }
725
726
727 /*
728  * In the actual authentication first verify the packet and then create the data structure
729  */
730 /*
731  * To process the TLS,
732  *  INCOMING DATA:
733  *      1. EAP-TLS should get the compelete TLS data from the peer.
734  *      2. Store that data in a data structure with any other required info
735  *      3. Hand this data structure to the TLS module.
736  *      4. TLS module will perform its operations on the data and hands back to EAP-TLS
737  *  OUTGOING DATA:
738  *      1. EAP-TLS if necessary will fragment it and send it to the destination.
739  *
740  *      During EAP-TLS initialization, TLS Context object will be
741  *      initialized and stored.  For every new authentication
742  *      requests, TLS will open a new session object and that
743  *      session object SHOULD be maintained even after the session
744  *      is completed, for session resumption. (Probably later as a
745  *      feature, as we do not know who maintains these session
746  *      objects ie, SSL_CTX (internally) or TLS module (explicitly). If
747  *      TLS module, then how to let SSL API know about these
748  *      sessions.)
749  */
750
751 /*
752  *      Process an EAP request
753  */
754 fr_tls_status_t eaptls_process(EAP_HANDLER *handler)
755 {
756         tls_session_t *tls_session = (tls_session_t *) handler->opaque;
757         EAPTLS_PACKET   *tlspacket;
758         fr_tls_status_t status;
759         REQUEST *request = handler->request;
760
761         if (!request) return FR_TLS_FAIL;
762
763         RDEBUG2("processing EAP-TLS");
764         SSL_set_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST, request);
765
766         if (handler->certs) pairadd(&request->packet->vps,
767                                     paircopy(handler->certs));
768
769         /* This case is when SSL generates Alert then we
770          * send that alert to the client and then send the EAP-Failure
771          */
772         status = eaptls_verify(handler);
773         RDEBUG2("eaptls_verify returned %d\n", status);
774
775         switch (status) {
776         default:
777         case FR_TLS_INVALID:
778         case FR_TLS_FAIL:
779
780                 /*
781                  *      Success means that we're done the initial
782                  *      handshake.  For TTLS, this means send stuff
783                  *      back to the client, and the client sends us
784                  *      more tunneled data.
785                  */
786         case FR_TLS_SUCCESS:
787                 goto done;
788
789                 /*
790                  *      Normal TLS request, continue with the "get rest
791                  *      of fragments" phase.
792                  */
793         case FR_TLS_REQUEST:
794                 eaptls_request(handler->eap_ds, tls_session);
795                 status = FR_TLS_HANDLED;
796                 goto done;
797
798                 /*
799                  *      The handshake is done, and we're in the "tunnel
800                  *      data" phase.
801                  */
802         case FR_TLS_OK:
803                 RDEBUG2("Done initial handshake");
804
805                 /*
806                  *      Get the rest of the fragments.
807                  */
808         case FR_TLS_FIRST_FRAGMENT:
809         case FR_TLS_MORE_FRAGMENTS:
810         case FR_TLS_LENGTH_INCLUDED:
811         case FR_TLS_MORE_FRAGMENTS_WITH_LENGTH:
812                 break;
813         }
814
815         /*
816          *      Extract the TLS packet from the buffer.
817          */
818         if ((tlspacket = eaptls_extract(request, handler->eap_ds, status)) == NULL) {
819                 status = FR_TLS_FAIL;
820                 goto done;
821         }
822
823         /*
824          *      Get the session struct from the handler
825          *
826          *      update the dirty_in buffer
827          *
828          *      NOTE: This buffer will contain partial data when M bit is set.
829          *
830          *      CAUTION while reinitializing this buffer, it should be
831          *      reinitialized only when this M bit is NOT set.
832          */
833         if (tlspacket->dlen !=
834             (tls_session->record_plus)(&tls_session->dirty_in, tlspacket->data, tlspacket->dlen)) {
835                 eaptls_free(&tlspacket);
836                 RDEBUG("Exceeded maximum record size");
837                 status =FR_TLS_FAIL;
838                 goto done;
839         }
840
841         /*
842          *      No longer needed.
843          */
844         eaptls_free(&tlspacket);
845
846         /*
847          *      SSL initalization is done.  Return.
848          *
849          *      The TLS data will be in the tls_session structure.
850          */
851         if (SSL_is_init_finished(tls_session->ssl)) {
852                 /*
853                  *      The initialization may be finished, but if
854                  *      there more fragments coming, then send ACK,
855                  *      and get the caller to continue the
856                  *      conversation.
857                  */     
858                 if ((status == FR_TLS_MORE_FRAGMENTS) ||
859                     (status == FR_TLS_MORE_FRAGMENTS_WITH_LENGTH) ||
860                     (status == FR_TLS_FIRST_FRAGMENT)) {
861                         /*
862                          *      Send the ACK.
863                          */
864                         eaptls_send_ack(handler->eap_ds,
865                                         tls_session->peap_flag);
866                         RDEBUG2("Init is done, but tunneled data is fragmented");
867                         status = FR_TLS_HANDLED;
868                         goto done;
869                 }
870
871                 status = tls_application_data(tls_session, request);
872                 goto done;
873         }
874
875         /*
876          *      Continue the handshake.
877          */
878         status = eaptls_operation(status, handler);
879
880  done:
881         SSL_set_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST, NULL);
882
883         return status;
884 }
885
886
887 /*
888  *      compose the TLS reply packet in the EAP reply typedata
889  */
890 int eaptls_compose(EAP_DS *eap_ds, EAPTLS_PACKET *reply)
891 {
892         uint8_t *ptr;
893
894         /*
895          *      Don't set eap_ds->request->type.type, as the main EAP
896          *      handler will do that for us.  This allows the TLS
897          *      module to be called from TTLS & PEAP.
898          */
899
900         /*
901          *      When the EAP server receives an EAP-Response with the
902          *      M bit set, it MUST respond with an EAP-Request with
903          *      EAP-Type=EAP-TLS and no data. This serves as a
904          *      fragment ACK. The EAP peer MUST wait until it receives
905          *      the EAP-Request before sending another fragment.
906          *
907          *      In order to prevent errors in the processing of
908          *      fragments, the EAP server MUST use increment the
909          *      Identifier value for each fragment ACK contained
910          *      within an EAP-Request, and the peer MUST include this
911          *      Identifier value in the subsequent fragment contained
912          *      within an EAP- Reponse.
913          */
914         eap_ds->request->type.data = malloc(reply->length - TLS_HEADER_LEN + 1);
915         if (eap_ds->request->type.data == NULL) {
916                 radlog(L_ERR, "out of memory");
917                 return 0;
918         }
919
920         /* EAPTLS Header length is excluded while computing EAP typelen */
921         eap_ds->request->type.length = reply->length - TLS_HEADER_LEN;
922
923         ptr = eap_ds->request->type.data;
924         *ptr++ = (uint8_t)(reply->flags & 0xFF);
925
926         if (reply->dlen) memcpy(ptr, reply->data, reply->dlen);
927
928         switch (reply->code) {
929         case FR_TLS_ACK:
930         case FR_TLS_START:
931         case FR_TLS_REQUEST:
932                 eap_ds->request->code = PW_EAP_REQUEST;
933                 break;
934         case FR_TLS_SUCCESS:
935                 eap_ds->request->code = PW_EAP_SUCCESS;
936                 break;
937         case FR_TLS_FAIL:
938                 eap_ds->request->code = PW_EAP_FAILURE;
939                 break;
940         default:
941                 /* Should never enter here */
942                 eap_ds->request->code = PW_EAP_FAILURE;
943                 break;
944         }
945
946         return 1;
947 }
948
949 /*
950  *      Parse TLS configuration
951  *
952  *      If the option given by 'attr' is set, we find the config section
953  *      of that name and use that for the TLS configuration. If not, we
954  *      fall back to compatibility mode and read the TLS options from
955  *      the 'tls' section.
956  */
957 fr_tls_server_conf_t *eaptls_conf_parse(CONF_SECTION *cs, const char *attr)
958 {
959         const char              *tls_conf_name;
960         CONF_PAIR               *cp;
961         CONF_SECTION            *parent;
962         CONF_SECTION            *tls_cs;
963         fr_tls_server_conf_t    *tls_conf;
964
965         if (!cs)
966                 return NULL;
967
968         rad_assert(attr != NULL);
969
970         parent = cf_item_parent(cf_sectiontoitem(cs));
971
972         cp = cf_pair_find(cs, attr);
973         if (cp) {
974                 tls_conf_name = cf_pair_value(cp);
975
976                 tls_cs = cf_section_sub_find_name2(parent, TLS_CONFIG_SECTION, tls_conf_name);
977
978                 if (!tls_cs) {
979                         radlog(L_ERR, "error: cannot find tls config '%s'", tls_conf_name);
980                         return NULL;
981                 }
982         } else {
983                 /*
984                  *      If we can't find the section given by the 'attr', we
985                  *      fall-back to looking for the "tls" section, as in
986                  *      previous versions.
987                  *
988                  *      We don't fall back if the 'attr' is specified, but we can't
989                  *      find the section - that is just a config error.
990                  */
991                 radlog(L_INFO, "debug: '%s' option missing, trying to use legacy configuration", attr);
992                 tls_cs = cf_section_sub_find(parent, "tls");
993         }
994
995         if (!tls_cs)
996                 return NULL;
997
998         tls_conf = tls_server_conf_parse(tls_cs);
999
1000         if (!tls_conf)
1001                 return NULL;
1002
1003         /*
1004          *      The EAP RFC's say 1020, but we're less picky.
1005          */
1006         if (tls_conf->fragment_size < 100) {
1007                 radlog(L_ERR, "error: Fragment size is too small.");
1008                 return NULL;
1009         }
1010
1011         /*
1012          *      The maximum size for a RADIUS packet is 4096,
1013          *      minus the header (20), Message-Authenticator (18),
1014          *      and State (18), etc. results in about 4000 bytes of data
1015          *      that can be devoted *solely* to EAP.
1016          */
1017         if (tls_conf->fragment_size > 4000) {
1018                 radlog(L_ERR, "error: Fragment size is too large.");
1019                 return NULL;
1020         }
1021
1022         /*
1023          *      Account for the EAP header (4), and the EAP-TLS header
1024          *      (6), as per Section 4.2 of RFC 2716.  What's left is
1025          *      the maximum amount of data we read from a TLS buffer.
1026          */
1027         tls_conf->fragment_size -= 10;
1028
1029         return tls_conf;
1030 }
1031