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