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