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