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