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