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