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