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