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