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