fadc72c81082f5609277c2f0b5b174007a5d50f7
[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         tls_session_t           *tls_session = handler->opaque;
305         EAP_DS                  *prev_eap_ds = handler->prev_eapds;
306         eaptls_packet_t         *eaptls_packet, *eaptls_prev = NULL;
307         REQUEST                 *request = handler->request;
308         size_t                  frag_len;
309
310         /*
311          *      We don't check ANY of the input parameters.  It's all
312          *      code which works together, so if something is wrong,
313          *      we SHOULD core dump.
314          *
315          *      e.g. if eap_ds is NULL, of if eap_ds->response is
316          *      NULL, of if it's NOT an EAP-Response, or if the packet
317          *      is too short.  See eap_validation()., in ../../eap.c
318          *
319          *      Also, eap_method_select() takes care of selecting the
320          *      appropriate type, so we don't need to check
321          *      eap_ds->response->type.num == PW_EAP_TLS, or anything
322          *      else.
323          */
324         eaptls_packet = (eaptls_packet_t *)eap_ds->response->type.data;
325         if (prev_eap_ds && prev_eap_ds->response)
326                 eaptls_prev = (eaptls_packet_t *)prev_eap_ds->response->type.data;
327
328         /*
329          *      First output the flags (for debugging)
330          */
331         RDEBUG3("Peer sent flags %c%c%c",
332                 TLS_START(eaptls_packet->flags) ? 'S' : '-',
333                 TLS_MORE_FRAGMENTS(eaptls_packet->flags) ? 'M' : '-',
334                 TLS_LENGTH_INCLUDED(eaptls_packet->flags) ? 'L' : '-');
335
336         /*
337          *      check for ACK
338          *
339          *      If there's no TLS data, or there's 1 byte of TLS data,
340          *      with the flags set to zero, then it's an ACK.
341          *
342          *      Find if this is a reply to the previous request sent
343          */
344         if ((!eaptls_packet) ||
345             ((eap_ds->response->length == EAP_HEADER_LEN + 2) &&
346              ((eaptls_packet->flags & 0xc0) == 0x00))) {
347
348                 if (prev_eap_ds && (prev_eap_ds->request->id == eap_ds->response->id)) {
349                         return tls_ack_handler(handler->opaque, request);
350                 } else {
351                         REDEBUG("Received Invalid TLS ACK");
352                         return FR_TLS_INVALID;
353                 }
354         }
355
356         /*
357          *      We send TLS_START, but do not receive it.
358          */
359         if (TLS_START(eaptls_packet->flags)) {
360                 REDEBUG("Peer sent EAP-TLS Start message (only the server is allowed to do this)");
361                 return FR_TLS_INVALID;
362         }
363
364         /*
365          *      Calculate this fragment's length
366          */
367         frag_len = eap_ds->response->length -
368                    (EAP_HEADER_LEN + (TLS_LENGTH_INCLUDED(eaptls_packet->flags) ? 6 : 2));
369
370         /*
371          *      The L bit (length included) is set to indicate the
372          *      presence of the four octet TLS Message Length field,
373          *      and MUST be set for the first fragment of a fragmented
374          *      TLS message or set of messages.
375          *
376          *      The M bit (more fragments) is set on all but the last
377          *      fragment.
378          *
379          *      The S bit (EAP-TLS start) is set in an EAP-TLS Start
380          *      message. This differentiates the EAP-TLS Start message
381          *      from a fragment acknowledgement.
382          */
383         if (TLS_LENGTH_INCLUDED(eaptls_packet->flags)) {
384                 size_t total_len = eaptls_packet->data[2] * 256 | eaptls_packet->data[3];
385
386                 if (frag_len > total_len) {
387                         RWDEBUG("TLS fragment length (%zu bytes) greater than TLS record length (%zu bytes)", frag_len,
388                                 total_len);
389                 }
390
391                 RDEBUG2("Peer indicated complete TLS record size will be %zu bytes", total_len);
392                 if (TLS_MORE_FRAGMENTS(eaptls_packet->flags)) {
393                         /*
394                          *      The supplicant is free to send fragments of wildly varying
395                          *      lengths, but the vast majority won't.
396                          *
397                          *      In this calculation we take into account the fact that the future
398                          *      fragments are likely to be 4 bytes larger than the initial one
399                          *      as they won't contain the length field.
400                          */
401                         if (frag_len + 4) {     /* check for wrap, else clang scan gets excited */
402                                 RDEBUG2("Expecting %i TLS record fragments",
403                                         (int)((((total_len - frag_len) + ((frag_len + 4) - 1)) / (frag_len + 4)) + 1));
404                         }
405
406                         /*
407                          *      FIRST_FRAGMENT is identified
408                          *      1. If there is no previous EAP-response received.
409                          *      2. If EAP-response received, then its M bit not set.
410                          *         (It is because Last fragment will not have M bit set)
411                          */
412                         if (!prev_eap_ds || (!prev_eap_ds->response) || (!eaptls_prev) ||
413                             !TLS_MORE_FRAGMENTS(eaptls_prev->flags)) {
414                                 RDEBUG2("Got first TLS record fragment (%zu bytes).  Peer indicated more fragments "
415                                         "to follow", frag_len);
416                                 tls_session->tls_record_in_total_len = total_len;
417                                 tls_session->tls_record_in_recvd_len = frag_len;
418
419                                 return FR_TLS_FIRST_FRAGMENT;
420                         }
421
422                         RDEBUG2("Got additional TLS record fragment with length (%zu bytes).  "
423                                 "Peer indicated more fragments to follow", frag_len);
424
425                         /*
426                          *      Check we've not exceeded the originally indicated TLS record size.
427                          */
428                         tls_session->tls_record_in_recvd_len += frag_len;
429                         if (tls_session->tls_record_in_recvd_len > tls_session->tls_record_in_total_len) {
430                                 RWDEBUG("Total received TLS record fragments (%zu bytes), exceeds "
431                                         "total TLS record length (%zu bytes)", frag_len, total_len);
432                         }
433
434                         return FR_TLS_MORE_FRAGMENTS_WITH_LENGTH;
435                 }
436
437                 /*
438                  *      If it's a complete record, our fragment size should match the
439                  *      value of the four octet TLS length field.
440                  */
441                 if (total_len != frag_len) {
442                         RWDEBUG("Peer indicated no more fragments, but TLS record length (%zu bytes) "
443                                 "does not match EAP-TLS data length (%zu bytes)", total_len, frag_len);
444                 }
445
446                 tls_session->tls_record_in_total_len = total_len;
447                 tls_session->tls_record_in_recvd_len = frag_len;
448                 RDEBUG2("Got complete TLS record (%zu bytes)", frag_len);
449                 return FR_TLS_LENGTH_INCLUDED;
450         }
451
452         /*
453          *      The previous packet had the M flags set, but this one doesn't,
454          *      this must be the final record fragment
455          */
456         if ((eaptls_prev && TLS_MORE_FRAGMENTS(eaptls_prev->flags)) && !TLS_MORE_FRAGMENTS(eaptls_packet->flags)) {
457                 RDEBUG2("Got final TLS record fragment (%zu bytes)", frag_len);
458                 tls_session->tls_record_in_recvd_len += frag_len;
459                 if (tls_session->tls_record_in_recvd_len != tls_session->tls_record_in_total_len) {
460                         RWDEBUG("Total received TLS record fragments (%zu bytes), does not equal indicated "
461                                 "TLS record length (%zu bytes)",
462                                 tls_session->tls_record_in_recvd_len, tls_session->tls_record_in_total_len);
463                 }
464         }
465
466         if (TLS_MORE_FRAGMENTS(eaptls_packet->flags)) {
467                 RDEBUG2("Got additional TLS record fragment (%zu bytes).  Peer indicated more fragments to follow",
468                         frag_len);
469                 tls_session->tls_record_in_recvd_len += frag_len;
470                 if (tls_session->tls_record_in_recvd_len > tls_session->tls_record_in_total_len) {
471                         RWDEBUG("Total received TLS record fragments (%zu bytes), exceeds "
472                                 "indicated TLS record length (%zu bytes)",
473                                 tls_session->tls_record_in_recvd_len, tls_session->tls_record_in_total_len);
474                 }
475                 return FR_TLS_MORE_FRAGMENTS;
476         }
477
478         /*
479          *      None of the flags are set, but it's still a valid EAP-TLS packet.
480          */
481         return FR_TLS_OK;
482 }
483
484 /*
485  * EAPTLS_PACKET
486  * code    = EAP-code
487  * id      = EAP-id
488  * length  = code + id + length + flags + tlsdata
489  *         =  1   +  1 +   2    +  1    +  X
490  * length  = EAP-length - 1(EAP-Type = 1 octet)
491  * flags   = EAP-typedata[0] (1 octet)
492  * dlen    = EAP-typedata[1-4] (4 octets), if L flag set
493  *         = length - 5(code+id+length+flags), otherwise
494  * data    = EAP-typedata[5-n], if L flag set
495  *         = EAP-typedata[1-n], otherwise
496  * packet  = EAP-typedata (complete typedata)
497  *
498  * Points to consider during EAP-TLS data extraction
499  * 1. In the received packet, No data will be present incase of ACK-NAK
500  * 2. Incase if more fragments need to be received then ACK after retreiving this fragment.
501  *
502  *  RFC 2716 Section 4.2.  PPP EAP TLS Request Packet
503  *
504  *  0              1               2               3
505  *  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
506  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
507  *  |     Code      |   Identifier  |       Length           |
508  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
509  *  |     Type      |     Flags     |      TLS Message Length
510  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
511  *  |     TLS Message Length    |       TLS Data...
512  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
513  *
514  *  The Length field is two octets and indicates the length of the EAP
515  *  packet including the Code, Identifir, Length, Type, and TLS data
516  *  fields.
517  */
518 static EAPTLS_PACKET *eaptls_extract(REQUEST *request, EAP_DS *eap_ds, fr_tls_status_t status)
519 {
520         EAPTLS_PACKET   *tlspacket;
521         uint32_t        data_len = 0;
522         uint32_t        len = 0;
523         uint8_t         *data = NULL;
524
525         if (status == FR_TLS_INVALID) return NULL;
526
527         /*
528          *      The main EAP code & eaptls_verify() take care of
529          *      ensuring that the packet is OK, and that we can
530          *      extract the various fields we want.
531          *
532          *      e.g. a TLS packet with zero data is allowed as an ACK,
533          *      but we will never see it here, as we will simply
534          *      send another fragment, instead of trying to extract
535          *      the data.
536          *
537          *      MUST have TLS type octet, followed by flags, followed
538          *      by data.
539          */
540         assert(eap_ds->response->length > 2);
541
542         tlspacket = talloc(eap_ds, EAPTLS_PACKET);
543         if (!tlspacket) return NULL;
544
545         /*
546          *      Code & id for EAPTLS & EAP are same
547          *      but eaptls_length = eap_length - 1(EAP-Type = 1 octet)
548          *
549          *      length = code + id + length + type + tlsdata
550          *             =  1   +  1 +   2    +  1    +  X
551          */
552         tlspacket->code = eap_ds->response->code;
553         tlspacket->id = eap_ds->response->id;
554         tlspacket->length = eap_ds->response->length - 1; /* EAP type */
555         tlspacket->flags = eap_ds->response->type.data[0];
556
557         /*
558          *      A quick sanity check of the flags.  If we've been told
559          *      that there's a length, and there isn't one, then stop.
560          */
561         if (TLS_LENGTH_INCLUDED(tlspacket->flags) &&
562             (tlspacket->length < 5)) { /* flags + TLS message length */
563                 REDEBUG("Invalid EAP-TLS packet received:  Length bit is set, "
564                         "but packet too short to contain length field");
565                 talloc_free(tlspacket);
566                 return NULL;
567         }
568
569         /*
570          *      If the final TLS packet is larger than we can handle, die
571          *      now.
572          *
573          *      Likewise, if the EAP packet says N bytes, and the TLS
574          *      packet says there's fewer bytes, it's a problem.
575          */
576         if (TLS_LENGTH_INCLUDED(tlspacket->flags)) {
577                 memcpy(&data_len, &eap_ds->response->type.data[1], 4);
578                 data_len = ntohl(data_len);
579                 if (data_len > MAX_RECORD_SIZE) {
580                         REDEBUG("Reassembled TLS record will be %u bytes, "
581                                 "greater than our maximum record size (" STRINGIFY(MAX_RECORD_SIZE) " bytes)",
582                                 data_len);
583                         talloc_free(tlspacket);
584                         return NULL;
585                 }
586         }
587
588         switch (status) {
589         /*
590          *      The TLS Message Length field is four octets, and
591          *      provides the total length of the TLS message or set of
592          *      messages that is being fragmented; this simplifies
593          *      buffer allocation.
594          *
595          *      Dynamic allocation of buffers as & when we know the
596          *      length should solve the problem.
597          */
598         case FR_TLS_FIRST_FRAGMENT:
599         case FR_TLS_LENGTH_INCLUDED:
600         case FR_TLS_MORE_FRAGMENTS_WITH_LENGTH:
601                 if (tlspacket->length < 5) { /* flags + TLS message length */
602                         REDEBUG("Invalid EAP-TLS packet received: Expected length, got none");
603                         talloc_free(tlspacket);
604                         return NULL;
605                 }
606
607                 /*
608                  *      Extract all the TLS fragments from the
609                  *      previous eap_ds Start appending this
610                  *      fragment to the above ds
611                  */
612                 memcpy(&data_len, &eap_ds->response->type.data[1], sizeof(uint32_t));
613                 data_len = ntohl(data_len);
614                 data = (eap_ds->response->type.data + 5/*flags+TLS-Length*/);
615                 len = eap_ds->response->type.length - 5/*flags+TLS-Length*/;
616
617                 /*
618                  *      Hmm... this should be an error, too.
619                  */
620                 if (data_len > len) {
621                         data_len = len;
622                 }
623                 break;
624
625                 /*
626                  *      Data length is implicit, from the EAP header.
627                  */
628         case FR_TLS_MORE_FRAGMENTS:
629         case FR_TLS_OK:
630                 data_len = eap_ds->response->type.length - 1/*flags*/;
631                 data = eap_ds->response->type.data + 1/*flags*/;
632                 break;
633
634         default:
635                 REDEBUG("Invalid EAP-TLS packet received");
636                 talloc_free(tlspacket);
637                 return NULL;
638         }
639
640         tlspacket->dlen = data_len;
641         if (data_len) {
642                 tlspacket->data = talloc_array(tlspacket, uint8_t,
643                                                data_len);
644                 if (!tlspacket->data) {
645                         talloc_free(tlspacket);
646                         return NULL;
647                 }
648                 memcpy(tlspacket->data, data, data_len);
649         }
650
651         return tlspacket;
652 }
653
654
655
656 /*
657  * To process the TLS,
658  *  INCOMING DATA:
659  *      1. EAP-TLS should get the compelete TLS data from the peer.
660  *      2. Store that data in a data structure with any other required info
661  *      3. Handle that data structure to the TLS module.
662  *      4. TLS module will perform its operations on the data and
663  *      handle back to EAP-TLS
664  *
665  *  OUTGOING DATA:
666  *      1. EAP-TLS if necessary will fragment it and send it to the
667  *      destination.
668  *
669  *      During EAP-TLS initialization, TLS Context object will be
670  *      initialized and stored.  For every new authentication
671  *      requests, TLS will open a new session object and that session
672  *      object should be maintained even after the session is
673  *      completed for session resumption. (Probably later as a feature
674  *      as we donot know who maintains these session objects ie,
675  *      SSL_CTX (internally) or TLS module(explicitly). If TLS module,
676  *      then how to let SSL API know about these sessions.)
677  */
678 static fr_tls_status_t eaptls_operation(fr_tls_status_t status, eap_handler_t *handler)
679 {
680         REQUEST         *request = handler->request;
681         tls_session_t   *tls_session = handler->opaque;
682
683         if ((status == FR_TLS_MORE_FRAGMENTS) ||
684             (status == FR_TLS_MORE_FRAGMENTS_WITH_LENGTH) ||
685             (status == FR_TLS_FIRST_FRAGMENT)) {
686                 /*
687                  *      Send the ACK.
688                  */
689                 eaptls_send_ack(handler, tls_session->peap_flag);
690                 return FR_TLS_HANDLED;
691
692         }
693
694         /*
695          *      We have the complete TLS-data or TLS-message.
696          *
697          *      Clean the dirty message.
698          *
699          *      Authenticate the user and send
700          *      Success/Failure.
701          *
702          *      If more info
703          *      is required then send another request.
704          */
705         if (!tls_handshake_recv(handler->request, tls_session)) {
706                 REDEBUG("TLS receive handshake failed during operation");
707                 tls_fail(tls_session);
708                 return FR_TLS_FAIL;
709         }
710
711         /*
712          *      FIXME: return success/fail.
713          *
714          *      TLS proper can decide what to do, then.
715          */
716         if (tls_session->dirty_out.used > 0) {
717                 eaptls_request(handler->eap_ds, tls_session);
718                 return FR_TLS_HANDLED;
719         }
720
721         /*
722          *      If there is no data to send i.e
723          *      dirty_out.used <=0 and if the SSL
724          *      handshake is finished, then return a
725          *      EPTLS_SUCCESS
726          */
727
728         if (SSL_is_init_finished(tls_session->ssl)) {
729                 /*
730                  *      Init is finished.  The rest is
731                  *      application data.
732                  */
733                 tls_session->info.content_type = application_data;
734                 return FR_TLS_SUCCESS;
735         }
736
737         /*
738          *      Who knows what happened...
739          */
740         REDEBUG("TLS failed during operation");
741         return FR_TLS_FAIL;
742 }
743
744
745 /*
746  * In the actual authentication first verify the packet and then create the data structure
747  */
748 /*
749  * To process the TLS,
750  *  INCOMING DATA:
751  *      1. EAP-TLS should get the compelete TLS data from the peer.
752  *      2. Store that data in a data structure with any other required info
753  *      3. Hand this data structure to the TLS module.
754  *      4. TLS module will perform its operations on the data and hands back to EAP-TLS
755  *  OUTGOING DATA:
756  *      1. EAP-TLS if necessary will fragment it and send it to the destination.
757  *
758  *      During EAP-TLS initialization, TLS Context object will be
759  *      initialized and stored.  For every new authentication
760  *      requests, TLS will open a new session object and that
761  *      session object SHOULD be maintained even after the session
762  *      is completed, for session resumption. (Probably later as a
763  *      feature, as we do not know who maintains these session
764  *      objects ie, SSL_CTX (internally) or TLS module (explicitly). If
765  *      TLS module, then how to let SSL API know about these
766  *      sessions.)
767  */
768
769 /*
770  *      Process an EAP request
771  */
772 fr_tls_status_t eaptls_process(eap_handler_t *handler)
773 {
774         tls_session_t *tls_session = (tls_session_t *) handler->opaque;
775         EAPTLS_PACKET   *tlspacket;
776         fr_tls_status_t status;
777         REQUEST *request = handler->request;
778
779         if (!request) return FR_TLS_FAIL;
780
781         RDEBUG2("Continuing EAP-TLS");
782
783         SSL_set_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST, request);
784
785         if (handler->certs) fr_pair_add(&request->packet->vps,
786                                     fr_pair_list_copy(request->packet, handler->certs));
787
788         /*
789          *      This case is when SSL generates Alert then we
790          *      send that alert to the client and then send the EAP-Failure
791          */
792         status = eaptls_verify(handler);
793         if ((status == FR_TLS_INVALID) || (status == FR_TLS_FAIL)) {
794                 REDEBUG("[eaptls verify] = %s", fr_int2str(fr_tls_status_table, status, "<INVALID>"));
795         } else {
796                 RDEBUG2("[eaptls verify] = %s", fr_int2str(fr_tls_status_table, status, "<INVALID>"));
797         }
798
799         switch (status) {
800         default:
801         case FR_TLS_INVALID:
802         case FR_TLS_FAIL:
803
804         /*
805          *      Success means that we're done the initial
806          *      handshake.  For TTLS, this means send stuff
807          *      back to the client, and the client sends us
808          *      more tunneled data.
809          */
810         case FR_TLS_SUCCESS:
811                 goto done;
812
813         /*
814          *      Normal TLS request, continue with the "get rest
815          *      of fragments" phase.
816          */
817         case FR_TLS_REQUEST:
818                 eaptls_request(handler->eap_ds, tls_session);
819                 status = FR_TLS_HANDLED;
820                 goto done;
821
822         /*
823          *      The handshake is done, and we're in the "tunnel
824          *      data" phase.
825          */
826         case FR_TLS_OK:
827                 RDEBUG2("Done initial handshake");
828
829         /*
830          *      Get the rest of the fragments.
831          */
832         case FR_TLS_FIRST_FRAGMENT:
833         case FR_TLS_MORE_FRAGMENTS:
834         case FR_TLS_LENGTH_INCLUDED:
835         case FR_TLS_MORE_FRAGMENTS_WITH_LENGTH:
836                 break;
837         }
838
839         /*
840          *      Extract the TLS packet from the buffer.
841          */
842         if ((tlspacket = eaptls_extract(request, handler->eap_ds, status)) == NULL) {
843                 status = FR_TLS_FAIL;
844                 goto done;
845         }
846
847         /*
848          *      Get the session struct from the handler
849          *
850          *      update the dirty_in buffer
851          *
852          *      NOTE: This buffer will contain partial data when M bit is set.
853          *
854          *      CAUTION while reinitializing this buffer, it should be
855          *      reinitialized only when this M bit is NOT set.
856          */
857         if (tlspacket->dlen !=
858             (tls_session->record_plus)(&tls_session->dirty_in, tlspacket->data, tlspacket->dlen)) {
859                 talloc_free(tlspacket);
860                 REDEBUG("Exceeded maximum record size");
861                 status = FR_TLS_FAIL;
862                 goto done;
863         }
864
865         /*
866          *      No longer needed.
867          */
868         talloc_free(tlspacket);
869
870         /*
871          *      SSL initalization is done.  Return.
872          *
873          *      The TLS data will be in the tls_session structure.
874          */
875         if (SSL_is_init_finished(tls_session->ssl)) {
876                 /*
877                  *      The initialization may be finished, but if
878                  *      there more fragments coming, then send ACK,
879                  *      and get the caller to continue the
880                  *      conversation.
881                  */
882                 if ((status == FR_TLS_MORE_FRAGMENTS) ||
883                     (status == FR_TLS_MORE_FRAGMENTS_WITH_LENGTH) ||
884                     (status == FR_TLS_FIRST_FRAGMENT)) {
885                         /*
886                          *      Send the ACK.
887                          */
888                         eaptls_send_ack(handler, tls_session->peap_flag);
889                         RDEBUG2("Init is done, but tunneled data is fragmented");
890                         status = FR_TLS_HANDLED;
891                         goto done;
892                 }
893
894                 status = tls_application_data(tls_session, request);
895                 goto done;
896         }
897
898         /*
899          *      Continue the handshake.
900          */
901         status = eaptls_operation(status, handler);
902         if (status == FR_TLS_SUCCESS) {
903 #define MAX_SESSION_SIZE (256)
904                 VALUE_PAIR *vps;
905                 char buffer[2 * MAX_SESSION_SIZE + 1];
906
907                 /*
908                  *      Restore the cached VPs before processing the
909                  *      application data.
910                  */
911                 tls_session_id(tls_session->ssl_session, buffer, MAX_SESSION_SIZE);
912
913                 vps = SSL_SESSION_get_ex_data(tls_session->ssl_session, fr_tls_ex_index_vps);
914                 if (!vps) {
915                         RWDEBUG("No information in cached session %s", buffer);
916                 } else {
917                         vp_cursor_t cursor;
918                         VALUE_PAIR *vp;
919
920                         RDEBUG("Adding cached attributes from session %s", buffer);
921
922                         /*
923                          *      The cbtls_get_session() function doesn't have
924                          *      access to sock->certs or handler->certs, which
925                          *      is where the certificates normally live.  So
926                          *      the certs are all in the VPS list here, and
927                          *      have to be manually extracted.
928                          */
929                         RINDENT();
930                         for (vp = fr_cursor_init(&cursor, &vps);
931                              vp;
932                              vp = fr_cursor_next(&cursor)) {
933                                 /*
934                                  *      TLS-* attrs get added back to
935                                  *      the request list.
936                                  */
937                                 if ((vp->da->vendor == 0) &&
938                                     (vp->da->attr >= PW_TLS_CERT_SERIAL) &&
939                                     (vp->da->attr <= PW_TLS_CLIENT_CERT_SUBJECT_ALT_NAME_UPN)) {
940                                         /*
941                                          *      Certs already exist.  Don't re-add them.
942                                          */
943                                         if (!handler->certs) {
944                                                 rdebug_pair(L_DBG_LVL_2, request, vp, "request:");
945                                                 fr_pair_add(&request->packet->vps, fr_pair_copy(request->packet, vp));
946                                         }
947                                 } else {
948                                         rdebug_pair(L_DBG_LVL_2, request, vp, "reply:");
949                                         fr_pair_add(&request->reply->vps, fr_pair_copy(request->reply, vp));
950                                 }
951                         }
952                         REXDENT();
953                 }
954         }
955
956  done:
957         SSL_set_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST, NULL);
958
959         return status;
960 }
961
962
963 /*
964  *      compose the TLS reply packet in the EAP reply typedata
965  */
966 int eaptls_compose(EAP_DS *eap_ds, EAPTLS_PACKET *reply)
967 {
968         uint8_t *ptr;
969
970         /*
971          *      Don't set eap_ds->request->type.num, as the main EAP
972          *      handler will do that for us.  This allows the TLS
973          *      module to be called from TTLS & PEAP.
974          */
975
976         /*
977          *      When the EAP server receives an EAP-Response with the
978          *      M bit set, it MUST respond with an EAP-Request with
979          *      EAP-Type=EAP-TLS and no data. This serves as a
980          *      fragment ACK. The EAP peer MUST wait until it receives
981          *      the EAP-Request before sending another fragment.
982          *
983          *      In order to prevent errors in the processing of
984          *      fragments, the EAP server MUST use increment the
985          *      Identifier value for each fragment ACK contained
986          *      within an EAP-Request, and the peer MUST include this
987          *      Identifier value in the subsequent fragment contained
988          *      within an EAP- Reponse.
989          */
990         eap_ds->request->type.data = talloc_array(eap_ds->request, uint8_t,
991                                                   reply->length - TLS_HEADER_LEN + 1);
992         if (!eap_ds->request->type.data) return 0;
993
994         /* EAPTLS Header length is excluded while computing EAP typelen */
995         eap_ds->request->type.length = reply->length - TLS_HEADER_LEN;
996
997         ptr = eap_ds->request->type.data;
998         *ptr++ = (uint8_t)(reply->flags & 0xFF);
999
1000         if (reply->dlen) memcpy(ptr, reply->data, reply->dlen);
1001
1002         switch (reply->code) {
1003         case FR_TLS_ACK:
1004         case FR_TLS_START:
1005         case FR_TLS_REQUEST:
1006                 eap_ds->request->code = PW_EAP_REQUEST;
1007                 break;
1008
1009         case FR_TLS_SUCCESS:
1010                 eap_ds->request->code = PW_EAP_SUCCESS;
1011                 break;
1012
1013         case FR_TLS_FAIL:
1014                 eap_ds->request->code = PW_EAP_FAILURE;
1015                 break;
1016
1017         default:
1018                 /* Should never enter here */
1019                 rad_assert(0);
1020                 break;
1021         }
1022
1023         return 1;
1024 }
1025
1026 /*
1027  *      Parse TLS configuration
1028  *
1029  *      If the option given by 'attr' is set, we find the config section
1030  *      of that name and use that for the TLS configuration. If not, we
1031  *      fall back to compatibility mode and read the TLS options from
1032  *      the 'tls' section.
1033  */
1034 fr_tls_server_conf_t *eaptls_conf_parse(CONF_SECTION *cs, char const *attr)
1035 {
1036         char const              *tls_conf_name;
1037         CONF_PAIR               *cp;
1038         CONF_SECTION            *parent;
1039         CONF_SECTION            *tls_cs;
1040         fr_tls_server_conf_t    *tls_conf;
1041
1042         if (!cs)
1043                 return NULL;
1044
1045         rad_assert(attr != NULL);
1046
1047         parent = cf_item_parent(cf_section_to_item(cs));
1048
1049         cp = cf_pair_find(cs, attr);
1050         if (cp) {
1051                 tls_conf_name = cf_pair_value(cp);
1052
1053                 tls_cs = cf_section_sub_find_name2(parent, TLS_CONFIG_SECTION, tls_conf_name);
1054
1055                 if (!tls_cs) {
1056                         ERROR("Cannot find tls config \"%s\"", tls_conf_name);
1057                         return NULL;
1058                 }
1059         } else {
1060                 /*
1061                  *      If we can't find the section given by the 'attr', we
1062                  *      fall-back to looking for the "tls" section, as in
1063                  *      previous versions.
1064                  *
1065                  *      We don't fall back if the 'attr' is specified, but we can't
1066                  *      find the section - that is just a config error.
1067                  */
1068                 INFO("TLS section \"%s\" missing, trying to use legacy configuration", attr);
1069                 tls_cs = cf_section_sub_find(parent, "tls");
1070         }
1071
1072         if (!tls_cs)
1073                 return NULL;
1074
1075         tls_conf = tls_server_conf_parse(tls_cs);
1076
1077         if (!tls_conf)
1078                 return NULL;
1079
1080         /*
1081          *      The EAP RFC's say 1020, but we're less picky.
1082          */
1083         if (tls_conf->fragment_size < 100) {
1084                 ERROR("Configured fragment size is too small, must be >= 100");
1085                 return NULL;
1086         }
1087
1088         /*
1089          *      The maximum size for a RADIUS packet is 4096,
1090          *      minus the header (20), Message-Authenticator (18),
1091          *      and State (18), etc. results in about 4000 bytes of data
1092          *      that can be devoted *solely* to EAP.
1093          */
1094         if (tls_conf->fragment_size > 4000) {
1095                 ERROR("Configured fragment size is too large, must be <= 4000");
1096                 return NULL;
1097         }
1098
1099         /*
1100          *      Account for the EAP header (4), and the EAP-TLS header
1101          *      (6), as per Section 4.2 of RFC 2716.  What's left is
1102          *      the maximum amount of data we read from a TLS buffer.
1103          */
1104         tls_conf->fragment_size -= 10;
1105
1106         return tls_conf;
1107 }
1108