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