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