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