Clean up debug && log messages
[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    The S flag is set only within the EAP-TLS start message
85    sent from the EAP server to the peer.
86 */
87 int eaptls_start(EAP_DS *eap_ds, int peap_flag)
88 {
89         EAPTLS_PACKET   reply;
90
91         reply.code = EAPTLS_START;
92         reply.length = TLS_HEADER_LEN + 1/*flags*/;
93
94         reply.flags = peap_flag;
95         reply.flags = SET_START(reply.flags);
96
97         reply.data = NULL;
98         reply.dlen = 0;
99
100         eaptls_compose(eap_ds, &reply);
101
102         return 1;
103 }
104
105 int eaptls_success(EAP_HANDLER *handler, int peap_flag)
106 {
107         EAPTLS_PACKET   reply;
108         tls_session_t *tls_session = handler->opaque;
109
110         reply.code = EAPTLS_SUCCESS;
111         reply.length = TLS_HEADER_LEN;
112         reply.flags = peap_flag;
113         reply.data = NULL;
114         reply.dlen = 0;
115
116         eaptls_compose(handler->eap_ds, &reply);
117
118         /*
119          *      Automatically generate MPPE keying material.
120          */
121         if (tls_session->prf_label) {
122                 eaptls_gen_mppe_keys(&handler->request->reply->vps,
123                                      tls_session->ssl, tls_session->prf_label);
124         } else {
125                 REQUEST *request = handler->request;
126
127                 RDEBUG("WARNING: Not adding MPPE keys because there is no PRF label");
128         }
129
130         return 1;
131 }
132
133 int eaptls_fail(EAP_HANDLER *handler, int peap_flag)
134 {
135         EAPTLS_PACKET   reply;
136         tls_session_t *tls_session = handler->opaque;
137
138         reply.code = EAPTLS_FAIL;
139         reply.length = TLS_HEADER_LEN;
140         reply.flags = peap_flag;
141         reply.data = NULL;
142         reply.dlen = 0;
143
144         /*
145          *      Force the session to NOT be cached.
146          */
147         SSL_CTX_remove_session(tls_session->ctx, tls_session->ssl->session);
148
149         eaptls_compose(handler->eap_ds, &reply);
150
151         return 1;
152 }
153
154 /*
155    A single TLS record may be up to 16384 octets in length, but a TLS
156    message may span multiple TLS records, and a TLS certificate message
157    may in principle be as long as 16MB.
158 */
159
160 /*
161  *      Frame the Dirty data that needs to be send to the client in an
162  *      EAP-Request.  We always embed the TLS-length in all EAP-TLS
163  *      packets that we send, for easy reference purpose.  Handle
164  *      fragmentation and sending the next fragment etc.
165  */
166 int eaptls_request(EAP_DS *eap_ds, tls_session_t *ssn)
167 {
168         EAPTLS_PACKET   reply;
169         unsigned int    size;
170         unsigned int    nlen;
171         unsigned int    lbit = 0;
172
173         /* This value determines whether we set (L)ength flag for
174                 EVERY packet we send and add corresponding
175                 "TLS Message Length" field.
176
177         length_flag = TRUE;
178                 This means we include L flag and "TLS Msg Len" in EVERY
179                 packet we send out.
180
181         length_flag = FALSE;
182                 This means we include L flag and "TLS Msg Len" **ONLY**
183                 in First packet of a fragment series. We do not use
184                 it anywhere else.
185
186                 Having L flag in every packet is prefered.
187
188         */
189         if (ssn->length_flag) {
190                 lbit = 4;
191         }
192         if (ssn->fragment == 0) {
193                 ssn->tls_msg_len = ssn->dirty_out.used;
194         }
195
196         reply.code = EAPTLS_REQUEST;
197         reply.flags = ssn->peap_flag;
198
199         /* Send data, NOT more than the FRAGMENT size */
200         if (ssn->dirty_out.used > ssn->offset) {
201                 size = ssn->offset;
202                 reply.flags = SET_MORE_FRAGMENTS(reply.flags);
203                 /* Length MUST be included if it is the First Fragment */
204                 if (ssn->fragment == 0) {
205                         lbit = 4;
206                 }
207                 ssn->fragment = 1;
208         } else {
209                 size = ssn->dirty_out.used;
210                 ssn->fragment = 0;
211         }
212
213         reply.dlen = lbit + size;
214         reply.length = TLS_HEADER_LEN + 1/*flags*/ + reply.dlen;
215
216         reply.data = malloc(reply.dlen);
217         if (lbit) {
218                 nlen = htonl(ssn->tls_msg_len);
219                 memcpy(reply.data, &nlen, lbit);
220                 reply.flags = SET_LENGTH_INCLUDED(reply.flags);
221         }
222         (ssn->record_minus)(&ssn->dirty_out, reply.data + lbit, size);
223
224         eaptls_compose(eap_ds, &reply);
225         free(reply.data);
226         reply.data = NULL;
227
228         return 1;
229 }
230
231 /*
232  * Acknowledge received is for one of the following messages sent earlier
233  * 1. Handshake completed Message, so now send, EAP-Success
234  * 2. Alert Message, now send, EAP-Failure
235  * 3. Fragment Message, now send, next Fragment
236  */
237 static eaptls_status_t eaptls_ack_handler(EAP_HANDLER *handler)
238 {
239         tls_session_t *tls_session;
240         REQUEST *request = handler->request;
241
242         tls_session = (tls_session_t *)handler->opaque;
243         if (tls_session == NULL){
244                 radlog_request(L_ERR, 0, request, "FAIL: Unexpected ACK received.  Could not obtain session information.");
245                 return EAPTLS_FAIL;
246         }
247         if (tls_session->info.initialized == 0) {
248                 RDEBUG("No SSL info available. Waiting for more SSL data.");
249                 return EAPTLS_REQUEST;
250         }
251         if ((tls_session->info.content_type == handshake) &&
252             (tls_session->info.origin == 0)) {
253                 radlog_request(L_ERR, 0, request, "FAIL: ACK without earlier message.");
254                 return EAPTLS_FAIL;
255         }
256
257         switch (tls_session->info.content_type) {
258         case alert:
259                 RDEBUG2("ACK alert");
260                 eaptls_fail(handler, tls_session->peap_flag);
261                 return EAPTLS_FAIL;
262
263         case handshake:
264                 if (tls_session->info.handshake_type == finished) {
265                         RDEBUG2("ACK handshake is finished");
266
267                         /* 
268                          *      From now on all the content is
269                          *      application data set it here as nobody else
270                          *      sets it.
271                          */
272                         tls_session->info.content_type = application_data;
273                         return EAPTLS_SUCCESS;
274                 } /* else more data to send */
275
276                 RDEBUG2("ACK handshake fragment handler");
277                 /* Fragmentation handler, send next fragment */
278                 return EAPTLS_REQUEST;
279
280         case application_data:
281                 RDEBUG2("ACK handshake fragment handler in application data");
282                 return EAPTLS_REQUEST;
283                                                 
284                 /*
285                  *      For the rest of the conditions, switch over
286                  *      to the default section below.
287                  */
288         default:
289                 RDEBUG2("ACK default");
290                 radlog_request(L_ERR, 0, request, "Invalid ACK received: %d",
291                        tls_session->info.content_type);
292                 return EAPTLS_FAIL;
293         }
294 }
295
296 /*
297  *      Similarly, when the EAP server receives an EAP-Response with
298  *      the M bit set, it MUST respond with an EAP-Request with
299  *      EAP-Type=EAP-TLS and no data. This serves as a fragment ACK.
300  *
301  *      In order to prevent errors in the processing of fragments, the
302  *      EAP server MUST use increment the Identifier value for each
303  *      fragment ACK contained within an EAP-Request, and the peer
304  *      MUST include this Identifier value in the subsequent fragment
305  *      contained within an EAP- Reponse.
306  *
307  *      EAP server sends an ACK when it determines there are More
308  *      fragments to receive to make the complete
309  *      TLS-record/TLS-Message
310  */
311 static int eaptls_send_ack(EAP_DS *eap_ds, int peap_flag)
312 {
313         EAPTLS_PACKET   reply;
314
315         reply.code = EAPTLS_ACK;
316         reply.length = TLS_HEADER_LEN + 1/*flags*/;
317         reply.flags = peap_flag;
318         reply.data = NULL;
319         reply.dlen = 0;
320
321         eaptls_compose(eap_ds, &reply);
322
323         return 1;
324 }
325
326 /*
327  *      The S flag is set only within the EAP-TLS start message sent
328  *      from the EAP server to the peer.
329  *
330  *      Similarly, when the EAP server receives an EAP-Response with
331  *      the M bit set, it MUST respond with an EAP-Request with
332  *      EAP-Type=EAP-TLS and no data. This serves as a fragment
333  *      ACK. The EAP peer MUST wait.
334  */
335 static eaptls_status_t eaptls_verify(EAP_HANDLER *handler)
336 {
337         EAP_DS *eap_ds = handler->eap_ds;
338         EAP_DS *prev_eap_ds = handler->prev_eapds;
339         eaptls_packet_t *eaptls_packet, *eaptls_prev = NULL;
340         REQUEST *request = handler->request;
341
342         /*
343          *      We don't check ANY of the input parameters.  It's all
344          *      code which works together, so if something is wrong,
345          *      we SHOULD core dump.
346          *
347          *      e.g. if eap_ds is NULL, of if eap_ds->response is
348          *      NULL, of if it's NOT an EAP-Response, or if the packet
349          *      is too short.  See eap_validation()., in ../../eap.c
350          *
351          *      Also, eaptype_select() takes care of selecting the
352          *      appropriate type, so we don't need to check
353          *      eap_ds->response->type.type == PW_EAP_TLS, or anything
354          *      else.
355          */
356         eaptls_packet = (eaptls_packet_t *)eap_ds->response->type.data;
357         if (prev_eap_ds && prev_eap_ds->response)
358                 eaptls_prev = (eaptls_packet_t *)prev_eap_ds->response->type.data;
359
360         /*
361          *      check for ACK
362          *
363          *      If there's no TLS data, or there's 1 byte of TLS data,
364          *      with the flags set to zero, then it's an ACK.
365          *
366          *      Find if this is a reply to the previous request sent
367          */
368         if ((eaptls_packet == NULL) ||
369             ((eap_ds->response->length == EAP_HEADER_LEN + 2) &&
370              ((eaptls_packet->flags & 0xc0) == 0x00))) {
371
372 #if 0
373                 /*
374                  *      Un-comment this for TLS inside of TTLS/PEAP
375                  */
376                 RDEBUG2("Received EAP-TLS ACK message");
377                 return eaptls_ack_handler(handler);
378 #else
379                 if (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 eaptls_ack_handler(handler);
385                 } else {
386                         radlog_request(L_ERR, 0, request, "Received Invalid TLS ACK");
387                         return EAPTLS_INVALID;
388                 }
389 #endif
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 EAPTLS_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 EAPTLS_FIRST_FRAGMENT;
430                         } else {
431
432                                 RDEBUG2("More Fragments with length included");
433                                 return EAPTLS_MORE_FRAGMENTS_WITH_LENGTH;
434                         }
435                 } else {
436                         RDEBUG2("Length Included");
437                         return EAPTLS_LENGTH_INCLUDED;
438                 }
439         }
440
441         if (TLS_MORE_FRAGMENTS(eaptls_packet->flags)) {
442                 RDEBUG2("More fragments to follow");
443                 return EAPTLS_MORE_FRAGMENTS;
444         }
445
446         /*
447          *      None of the flags are set, but it's still a valid
448          *      EAPTLS packet.
449          */
450         return EAPTLS_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, eaptls_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  == EAPTLS_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 EAPTLS_FIRST_FRAGMENT:
579         case EAPTLS_LENGTH_INCLUDED:
580         case EAPTLS_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 EAPTLS_MORE_FRAGMENTS:
609         case EAPTLS_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 eaptls_status_t eaptls_operation(eaptls_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 == EAPTLS_MORE_FRAGMENTS) ||
666             (status == EAPTLS_MORE_FRAGMENTS_WITH_LENGTH) ||
667             (status == EAPTLS_FIRST_FRAGMENT)) {
668                 /*
669                  *      Send the ACK.
670                  */
671                 eaptls_send_ack(handler->eap_ds, tls_session->peap_flag);
672                 return EAPTLS_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(tls_session)) {
688                 DEBUG2("TLS receive handshake failed during operation");
689                 eaptls_fail(handler, tls_session->peap_flag);
690                 return EAPTLS_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 EAPTLS_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 EAPTLS_SUCCESS;
717         }
718         
719         /*
720          *      Who knows what happened...
721          */
722         DEBUG2("TLS failed during operation");
723         return EAPTLS_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 eaptls_status_t eaptls_process(EAP_HANDLER *handler)
755 {
756         tls_session_t *tls_session = (tls_session_t *) handler->opaque;
757         EAPTLS_PACKET   *tlspacket;
758         eaptls_status_t status;
759         REQUEST *request = handler->request;
760
761         RDEBUG2("processing EAP-TLS");
762
763         /* This case is when SSL generates Alert then we
764          * send that alert to the client and then send the EAP-Failure
765          */
766         status = eaptls_verify(handler);
767         RDEBUG2("eaptls_verify returned %d\n", status);
768
769         switch (status) {
770         default:
771         case EAPTLS_INVALID:
772         case EAPTLS_FAIL:
773
774                 /*
775                  *      Success means that we're done the initial
776                  *      handshake.  For TTLS, this means send stuff
777                  *      back to the client, and the client sends us
778                  *      more tunneled data.
779                  */
780         case EAPTLS_SUCCESS:
781                 return status;
782                 break;
783
784                 /*
785                  *      Normal TLS request, continue with the "get rest
786                  *      of fragments" phase.
787                  */
788         case EAPTLS_REQUEST:
789                 eaptls_request(handler->eap_ds, tls_session);
790                 return EAPTLS_HANDLED;
791                 break;
792
793                 /*
794                  *      The handshake is done, and we're in the "tunnel
795                  *      data" phase.
796                  */
797         case EAPTLS_OK:
798                 RDEBUG2("Done initial handshake");
799
800                 /*
801                  *      Get the rest of the fragments.
802                  */
803         case EAPTLS_FIRST_FRAGMENT:
804         case EAPTLS_MORE_FRAGMENTS:
805         case EAPTLS_LENGTH_INCLUDED:
806         case EAPTLS_MORE_FRAGMENTS_WITH_LENGTH:
807                 break;
808         }
809
810         /*
811          *      Extract the TLS packet from the buffer.
812          */
813         if ((tlspacket = eaptls_extract(request, handler->eap_ds, status)) == NULL)
814                 return EAPTLS_FAIL;
815
816         /*
817          *      Get the session struct from the handler
818          *
819          *      update the dirty_in buffer
820          *
821          *      NOTE: This buffer will contain partial data when M bit is set.
822          *
823          *      CAUTION while reinitializing this buffer, it should be
824          *      reinitialized only when this M bit is NOT set.
825          */
826         if (tlspacket->dlen !=
827             (tls_session->record_plus)(&tls_session->dirty_in, tlspacket->data, tlspacket->dlen)) {
828                 eaptls_free(&tlspacket);
829                 RDEBUG("Exceeded maximum record size");
830                 return EAPTLS_FAIL;
831         }
832
833         /*
834          *      No longer needed.
835          */
836         eaptls_free(&tlspacket);
837
838         /*
839          *      SSL initalization is done.  Return.
840          *
841          *      The TLS data will be in the tls_session structure.
842          */
843         if (SSL_is_init_finished(tls_session->ssl)) {
844                 int err;
845
846                 /*
847                  *      The initialization may be finished, but if
848                  *      there more fragments coming, then send ACK,
849                  *      and get the caller to continue the
850                  *      conversation.
851                  */     
852                 if ((status == EAPTLS_MORE_FRAGMENTS) ||
853                     (status == EAPTLS_MORE_FRAGMENTS_WITH_LENGTH) ||
854                     (status == EAPTLS_FIRST_FRAGMENT)) {
855                         /*
856                          *      Send the ACK.
857                          */
858                         eaptls_send_ack(handler->eap_ds,
859                                         tls_session->peap_flag);
860                         RDEBUG2("Init is done, but tunneled data is fragmented");
861                         return EAPTLS_HANDLED;
862                 }
863
864                 /*      
865                  *      Decrypt the complete record.
866                  */
867                 BIO_write(tls_session->into_ssl, tls_session->dirty_in.data,
868                           tls_session->dirty_in.used);
869
870                 /*
871                  *      Clear the dirty buffer now that we are done with it
872                  *      and init the clean_out buffer to store decrypted data
873                  */
874                 (tls_session->record_init)(&tls_session->dirty_in);
875                 (tls_session->record_init)(&tls_session->clean_out);
876
877                 /*
878                  *      Read (and decrypt) the tunneled data from the
879                  *      SSL session, and put it into the decrypted
880                  *      data buffer.
881                  */
882                 err = SSL_read(tls_session->ssl, tls_session->clean_out.data,
883                                sizeof(tls_session->clean_out.data));
884
885                 if (err < 0) {
886                         RDEBUG("SSL_read Error");
887
888                         switch (SSL_get_error(tls_session->ssl, err)) {
889                         case SSL_ERROR_WANT_READ:
890                         case SSL_ERROR_WANT_WRITE:
891                                 RDEBUG("Error in fragmentation logic");
892                                 break;
893                         default:
894                                 /*
895                                  *      FIXME: Call int_ssl_check?
896                                  */
897                                 break;
898                         }
899                         return EAPTLS_FAIL;
900                 }
901
902                 if (err == 0) {
903                         RDEBUG("WARNING: No data inside of the tunnel.");
904                 }
905         
906                 /*
907                  *      Passed all checks, successfully decrypted data
908                  */
909                 tls_session->clean_out.used = err;
910                 
911                 return EAPTLS_OK;
912         }
913
914         /*
915          *      Continue the handshake.
916          */
917         return eaptls_operation(status, handler);
918 }
919
920
921 /*
922  *      compose the TLS reply packet in the EAP reply typedata
923  */
924 int eaptls_compose(EAP_DS *eap_ds, EAPTLS_PACKET *reply)
925 {
926         uint8_t *ptr;
927
928         /*
929          *      Don't set eap_ds->request->type.type, as the main EAP
930          *      handler will do that for us.  This allows the TLS
931          *      module to be called from TTLS & PEAP.
932          */
933
934         /*
935          *      When the EAP server receives an EAP-Response with the
936          *      M bit set, it MUST respond with an EAP-Request with
937          *      EAP-Type=EAP-TLS and no data. This serves as a
938          *      fragment ACK. The EAP peer MUST wait until it receives
939          *      the EAP-Request before sending another fragment.
940          *
941          *      In order to prevent errors in the processing of
942          *      fragments, the EAP server MUST use increment the
943          *      Identifier value for each fragment ACK contained
944          *      within an EAP-Request, and the peer MUST include this
945          *      Identifier value in the subsequent fragment contained
946          *      within an EAP- Reponse.
947          */
948         eap_ds->request->type.data = malloc(reply->length - TLS_HEADER_LEN + 1);
949         if (eap_ds->request->type.data == NULL) {
950                 radlog(L_ERR, "out of memory");
951                 return 0;
952         }
953
954         /* EAPTLS Header length is excluded while computing EAP typelen */
955         eap_ds->request->type.length = reply->length - TLS_HEADER_LEN;
956
957         ptr = eap_ds->request->type.data;
958         *ptr++ = (uint8_t)(reply->flags & 0xFF);
959
960         if (reply->dlen) memcpy(ptr, reply->data, reply->dlen);
961
962         switch (reply->code) {
963         case EAPTLS_ACK:
964         case EAPTLS_START:
965         case EAPTLS_REQUEST:
966                 eap_ds->request->code = PW_EAP_REQUEST;
967                 break;
968         case EAPTLS_SUCCESS:
969                 eap_ds->request->code = PW_EAP_SUCCESS;
970                 break;
971         case EAPTLS_FAIL:
972                 eap_ds->request->code = PW_EAP_FAILURE;
973                 break;
974         default:
975                 /* Should never enter here */
976                 eap_ds->request->code = PW_EAP_FAILURE;
977                 break;
978         }
979
980         return 1;
981 }