Re-initialize hostapd/wpa_supplicant git repository based on 0.6.3 release
[wpasupplicant] / src / eap_peer / eap_tls_common.c
1 /*
2  * EAP peer: EAP-TLS/PEAP/TTLS/FAST common functions
3  * Copyright (c) 2004-2008, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "includes.h"
16
17 #include "common.h"
18 #include "eap_i.h"
19 #include "eap_tls_common.h"
20 #include "eap_config.h"
21 #include "sha1.h"
22 #include "tls.h"
23
24
25 static int eap_tls_check_blob(struct eap_sm *sm, const char **name,
26                               const u8 **data, size_t *data_len)
27 {
28         const struct wpa_config_blob *blob;
29
30         if (*name == NULL || os_strncmp(*name, "blob://", 7) != 0)
31                 return 0;
32
33         blob = eap_get_config_blob(sm, *name + 7);
34         if (blob == NULL) {
35                 wpa_printf(MSG_ERROR, "%s: Named configuration blob '%s' not "
36                            "found", __func__, *name + 7);
37                 return -1;
38         }
39
40         *name = NULL;
41         *data = blob->data;
42         *data_len = blob->len;
43
44         return 0;
45 }
46
47
48 static void eap_tls_params_from_conf1(struct tls_connection_params *params,
49                                       struct eap_peer_config *config)
50 {
51         params->ca_cert = (char *) config->ca_cert;
52         params->ca_path = (char *) config->ca_path;
53         params->client_cert = (char *) config->client_cert;
54         params->private_key = (char *) config->private_key;
55         params->private_key_passwd = (char *) config->private_key_passwd;
56         params->dh_file = (char *) config->dh_file;
57         params->subject_match = (char *) config->subject_match;
58         params->altsubject_match = (char *) config->altsubject_match;
59         params->engine_id = config->engine_id;
60         params->pin = config->pin;
61         params->key_id = config->key_id;
62 }
63
64
65 static void eap_tls_params_from_conf2(struct tls_connection_params *params,
66                                       struct eap_peer_config *config)
67 {
68         params->ca_cert = (char *) config->ca_cert2;
69         params->ca_path = (char *) config->ca_path2;
70         params->client_cert = (char *) config->client_cert2;
71         params->private_key = (char *) config->private_key2;
72         params->private_key_passwd = (char *) config->private_key2_passwd;
73         params->dh_file = (char *) config->dh_file2;
74         params->subject_match = (char *) config->subject_match2;
75         params->altsubject_match = (char *) config->altsubject_match2;
76 }
77
78
79 static int eap_tls_params_from_conf(struct eap_sm *sm,
80                                     struct eap_ssl_data *data,
81                                     struct tls_connection_params *params,
82                                     struct eap_peer_config *config, int phase2)
83 {
84         os_memset(params, 0, sizeof(*params));
85         params->engine = config->engine;
86         if (phase2)
87                 eap_tls_params_from_conf2(params, config);
88         else
89                 eap_tls_params_from_conf1(params, config);
90         params->tls_ia = data->tls_ia;
91
92         /*
93          * Use blob data, if available. Otherwise, leave reference to external
94          * file as-is.
95          */
96         if (eap_tls_check_blob(sm, &params->ca_cert, &params->ca_cert_blob,
97                                &params->ca_cert_blob_len) ||
98             eap_tls_check_blob(sm, &params->client_cert,
99                                &params->client_cert_blob,
100                                &params->client_cert_blob_len) ||
101             eap_tls_check_blob(sm, &params->private_key,
102                                &params->private_key_blob,
103                                &params->private_key_blob_len) ||
104             eap_tls_check_blob(sm, &params->dh_file, &params->dh_blob,
105                                &params->dh_blob_len)) {
106                 wpa_printf(MSG_INFO, "SSL: Failed to get configuration blobs");
107                 return -1;
108         }
109
110         return 0;
111 }
112
113
114 static int eap_tls_init_connection(struct eap_sm *sm,
115                                    struct eap_ssl_data *data,
116                                    struct eap_peer_config *config,
117                                    struct tls_connection_params *params)
118 {
119         int res;
120
121         data->conn = tls_connection_init(sm->ssl_ctx);
122         if (data->conn == NULL) {
123                 wpa_printf(MSG_INFO, "SSL: Failed to initialize new TLS "
124                            "connection");
125                 return -1;
126         }
127
128         res = tls_connection_set_params(sm->ssl_ctx, data->conn, params);
129         if (res == TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED) {
130                 /*
131                  * At this point with the pkcs11 engine the PIN might be wrong.
132                  * We reset the PIN in the configuration to be sure to not use
133                  * it again and the calling function must request a new one.
134                  */
135                 os_free(config->pin);
136                 config->pin = NULL;
137         } else if (res == TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED) {
138                 wpa_printf(MSG_INFO, "TLS: Failed to load private key");
139                 /*
140                  * We do not know exactly but maybe the PIN was wrong,
141                  * so ask for a new one.
142                  */
143                 os_free(config->pin);
144                 config->pin = NULL;
145                 eap_sm_request_pin(sm);
146                 sm->ignore = TRUE;
147                 return -1;
148         } else if (res) {
149                 wpa_printf(MSG_INFO, "TLS: Failed to set TLS connection "
150                            "parameters");
151                 return -1;
152         }
153
154         return 0;
155 }
156
157
158 /**
159  * eap_peer_tls_ssl_init - Initialize shared TLS functionality
160  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
161  * @data: Data for TLS processing
162  * @config: Pointer to the network configuration
163  * Returns: 0 on success, -1 on failure
164  *
165  * This function is used to initialize shared TLS functionality for EAP-TLS,
166  * EAP-PEAP, EAP-TTLS, and EAP-FAST.
167  */
168 int eap_peer_tls_ssl_init(struct eap_sm *sm, struct eap_ssl_data *data,
169                           struct eap_peer_config *config)
170 {
171         struct tls_connection_params params;
172
173         if (config == NULL)
174                 return -1;
175
176         data->eap = sm;
177         data->phase2 = sm->init_phase2;
178         if (eap_tls_params_from_conf(sm, data, &params, config, data->phase2) <
179             0)
180                 return -1;
181
182         if (eap_tls_init_connection(sm, data, config, &params) < 0)
183                 return -1;
184
185         data->tls_out_limit = config->fragment_size;
186         if (data->phase2) {
187                 /* Limit the fragment size in the inner TLS authentication
188                  * since the outer authentication with EAP-PEAP does not yet
189                  * support fragmentation */
190                 if (data->tls_out_limit > 100)
191                         data->tls_out_limit -= 100;
192         }
193
194         if (config->phase1 &&
195             os_strstr(config->phase1, "include_tls_length=1")) {
196                 wpa_printf(MSG_DEBUG, "TLS: Include TLS Message Length in "
197                            "unfragmented packets");
198                 data->include_tls_length = 1;
199         }
200
201         return 0;
202 }
203
204
205 /**
206  * eap_peer_tls_ssl_deinit - Deinitialize shared TLS functionality
207  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
208  * @data: Data for TLS processing
209  *
210  * This function deinitializes shared TLS functionality that was initialized
211  * with eap_peer_tls_ssl_init().
212  */
213 void eap_peer_tls_ssl_deinit(struct eap_sm *sm, struct eap_ssl_data *data)
214 {
215         tls_connection_deinit(sm->ssl_ctx, data->conn);
216         eap_peer_tls_reset_input(data);
217         eap_peer_tls_reset_output(data);
218 }
219
220
221 /**
222  * eap_peer_tls_derive_key - Derive a key based on TLS session data
223  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
224  * @data: Data for TLS processing
225  * @label: Label string for deriving the keys, e.g., "client EAP encryption"
226  * @len: Length of the key material to generate (usually 64 for MSK)
227  * Returns: Pointer to allocated key on success or %NULL on failure
228  *
229  * This function uses TLS-PRF to generate pseudo-random data based on the TLS
230  * session data (client/server random and master key). Each key type may use a
231  * different label to bind the key usage into the generated material.
232  *
233  * The caller is responsible for freeing the returned buffer.
234  */
235 u8 * eap_peer_tls_derive_key(struct eap_sm *sm, struct eap_ssl_data *data,
236                              const char *label, size_t len)
237 {
238         struct tls_keys keys;
239         u8 *rnd = NULL, *out;
240
241         out = os_malloc(len);
242         if (out == NULL)
243                 return NULL;
244
245         /* First, try to use TLS library function for PRF, if available. */
246         if (tls_connection_prf(sm->ssl_ctx, data->conn, label, 0, out, len) ==
247             0)
248                 return out;
249
250         /*
251          * TLS library did not support key generation, so get the needed TLS
252          * session parameters and use an internal implementation of TLS PRF to
253          * derive the key.
254          */
255         if (tls_connection_get_keys(sm->ssl_ctx, data->conn, &keys))
256                 goto fail;
257
258         if (keys.client_random == NULL || keys.server_random == NULL ||
259             keys.master_key == NULL)
260                 goto fail;
261
262         rnd = os_malloc(keys.client_random_len + keys.server_random_len);
263         if (rnd == NULL)
264                 goto fail;
265         os_memcpy(rnd, keys.client_random, keys.client_random_len);
266         os_memcpy(rnd + keys.client_random_len, keys.server_random,
267                   keys.server_random_len);
268
269         if (tls_prf(keys.master_key, keys.master_key_len,
270                     label, rnd, keys.client_random_len +
271                     keys.server_random_len, out, len))
272                 goto fail;
273
274         os_free(rnd);
275         return out;
276
277 fail:
278         os_free(out);
279         os_free(rnd);
280         return NULL;
281 }
282
283
284 /**
285  * eap_peer_tls_reassemble_fragment - Reassemble a received fragment
286  * @data: Data for TLS processing
287  * @in_data: Next incoming TLS segment
288  * @in_len: Length of in_data
289  * Returns: 0 on success, 1 if more data is needed for the full message, or
290  * -1 on error
291  */
292 static int eap_peer_tls_reassemble_fragment(struct eap_ssl_data *data,
293                                             const u8 *in_data, size_t in_len)
294 {
295         u8 *buf;
296
297         if (data->tls_in_len + in_len == 0) {
298                 /* No message data received?! */
299                 wpa_printf(MSG_WARNING, "SSL: Invalid reassembly state: "
300                            "tls_in_left=%lu tls_in_len=%lu in_len=%lu",
301                            (unsigned long) data->tls_in_left,
302                            (unsigned long) data->tls_in_len,
303                            (unsigned long) in_len);
304                 eap_peer_tls_reset_input(data);
305                 return -1;
306         }
307
308         if (data->tls_in_len + in_len > 65536) {
309                 /*
310                  * Limit length to avoid rogue servers from causing large
311                  * memory allocations.
312                  */
313                 wpa_printf(MSG_INFO, "SSL: Too long TLS fragment (size over "
314                            "64 kB)");
315                 eap_peer_tls_reset_input(data);
316                 return -1;
317         }
318
319         if (in_len > data->tls_in_left) {
320                 /* Sender is doing something odd - reject message */
321                 wpa_printf(MSG_INFO, "SSL: more data than TLS message length "
322                            "indicated");
323                 eap_peer_tls_reset_input(data);
324                 return -1;
325         }
326
327         buf = os_realloc(data->tls_in, data->tls_in_len + in_len);
328         if (buf == NULL) {
329                 wpa_printf(MSG_INFO, "SSL: Could not allocate memory for TLS "
330                            "data");
331                 eap_peer_tls_reset_input(data);
332                 return -1;
333         }
334         os_memcpy(buf + data->tls_in_len, in_data, in_len);
335         data->tls_in = buf;
336         data->tls_in_len += in_len;
337         data->tls_in_left -= in_len;
338
339         if (data->tls_in_left > 0) {
340                 wpa_printf(MSG_DEBUG, "SSL: Need %lu bytes more input "
341                            "data", (unsigned long) data->tls_in_left);
342                 return 1;
343         }
344
345         return 0;
346 }
347
348
349 /**
350  * eap_peer_tls_data_reassemble - Reassemble TLS data
351  * @data: Data for TLS processing
352  * @in_data: Next incoming TLS segment
353  * @in_len: Length of in_data
354  * @out_len: Variable for returning length of the reassembled message
355  * @need_more_input: Variable for returning whether more input data is needed
356  * to reassemble this TLS packet
357  * Returns: Pointer to output data, %NULL on error or when more data is needed
358  * for the full message (in which case, *need_more_input is also set to 1).
359  *
360  * This function reassembles TLS fragments. Caller must not free the returned
361  * data buffer since an internal pointer to it is maintained.
362  */
363 const u8 * eap_peer_tls_data_reassemble(
364         struct eap_ssl_data *data, const u8 *in_data, size_t in_len,
365         size_t *out_len, int *need_more_input)
366 {
367         *need_more_input = 0;
368
369         if (data->tls_in_left > in_len || data->tls_in) {
370                 /* Message has fragments */
371                 int res = eap_peer_tls_reassemble_fragment(data, in_data,
372                                                            in_len);
373                 if (res) {
374                         if (res == 1)
375                                 *need_more_input = 1;
376                         return NULL;
377                 }
378
379                 /* Message is now fully reassembled. */
380         } else {
381                 /* No fragments in this message, so just make a copy of it. */
382                 data->tls_in_left = 0;
383                 data->tls_in = os_malloc(in_len ? in_len : 1);
384                 if (data->tls_in == NULL)
385                         return NULL;
386                 os_memcpy(data->tls_in, in_data, in_len);
387                 data->tls_in_len = in_len;
388         }
389
390         *out_len = data->tls_in_len;
391         return data->tls_in;
392 }
393
394
395 /**
396  * eap_tls_process_input - Process incoming TLS message
397  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
398  * @data: Data for TLS processing
399  * @in_data: Message received from the server
400  * @in_len: Length of in_data
401  * @out_data: Buffer for returning a pointer to application data (if available)
402  * Returns: 0 on success, 1 if more input data is needed, 2 if application data
403  * is available, -1 on failure
404  */
405 static int eap_tls_process_input(struct eap_sm *sm, struct eap_ssl_data *data,
406                                  const u8 *in_data, size_t in_len,
407                                  struct wpabuf **out_data)
408 {
409         const u8 *msg;
410         size_t msg_len;
411         int need_more_input;
412         u8 *appl_data;
413         size_t appl_data_len;
414
415         msg = eap_peer_tls_data_reassemble(data, in_data, in_len,
416                                            &msg_len, &need_more_input);
417         if (msg == NULL)
418                 return need_more_input ? 1 : -1;
419
420         /* Full TLS message reassembled - continue handshake processing */
421         if (data->tls_out) {
422                 /* This should not happen.. */
423                 wpa_printf(MSG_INFO, "SSL: eap_tls_process_input - pending "
424                            "tls_out data even though tls_out_len = 0");
425                 os_free(data->tls_out);
426                 WPA_ASSERT(data->tls_out == NULL);
427         }
428         appl_data = NULL;
429         data->tls_out = tls_connection_handshake(sm->ssl_ctx, data->conn,
430                                                  msg, msg_len,
431                                                  &data->tls_out_len,
432                                                  &appl_data, &appl_data_len);
433
434         eap_peer_tls_reset_input(data);
435
436         if (appl_data &&
437             tls_connection_established(sm->ssl_ctx, data->conn) &&
438             !tls_connection_get_failed(sm->ssl_ctx, data->conn)) {
439                 wpa_hexdump_key(MSG_MSGDUMP, "SSL: Application data",
440                                 appl_data, appl_data_len);
441                 *out_data = wpabuf_alloc_ext_data(appl_data, appl_data_len);
442                 if (*out_data == NULL) {
443                         os_free(appl_data);
444                         return -1;
445                 }
446                 return 2;
447         }
448
449         os_free(appl_data);
450
451         return 0;
452 }
453
454
455 /**
456  * eap_tls_process_output - Process outgoing TLS message
457  * @data: Data for TLS processing
458  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
459  * @peap_version: Version number for EAP-PEAP/TTLS
460  * @id: EAP identifier for the response
461  * @ret: Return value to use on success
462  * @out_data: Buffer for returning the allocated output buffer
463  * Returns: ret (0 or 1) on success, -1 on failure
464  */
465 static int eap_tls_process_output(struct eap_ssl_data *data, EapType eap_type,
466                                   int peap_version, u8 id, int ret,
467                                   struct wpabuf **out_data)
468 {
469         size_t len;
470         u8 *flags;
471         int more_fragments, length_included;
472         
473         len = data->tls_out_len - data->tls_out_pos;
474         wpa_printf(MSG_DEBUG, "SSL: %lu bytes left to be sent out (of total "
475                    "%lu bytes)",
476                    (unsigned long) len, (unsigned long) data->tls_out_len);
477
478         /*
479          * Limit outgoing message to the configured maximum size. Fragment
480          * message if needed.
481          */
482         if (len > data->tls_out_limit) {
483                 more_fragments = 1;
484                 len = data->tls_out_limit;
485                 wpa_printf(MSG_DEBUG, "SSL: sending %lu bytes, more fragments "
486                            "will follow", (unsigned long) len);
487         } else
488                 more_fragments = 0;
489
490         length_included = data->tls_out_pos == 0 &&
491                 (data->tls_out_len > data->tls_out_limit ||
492                  data->include_tls_length);
493
494         *out_data = eap_msg_alloc(EAP_VENDOR_IETF, eap_type,
495                                   1 + length_included * 4 + len,
496                                   EAP_CODE_RESPONSE, id);
497         if (*out_data == NULL)
498                 return -1;
499
500         flags = wpabuf_put(*out_data, 1);
501         *flags = peap_version;
502         if (more_fragments)
503                 *flags |= EAP_TLS_FLAGS_MORE_FRAGMENTS;
504         if (length_included) {
505                 *flags |= EAP_TLS_FLAGS_LENGTH_INCLUDED;
506                 wpabuf_put_be32(*out_data, data->tls_out_len);
507         }
508
509         wpabuf_put_data(*out_data, &data->tls_out[data->tls_out_pos], len);
510         data->tls_out_pos += len;
511
512         if (!more_fragments)
513                 eap_peer_tls_reset_output(data);
514
515         return ret;
516 }
517
518
519 /**
520  * eap_peer_tls_process_helper - Process TLS handshake message
521  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
522  * @data: Data for TLS processing
523  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
524  * @peap_version: Version number for EAP-PEAP/TTLS
525  * @id: EAP identifier for the response
526  * @in_data: Message received from the server
527  * @in_len: Length of in_data
528  * @out_data: Buffer for returning a pointer to the response message
529  * Returns: 0 on success, 1 if more input data is needed, 2 if application data
530  * is available, or -1 on failure
531  *
532  * This function can be used to process TLS handshake messages. It reassembles
533  * the received fragments and uses a TLS library to process the messages. The
534  * response data from the TLS library is fragmented to suitable output messages
535  * that the caller can send out.
536  *
537  * out_data is used to return the response message if the return value of this
538  * function is 0, 2, or -1. In case of failure, the message is likely a TLS
539  * alarm message. The caller is responsible for freeing the allocated buffer if
540  * *out_data is not %NULL.
541  *
542  * This function is called for each received TLS message during the TLS
543  * handshake after eap_peer_tls_process_init() call and possible processing of
544  * TLS Flags field. Once the handshake has been completed, i.e., when
545  * tls_connection_established() returns 1, EAP method specific decrypting of
546  * the tunneled data is used.
547  */
548 int eap_peer_tls_process_helper(struct eap_sm *sm, struct eap_ssl_data *data,
549                                 EapType eap_type, int peap_version,
550                                 u8 id, const u8 *in_data, size_t in_len,
551                                 struct wpabuf **out_data)
552 {
553         int ret = 0;
554
555         *out_data = NULL;
556
557         if (data->tls_out_len > 0 && in_len > 0) {
558                 wpa_printf(MSG_DEBUG, "SSL: Received non-ACK when output "
559                            "fragments are waiting to be sent out");
560                 return -1;
561         }
562
563         if (data->tls_out_len == 0) {
564                 /*
565                  * No more data to send out - expect to receive more data from
566                  * the AS.
567                  */
568                 int res = eap_tls_process_input(sm, data, in_data, in_len,
569                                                 out_data);
570                 if (res) {
571                         /*
572                          * Input processing failed (res = -1) or more data is
573                          * needed (res = 1).
574                          */
575                         return res;
576                 }
577
578                 /*
579                  * The incoming message has been reassembled and processed. The
580                  * response was allocated into data->tls_out buffer.
581                  */
582         }
583
584         if (data->tls_out == NULL) {
585                 /*
586                  * No outgoing fragments remaining from the previous message
587                  * and no new message generated. This indicates an error in TLS
588                  * processing.
589                  */
590                 eap_peer_tls_reset_output(data);
591                 return -1;
592         }
593
594         if (tls_connection_get_failed(sm->ssl_ctx, data->conn)) {
595                 /* TLS processing has failed - return error */
596                 wpa_printf(MSG_DEBUG, "SSL: Failed - tls_out available to "
597                            "report error");
598                 ret = -1;
599                 /* TODO: clean pin if engine used? */
600         }
601
602         if (data->tls_out_len == 0) {
603                 /*
604                  * TLS negotiation should now be complete since all other cases
605                  * needing more data should have been caught above based on
606                  * the TLS Message Length field.
607                  */
608                 wpa_printf(MSG_DEBUG, "SSL: No data to be sent out");
609                 os_free(data->tls_out);
610                 data->tls_out = NULL;
611                 return 1;
612         }
613
614         /* Send the pending message (in fragments, if needed). */
615         return eap_tls_process_output(data, eap_type, peap_version, id, ret,
616                                       out_data);
617 }
618
619
620 /**
621  * eap_peer_tls_build_ack - Build a TLS ACK frame
622  * @id: EAP identifier for the response
623  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
624  * @peap_version: Version number for EAP-PEAP/TTLS
625  * Returns: Pointer to the allocated ACK frame or %NULL on failure
626  */
627 struct wpabuf * eap_peer_tls_build_ack(u8 id, EapType eap_type,
628                                        int peap_version)
629 {
630         struct wpabuf *resp;
631
632         resp = eap_msg_alloc(EAP_VENDOR_IETF, eap_type, 1, EAP_CODE_RESPONSE,
633                              id);
634         if (resp == NULL)
635                 return NULL;
636         wpa_printf(MSG_DEBUG, "SSL: Building ACK (type=%d id=%d ver=%d)",
637                    (int) eap_type, id, peap_version);
638         wpabuf_put_u8(resp, peap_version); /* Flags */
639         return resp;
640 }
641
642
643 /**
644  * eap_peer_tls_reauth_init - Re-initialize shared TLS for session resumption
645  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
646  * @data: Data for TLS processing
647  * Returns: 0 on success, -1 on failure
648  */
649 int eap_peer_tls_reauth_init(struct eap_sm *sm, struct eap_ssl_data *data)
650 {
651         eap_peer_tls_reset_input(data);
652         eap_peer_tls_reset_output(data);
653         return tls_connection_shutdown(sm->ssl_ctx, data->conn);
654 }
655
656
657 /**
658  * eap_peer_tls_status - Get TLS status
659  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
660  * @data: Data for TLS processing
661  * @buf: Buffer for status information
662  * @buflen: Maximum buffer length
663  * @verbose: Whether to include verbose status information
664  * Returns: Number of bytes written to buf.
665  */
666 int eap_peer_tls_status(struct eap_sm *sm, struct eap_ssl_data *data,
667                         char *buf, size_t buflen, int verbose)
668 {
669         char name[128];
670         int len = 0, ret;
671
672         if (tls_get_cipher(sm->ssl_ctx, data->conn, name, sizeof(name)) == 0) {
673                 ret = os_snprintf(buf + len, buflen - len,
674                                   "EAP TLS cipher=%s\n", name);
675                 if (ret < 0 || (size_t) ret >= buflen - len)
676                         return len;
677                 len += ret;
678         }
679
680         return len;
681 }
682
683
684 /**
685  * eap_peer_tls_process_init - Initial validation/processing of EAP requests
686  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
687  * @data: Data for TLS processing
688  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
689  * @ret: Return values from EAP request validation and processing
690  * @reqData: EAP request to be processed (eapReqData)
691  * @len: Buffer for returning length of the remaining payload
692  * @flags: Buffer for returning TLS flags
693  * Returns: Pointer to payload after TLS flags and length or %NULL on failure
694  *
695  * This function validates the EAP header and processes the optional TLS
696  * Message Length field. If this is the first fragment of a TLS message, the
697  * TLS reassembly code is initialized to receive the indicated number of bytes.
698  *
699  * EAP-TLS, EAP-PEAP, EAP-TTLS, and EAP-FAST methods are expected to use this
700  * function as the first step in processing received messages. They will need
701  * to process the flags (apart from Message Length Included) that are returned
702  * through the flags pointer and the message payload that will be returned (and
703  * the length is returned through the len pointer). Return values (ret) are set
704  * for continuation of EAP method processing. The caller is responsible for
705  * setting these to indicate completion (either success or failure) based on
706  * the authentication result.
707  */
708 const u8 * eap_peer_tls_process_init(struct eap_sm *sm,
709                                      struct eap_ssl_data *data,
710                                      EapType eap_type,
711                                      struct eap_method_ret *ret,
712                                      const struct wpabuf *reqData,
713                                      size_t *len, u8 *flags)
714 {
715         const u8 *pos;
716         size_t left;
717         unsigned int tls_msg_len;
718
719         if (tls_get_errors(sm->ssl_ctx)) {
720                 wpa_printf(MSG_INFO, "SSL: TLS errors detected");
721                 ret->ignore = TRUE;
722                 return NULL;
723         }
724
725         pos = eap_hdr_validate(EAP_VENDOR_IETF, eap_type, reqData, &left);
726         if (pos == NULL) {
727                 ret->ignore = TRUE;
728                 return NULL;
729         }
730         *flags = *pos++;
731         left--;
732         wpa_printf(MSG_DEBUG, "SSL: Received packet(len=%lu) - "
733                    "Flags 0x%02x", (unsigned long) wpabuf_len(reqData),
734                    *flags);
735         if (*flags & EAP_TLS_FLAGS_LENGTH_INCLUDED) {
736                 if (left < 4) {
737                         wpa_printf(MSG_INFO, "SSL: Short frame with TLS "
738                                    "length");
739                         ret->ignore = TRUE;
740                         return NULL;
741                 }
742                 tls_msg_len = WPA_GET_BE32(pos);
743                 wpa_printf(MSG_DEBUG, "SSL: TLS Message Length: %d",
744                            tls_msg_len);
745                 if (data->tls_in_left == 0) {
746                         data->tls_in_total = tls_msg_len;
747                         data->tls_in_left = tls_msg_len;
748                         os_free(data->tls_in);
749                         data->tls_in = NULL;
750                         data->tls_in_len = 0;
751                 }
752                 pos += 4;
753                 left -= 4;
754         }
755
756         ret->ignore = FALSE;
757         ret->methodState = METHOD_MAY_CONT;
758         ret->decision = DECISION_FAIL;
759         ret->allowNotifications = TRUE;
760
761         *len = left;
762         return pos;
763 }
764
765
766 /**
767  * eap_peer_tls_reset_input - Reset input buffers
768  * @data: Data for TLS processing
769  *
770  * This function frees any allocated memory for input buffers and resets input
771  * state.
772  */
773 void eap_peer_tls_reset_input(struct eap_ssl_data *data)
774 {
775         data->tls_in_left = data->tls_in_total = data->tls_in_len = 0;
776         os_free(data->tls_in);
777         data->tls_in = NULL;
778 }
779
780
781 /**
782  * eap_peer_tls_reset_output - Reset output buffers
783  * @data: Data for TLS processing
784  *
785  * This function frees any allocated memory for output buffers and resets
786  * output state.
787  */
788 void eap_peer_tls_reset_output(struct eap_ssl_data *data)
789 {
790         data->tls_out_len = 0;
791         data->tls_out_pos = 0;
792         os_free(data->tls_out);
793         data->tls_out = NULL;
794 }
795
796
797 /**
798  * eap_peer_tls_decrypt - Decrypt received phase 2 TLS message
799  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
800  * @data: Data for TLS processing
801  * @in_data: Message received from the server
802  * @in_decrypted: Buffer for returning a pointer to the decrypted message
803  * Returns: 0 on success, 1 if more input data is needed, or -1 on failure
804  */
805 int eap_peer_tls_decrypt(struct eap_sm *sm, struct eap_ssl_data *data,
806                          const struct wpabuf *in_data,
807                          struct wpabuf **in_decrypted)
808 {
809         int res;
810         const u8 *msg;
811         size_t msg_len, buf_len;
812         int need_more_input;
813
814         msg = eap_peer_tls_data_reassemble(data, wpabuf_head(in_data),
815                                            wpabuf_len(in_data), &msg_len,
816                                            &need_more_input);
817         if (msg == NULL)
818                 return need_more_input ? 1 : -1;
819
820         buf_len = wpabuf_len(in_data);
821         if (data->tls_in_total > buf_len)
822                 buf_len = data->tls_in_total;
823         *in_decrypted = wpabuf_alloc(buf_len ? buf_len : 1);
824         if (*in_decrypted == NULL) {
825                 eap_peer_tls_reset_input(data);
826                 wpa_printf(MSG_WARNING, "SSL: Failed to allocate memory for "
827                            "decryption");
828                 return -1;
829         }
830
831         res = tls_connection_decrypt(sm->ssl_ctx, data->conn, msg, msg_len,
832                                      wpabuf_mhead(*in_decrypted), buf_len);
833         eap_peer_tls_reset_input(data);
834         if (res < 0) {
835                 wpa_printf(MSG_INFO, "SSL: Failed to decrypt Phase 2 data");
836                 return -1;
837         }
838         wpabuf_put(*in_decrypted, res);
839         return 0;
840 }
841
842
843 /**
844  * eap_peer_tls_encrypt - Encrypt phase 2 TLS message
845  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
846  * @data: Data for TLS processing
847  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
848  * @peap_version: Version number for EAP-PEAP/TTLS
849  * @id: EAP identifier for the response
850  * @in_data: Plaintext phase 2 data to encrypt or %NULL to continue fragments
851  * @out_data: Buffer for returning a pointer to the encrypted response message
852  * Returns: 0 on success, -1 on failure
853  */
854 int eap_peer_tls_encrypt(struct eap_sm *sm, struct eap_ssl_data *data,
855                          EapType eap_type, int peap_version, u8 id,
856                          const struct wpabuf *in_data,
857                          struct wpabuf **out_data)
858 {
859         int res;
860         size_t len;
861
862         if (in_data) {
863                 eap_peer_tls_reset_output(data);
864                 len = wpabuf_len(in_data) + 100;
865                 data->tls_out = os_malloc(len);
866                 if (data->tls_out == NULL)
867                         return -1;
868
869                 res = tls_connection_encrypt(sm->ssl_ctx, data->conn,
870                                              wpabuf_head(in_data),
871                                              wpabuf_len(in_data),
872                                              data->tls_out, len);
873                 if (res < 0) {
874                         wpa_printf(MSG_INFO, "SSL: Failed to encrypt Phase 2 "
875                                    "data (in_len=%lu)",
876                                    (unsigned long) wpabuf_len(in_data));
877                         eap_peer_tls_reset_output(data);
878                         return -1;
879                 }
880
881                 data->tls_out_len = res;
882         }
883
884         return eap_tls_process_output(data, eap_type, peap_version, id, 0,
885                                       out_data);
886 }
887
888
889 /**
890  * eap_peer_select_phase2_methods - Select phase 2 EAP method
891  * @config: Pointer to the network configuration
892  * @prefix: 'phase2' configuration prefix, e.g., "auth="
893  * @types: Buffer for returning allocated list of allowed EAP methods
894  * @num_types: Buffer for returning number of allocated EAP methods
895  * Returns: 0 on success, -1 on failure
896  *
897  * This function is used to parse EAP method list and select allowed methods
898  * for Phase2 authentication.
899  */
900 int eap_peer_select_phase2_methods(struct eap_peer_config *config,
901                                    const char *prefix,
902                                    struct eap_method_type **types,
903                                    size_t *num_types)
904 {
905         char *start, *pos, *buf;
906         struct eap_method_type *methods = NULL, *_methods;
907         u8 method;
908         size_t num_methods = 0, prefix_len;
909
910         if (config == NULL || config->phase2 == NULL)
911                 goto get_defaults;
912
913         start = buf = os_strdup(config->phase2);
914         if (buf == NULL)
915                 return -1;
916
917         prefix_len = os_strlen(prefix);
918
919         while (start && *start != '\0') {
920                 int vendor;
921                 pos = os_strstr(start, prefix);
922                 if (pos == NULL)
923                         break;
924                 if (start != pos && *(pos - 1) != ' ') {
925                         start = pos + prefix_len;
926                         continue;
927                 }
928
929                 start = pos + prefix_len;
930                 pos = os_strchr(start, ' ');
931                 if (pos)
932                         *pos++ = '\0';
933                 method = eap_get_phase2_type(start, &vendor);
934                 if (vendor == EAP_VENDOR_IETF && method == EAP_TYPE_NONE) {
935                         wpa_printf(MSG_ERROR, "TLS: Unsupported Phase2 EAP "
936                                    "method '%s'", start);
937                 } else {
938                         num_methods++;
939                         _methods = os_realloc(methods,
940                                               num_methods * sizeof(*methods));
941                         if (_methods == NULL) {
942                                 os_free(methods);
943                                 os_free(buf);
944                                 return -1;
945                         }
946                         methods = _methods;
947                         methods[num_methods - 1].vendor = vendor;
948                         methods[num_methods - 1].method = method;
949                 }
950
951                 start = pos;
952         }
953
954         os_free(buf);
955
956 get_defaults:
957         if (methods == NULL)
958                 methods = eap_get_phase2_types(config, &num_methods);
959
960         if (methods == NULL) {
961                 wpa_printf(MSG_ERROR, "TLS: No Phase2 EAP methods available");
962                 return -1;
963         }
964         wpa_hexdump(MSG_DEBUG, "TLS: Phase2 EAP types",
965                     (u8 *) methods,
966                     num_methods * sizeof(struct eap_method_type));
967
968         *types = methods;
969         *num_types = num_methods;
970
971         return 0;
972 }
973
974
975 /**
976  * eap_peer_tls_phase2_nak - Generate EAP-Nak for Phase 2
977  * @types: Buffer for returning allocated list of allowed EAP methods
978  * @num_types: Buffer for returning number of allocated EAP methods
979  * @hdr: EAP-Request header (and the following EAP type octet)
980  * @resp: Buffer for returning the EAP-Nak message
981  * Returns: 0 on success, -1 on failure
982  */
983 int eap_peer_tls_phase2_nak(struct eap_method_type *types, size_t num_types,
984                             struct eap_hdr *hdr, struct wpabuf **resp)
985 {
986         u8 *pos = (u8 *) (hdr + 1);
987         size_t i;
988
989         /* TODO: add support for expanded Nak */
990         wpa_printf(MSG_DEBUG, "TLS: Phase 2 Request: Nak type=%d", *pos);
991         wpa_hexdump(MSG_DEBUG, "TLS: Allowed Phase2 EAP types",
992                     (u8 *) types, num_types * sizeof(struct eap_method_type));
993         *resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_NAK, num_types,
994                               EAP_CODE_RESPONSE, hdr->identifier);
995         if (*resp == NULL)
996                 return -1;
997
998         for (i = 0; i < num_types; i++) {
999                 if (types[i].vendor == EAP_VENDOR_IETF &&
1000                     types[i].method < 256)
1001                         wpabuf_put_u8(*resp, types[i].method);
1002         }
1003
1004         eap_update_len(*resp);
1005
1006         return 0;
1007 }