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