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