]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - contrib/wpa/src/eap_peer/eap_tls_common.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / contrib / wpa / 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         if (!length_included &&
505             eap_type == EAP_TYPE_PEAP && peap_version == 0 &&
506             !tls_connection_established(data->eap->ssl_ctx, data->conn)) {
507                 /*
508                  * Windows Server 2008 NPS really wants to have the TLS Message
509                  * length included in phase 0 even for unfragmented frames or
510                  * it will get very confused with Compound MAC calculation and
511                  * Outer TLVs.
512                  */
513                 length_included = 1;
514         }
515
516         *out_data = eap_msg_alloc(EAP_VENDOR_IETF, eap_type,
517                                   1 + length_included * 4 + len,
518                                   EAP_CODE_RESPONSE, id);
519         if (*out_data == NULL)
520                 return -1;
521
522         flags = wpabuf_put(*out_data, 1);
523         *flags = peap_version;
524         if (more_fragments)
525                 *flags |= EAP_TLS_FLAGS_MORE_FRAGMENTS;
526         if (length_included) {
527                 *flags |= EAP_TLS_FLAGS_LENGTH_INCLUDED;
528                 wpabuf_put_be32(*out_data, data->tls_out_len);
529         }
530
531         wpabuf_put_data(*out_data, &data->tls_out[data->tls_out_pos], len);
532         data->tls_out_pos += len;
533
534         if (!more_fragments)
535                 eap_peer_tls_reset_output(data);
536
537         return ret;
538 }
539
540
541 /**
542  * eap_peer_tls_process_helper - Process TLS handshake message
543  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
544  * @data: Data for TLS processing
545  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
546  * @peap_version: Version number for EAP-PEAP/TTLS
547  * @id: EAP identifier for the response
548  * @in_data: Message received from the server
549  * @in_len: Length of in_data
550  * @out_data: Buffer for returning a pointer to the response message
551  * Returns: 0 on success, 1 if more input data is needed, 2 if application data
552  * is available, or -1 on failure
553  *
554  * This function can be used to process TLS handshake messages. It reassembles
555  * the received fragments and uses a TLS library to process the messages. The
556  * response data from the TLS library is fragmented to suitable output messages
557  * that the caller can send out.
558  *
559  * out_data is used to return the response message if the return value of this
560  * function is 0, 2, or -1. In case of failure, the message is likely a TLS
561  * alarm message. The caller is responsible for freeing the allocated buffer if
562  * *out_data is not %NULL.
563  *
564  * This function is called for each received TLS message during the TLS
565  * handshake after eap_peer_tls_process_init() call and possible processing of
566  * TLS Flags field. Once the handshake has been completed, i.e., when
567  * tls_connection_established() returns 1, EAP method specific decrypting of
568  * the tunneled data is used.
569  */
570 int eap_peer_tls_process_helper(struct eap_sm *sm, struct eap_ssl_data *data,
571                                 EapType eap_type, int peap_version,
572                                 u8 id, const u8 *in_data, size_t in_len,
573                                 struct wpabuf **out_data)
574 {
575         int ret = 0;
576
577         *out_data = NULL;
578
579         if (data->tls_out_len > 0 && in_len > 0) {
580                 wpa_printf(MSG_DEBUG, "SSL: Received non-ACK when output "
581                            "fragments are waiting to be sent out");
582                 return -1;
583         }
584
585         if (data->tls_out_len == 0) {
586                 /*
587                  * No more data to send out - expect to receive more data from
588                  * the AS.
589                  */
590                 int res = eap_tls_process_input(sm, data, in_data, in_len,
591                                                 out_data);
592                 if (res) {
593                         /*
594                          * Input processing failed (res = -1) or more data is
595                          * needed (res = 1).
596                          */
597                         return res;
598                 }
599
600                 /*
601                  * The incoming message has been reassembled and processed. The
602                  * response was allocated into data->tls_out buffer.
603                  */
604         }
605
606         if (data->tls_out == NULL) {
607                 /*
608                  * No outgoing fragments remaining from the previous message
609                  * and no new message generated. This indicates an error in TLS
610                  * processing.
611                  */
612                 eap_peer_tls_reset_output(data);
613                 return -1;
614         }
615
616         if (tls_connection_get_failed(sm->ssl_ctx, data->conn)) {
617                 /* TLS processing has failed - return error */
618                 wpa_printf(MSG_DEBUG, "SSL: Failed - tls_out available to "
619                            "report error");
620                 ret = -1;
621                 /* TODO: clean pin if engine used? */
622         }
623
624         if (data->tls_out_len == 0) {
625                 /*
626                  * TLS negotiation should now be complete since all other cases
627                  * needing more data should have been caught above based on
628                  * the TLS Message Length field.
629                  */
630                 wpa_printf(MSG_DEBUG, "SSL: No data to be sent out");
631                 os_free(data->tls_out);
632                 data->tls_out = NULL;
633                 return 1;
634         }
635
636         /* Send the pending message (in fragments, if needed). */
637         return eap_tls_process_output(data, eap_type, peap_version, id, ret,
638                                       out_data);
639 }
640
641
642 /**
643  * eap_peer_tls_build_ack - Build a TLS ACK frame
644  * @id: EAP identifier for the response
645  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
646  * @peap_version: Version number for EAP-PEAP/TTLS
647  * Returns: Pointer to the allocated ACK frame or %NULL on failure
648  */
649 struct wpabuf * eap_peer_tls_build_ack(u8 id, EapType eap_type,
650                                        int peap_version)
651 {
652         struct wpabuf *resp;
653
654         resp = eap_msg_alloc(EAP_VENDOR_IETF, eap_type, 1, EAP_CODE_RESPONSE,
655                              id);
656         if (resp == NULL)
657                 return NULL;
658         wpa_printf(MSG_DEBUG, "SSL: Building ACK (type=%d id=%d ver=%d)",
659                    (int) eap_type, id, peap_version);
660         wpabuf_put_u8(resp, peap_version); /* Flags */
661         return resp;
662 }
663
664
665 /**
666  * eap_peer_tls_reauth_init - Re-initialize shared TLS for session resumption
667  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
668  * @data: Data for TLS processing
669  * Returns: 0 on success, -1 on failure
670  */
671 int eap_peer_tls_reauth_init(struct eap_sm *sm, struct eap_ssl_data *data)
672 {
673         eap_peer_tls_reset_input(data);
674         eap_peer_tls_reset_output(data);
675         return tls_connection_shutdown(sm->ssl_ctx, data->conn);
676 }
677
678
679 /**
680  * eap_peer_tls_status - Get TLS status
681  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
682  * @data: Data for TLS processing
683  * @buf: Buffer for status information
684  * @buflen: Maximum buffer length
685  * @verbose: Whether to include verbose status information
686  * Returns: Number of bytes written to buf.
687  */
688 int eap_peer_tls_status(struct eap_sm *sm, struct eap_ssl_data *data,
689                         char *buf, size_t buflen, int verbose)
690 {
691         char name[128];
692         int len = 0, ret;
693
694         if (tls_get_cipher(sm->ssl_ctx, data->conn, name, sizeof(name)) == 0) {
695                 ret = os_snprintf(buf + len, buflen - len,
696                                   "EAP TLS cipher=%s\n", name);
697                 if (ret < 0 || (size_t) ret >= buflen - len)
698                         return len;
699                 len += ret;
700         }
701
702         return len;
703 }
704
705
706 /**
707  * eap_peer_tls_process_init - Initial validation/processing of EAP requests
708  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
709  * @data: Data for TLS processing
710  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
711  * @ret: Return values from EAP request validation and processing
712  * @reqData: EAP request to be processed (eapReqData)
713  * @len: Buffer for returning length of the remaining payload
714  * @flags: Buffer for returning TLS flags
715  * Returns: Pointer to payload after TLS flags and length or %NULL on failure
716  *
717  * This function validates the EAP header and processes the optional TLS
718  * Message Length field. If this is the first fragment of a TLS message, the
719  * TLS reassembly code is initialized to receive the indicated number of bytes.
720  *
721  * EAP-TLS, EAP-PEAP, EAP-TTLS, and EAP-FAST methods are expected to use this
722  * function as the first step in processing received messages. They will need
723  * to process the flags (apart from Message Length Included) that are returned
724  * through the flags pointer and the message payload that will be returned (and
725  * the length is returned through the len pointer). Return values (ret) are set
726  * for continuation of EAP method processing. The caller is responsible for
727  * setting these to indicate completion (either success or failure) based on
728  * the authentication result.
729  */
730 const u8 * eap_peer_tls_process_init(struct eap_sm *sm,
731                                      struct eap_ssl_data *data,
732                                      EapType eap_type,
733                                      struct eap_method_ret *ret,
734                                      const struct wpabuf *reqData,
735                                      size_t *len, u8 *flags)
736 {
737         const u8 *pos;
738         size_t left;
739         unsigned int tls_msg_len;
740
741         if (tls_get_errors(sm->ssl_ctx)) {
742                 wpa_printf(MSG_INFO, "SSL: TLS errors detected");
743                 ret->ignore = TRUE;
744                 return NULL;
745         }
746
747         pos = eap_hdr_validate(EAP_VENDOR_IETF, eap_type, reqData, &left);
748         if (pos == NULL) {
749                 ret->ignore = TRUE;
750                 return NULL;
751         }
752         if (left == 0) {
753                 wpa_printf(MSG_DEBUG, "SSL: Invalid TLS message: no Flags "
754                            "octet included");
755                 if (!sm->workaround) {
756                         ret->ignore = TRUE;
757                         return NULL;
758                 }
759
760                 wpa_printf(MSG_DEBUG, "SSL: Workaround - assume no Flags "
761                            "indicates ACK frame");
762                 *flags = 0;
763         } else {
764                 *flags = *pos++;
765                 left--;
766         }
767         wpa_printf(MSG_DEBUG, "SSL: Received packet(len=%lu) - "
768                    "Flags 0x%02x", (unsigned long) wpabuf_len(reqData),
769                    *flags);
770         if (*flags & EAP_TLS_FLAGS_LENGTH_INCLUDED) {
771                 if (left < 4) {
772                         wpa_printf(MSG_INFO, "SSL: Short frame with TLS "
773                                    "length");
774                         ret->ignore = TRUE;
775                         return NULL;
776                 }
777                 tls_msg_len = WPA_GET_BE32(pos);
778                 wpa_printf(MSG_DEBUG, "SSL: TLS Message Length: %d",
779                            tls_msg_len);
780                 if (data->tls_in_left == 0) {
781                         data->tls_in_total = tls_msg_len;
782                         data->tls_in_left = tls_msg_len;
783                         os_free(data->tls_in);
784                         data->tls_in = NULL;
785                         data->tls_in_len = 0;
786                 }
787                 pos += 4;
788                 left -= 4;
789         }
790
791         ret->ignore = FALSE;
792         ret->methodState = METHOD_MAY_CONT;
793         ret->decision = DECISION_FAIL;
794         ret->allowNotifications = TRUE;
795
796         *len = left;
797         return pos;
798 }
799
800
801 /**
802  * eap_peer_tls_reset_input - Reset input buffers
803  * @data: Data for TLS processing
804  *
805  * This function frees any allocated memory for input buffers and resets input
806  * state.
807  */
808 void eap_peer_tls_reset_input(struct eap_ssl_data *data)
809 {
810         data->tls_in_left = data->tls_in_total = data->tls_in_len = 0;
811         os_free(data->tls_in);
812         data->tls_in = NULL;
813 }
814
815
816 /**
817  * eap_peer_tls_reset_output - Reset output buffers
818  * @data: Data for TLS processing
819  *
820  * This function frees any allocated memory for output buffers and resets
821  * output state.
822  */
823 void eap_peer_tls_reset_output(struct eap_ssl_data *data)
824 {
825         data->tls_out_len = 0;
826         data->tls_out_pos = 0;
827         os_free(data->tls_out);
828         data->tls_out = NULL;
829 }
830
831
832 /**
833  * eap_peer_tls_decrypt - Decrypt received phase 2 TLS message
834  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
835  * @data: Data for TLS processing
836  * @in_data: Message received from the server
837  * @in_decrypted: Buffer for returning a pointer to the decrypted message
838  * Returns: 0 on success, 1 if more input data is needed, or -1 on failure
839  */
840 int eap_peer_tls_decrypt(struct eap_sm *sm, struct eap_ssl_data *data,
841                          const struct wpabuf *in_data,
842                          struct wpabuf **in_decrypted)
843 {
844         int res;
845         const u8 *msg;
846         size_t msg_len, buf_len;
847         int need_more_input;
848
849         msg = eap_peer_tls_data_reassemble(data, wpabuf_head(in_data),
850                                            wpabuf_len(in_data), &msg_len,
851                                            &need_more_input);
852         if (msg == NULL)
853                 return need_more_input ? 1 : -1;
854
855         buf_len = wpabuf_len(in_data);
856         if (data->tls_in_total > buf_len)
857                 buf_len = data->tls_in_total;
858         /*
859          * Even though we try to disable TLS compression, it is possible that
860          * this cannot be done with all TLS libraries. Add extra buffer space
861          * to handle the possibility of the decrypted data being longer than
862          * input data.
863          */
864         buf_len += 500;
865         buf_len *= 3;
866         *in_decrypted = wpabuf_alloc(buf_len ? buf_len : 1);
867         if (*in_decrypted == NULL) {
868                 eap_peer_tls_reset_input(data);
869                 wpa_printf(MSG_WARNING, "SSL: Failed to allocate memory for "
870                            "decryption");
871                 return -1;
872         }
873
874         res = tls_connection_decrypt(sm->ssl_ctx, data->conn, msg, msg_len,
875                                      wpabuf_mhead(*in_decrypted), buf_len);
876         eap_peer_tls_reset_input(data);
877         if (res < 0) {
878                 wpa_printf(MSG_INFO, "SSL: Failed to decrypt Phase 2 data");
879                 return -1;
880         }
881         wpabuf_put(*in_decrypted, res);
882         return 0;
883 }
884
885
886 /**
887  * eap_peer_tls_encrypt - Encrypt phase 2 TLS message
888  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
889  * @data: Data for TLS processing
890  * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
891  * @peap_version: Version number for EAP-PEAP/TTLS
892  * @id: EAP identifier for the response
893  * @in_data: Plaintext phase 2 data to encrypt or %NULL to continue fragments
894  * @out_data: Buffer for returning a pointer to the encrypted response message
895  * Returns: 0 on success, -1 on failure
896  */
897 int eap_peer_tls_encrypt(struct eap_sm *sm, struct eap_ssl_data *data,
898                          EapType eap_type, int peap_version, u8 id,
899                          const struct wpabuf *in_data,
900                          struct wpabuf **out_data)
901 {
902         int res;
903         size_t len;
904
905         if (in_data) {
906                 eap_peer_tls_reset_output(data);
907                 len = wpabuf_len(in_data) + 300;
908                 data->tls_out = os_malloc(len);
909                 if (data->tls_out == NULL)
910                         return -1;
911
912                 res = tls_connection_encrypt(sm->ssl_ctx, data->conn,
913                                              wpabuf_head(in_data),
914                                              wpabuf_len(in_data),
915                                              data->tls_out, len);
916                 if (res < 0) {
917                         wpa_printf(MSG_INFO, "SSL: Failed to encrypt Phase 2 "
918                                    "data (in_len=%lu)",
919                                    (unsigned long) wpabuf_len(in_data));
920                         eap_peer_tls_reset_output(data);
921                         return -1;
922                 }
923
924                 data->tls_out_len = res;
925         }
926
927         return eap_tls_process_output(data, eap_type, peap_version, id, 0,
928                                       out_data);
929 }
930
931
932 /**
933  * eap_peer_select_phase2_methods - Select phase 2 EAP method
934  * @config: Pointer to the network configuration
935  * @prefix: 'phase2' configuration prefix, e.g., "auth="
936  * @types: Buffer for returning allocated list of allowed EAP methods
937  * @num_types: Buffer for returning number of allocated EAP methods
938  * Returns: 0 on success, -1 on failure
939  *
940  * This function is used to parse EAP method list and select allowed methods
941  * for Phase2 authentication.
942  */
943 int eap_peer_select_phase2_methods(struct eap_peer_config *config,
944                                    const char *prefix,
945                                    struct eap_method_type **types,
946                                    size_t *num_types)
947 {
948         char *start, *pos, *buf;
949         struct eap_method_type *methods = NULL, *_methods;
950         u8 method;
951         size_t num_methods = 0, prefix_len;
952
953         if (config == NULL || config->phase2 == NULL)
954                 goto get_defaults;
955
956         start = buf = os_strdup(config->phase2);
957         if (buf == NULL)
958                 return -1;
959
960         prefix_len = os_strlen(prefix);
961
962         while (start && *start != '\0') {
963                 int vendor;
964                 pos = os_strstr(start, prefix);
965                 if (pos == NULL)
966                         break;
967                 if (start != pos && *(pos - 1) != ' ') {
968                         start = pos + prefix_len;
969                         continue;
970                 }
971
972                 start = pos + prefix_len;
973                 pos = os_strchr(start, ' ');
974                 if (pos)
975                         *pos++ = '\0';
976                 method = eap_get_phase2_type(start, &vendor);
977                 if (vendor == EAP_VENDOR_IETF && method == EAP_TYPE_NONE) {
978                         wpa_printf(MSG_ERROR, "TLS: Unsupported Phase2 EAP "
979                                    "method '%s'", start);
980                 } else {
981                         num_methods++;
982                         _methods = os_realloc(methods,
983                                               num_methods * sizeof(*methods));
984                         if (_methods == NULL) {
985                                 os_free(methods);
986                                 os_free(buf);
987                                 return -1;
988                         }
989                         methods = _methods;
990                         methods[num_methods - 1].vendor = vendor;
991                         methods[num_methods - 1].method = method;
992                 }
993
994                 start = pos;
995         }
996
997         os_free(buf);
998
999 get_defaults:
1000         if (methods == NULL)
1001                 methods = eap_get_phase2_types(config, &num_methods);
1002
1003         if (methods == NULL) {
1004                 wpa_printf(MSG_ERROR, "TLS: No Phase2 EAP methods available");
1005                 return -1;
1006         }
1007         wpa_hexdump(MSG_DEBUG, "TLS: Phase2 EAP types",
1008                     (u8 *) methods,
1009                     num_methods * sizeof(struct eap_method_type));
1010
1011         *types = methods;
1012         *num_types = num_methods;
1013
1014         return 0;
1015 }
1016
1017
1018 /**
1019  * eap_peer_tls_phase2_nak - Generate EAP-Nak for Phase 2
1020  * @types: Buffer for returning allocated list of allowed EAP methods
1021  * @num_types: Buffer for returning number of allocated EAP methods
1022  * @hdr: EAP-Request header (and the following EAP type octet)
1023  * @resp: Buffer for returning the EAP-Nak message
1024  * Returns: 0 on success, -1 on failure
1025  */
1026 int eap_peer_tls_phase2_nak(struct eap_method_type *types, size_t num_types,
1027                             struct eap_hdr *hdr, struct wpabuf **resp)
1028 {
1029         u8 *pos = (u8 *) (hdr + 1);
1030         size_t i;
1031
1032         /* TODO: add support for expanded Nak */
1033         wpa_printf(MSG_DEBUG, "TLS: Phase 2 Request: Nak type=%d", *pos);
1034         wpa_hexdump(MSG_DEBUG, "TLS: Allowed Phase2 EAP types",
1035                     (u8 *) types, num_types * sizeof(struct eap_method_type));
1036         *resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_NAK, num_types,
1037                               EAP_CODE_RESPONSE, hdr->identifier);
1038         if (*resp == NULL)
1039                 return -1;
1040
1041         for (i = 0; i < num_types; i++) {
1042                 if (types[i].vendor == EAP_VENDOR_IETF &&
1043                     types[i].method < 256)
1044                         wpabuf_put_u8(*resp, types[i].method);
1045         }
1046
1047         eap_update_len(*resp);
1048
1049         return 0;
1050 }