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