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