Home | History | Annotate | Download | only in wpa_supplicant
      1 /*
      2  * wpa_supplicant: TLSv1 client (RFC 2246)
      3  * Copyright (c) 2006, 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 "base64.h"
     19 #include "md5.h"
     20 #include "sha1.h"
     21 #include "crypto.h"
     22 #include "tls.h"
     23 #include "tlsv1_common.h"
     24 #include "tlsv1_client.h"
     25 #include "x509v3.h"
     26 
     27 /* TODO:
     28  * Support for a message fragmented across several records (RFC 2246, 6.2.1)
     29  */
     30 
     31 struct tlsv1_client {
     32 	enum {
     33 		CLIENT_HELLO, SERVER_HELLO, SERVER_CERTIFICATE,
     34 		SERVER_KEY_EXCHANGE, SERVER_CERTIFICATE_REQUEST,
     35 		SERVER_HELLO_DONE, CLIENT_KEY_EXCHANGE, CHANGE_CIPHER_SPEC,
     36 		SERVER_CHANGE_CIPHER_SPEC, SERVER_FINISHED, ACK_FINISHED,
     37 		ESTABLISHED, FAILED
     38 	} state;
     39 
     40 	struct tlsv1_record_layer rl;
     41 
     42 	u8 session_id[TLS_SESSION_ID_MAX_LEN];
     43 	size_t session_id_len;
     44 	u8 client_random[TLS_RANDOM_LEN];
     45 	u8 server_random[TLS_RANDOM_LEN];
     46 	u8 master_secret[TLS_MASTER_SECRET_LEN];
     47 
     48 	u8 alert_level;
     49 	u8 alert_description;
     50 
     51 	unsigned int certificate_requested:1;
     52 	unsigned int session_resumed:1;
     53 	unsigned int ticket:1;
     54 	unsigned int ticket_key:1;
     55 
     56 	struct crypto_public_key *server_rsa_key;
     57 
     58 	struct crypto_hash *verify_md5_client;
     59 	struct crypto_hash *verify_sha1_client;
     60 	struct crypto_hash *verify_md5_server;
     61 	struct crypto_hash *verify_sha1_server;
     62 	struct crypto_hash *verify_md5_cert;
     63 	struct crypto_hash *verify_sha1_cert;
     64 
     65 #define MAX_CIPHER_COUNT 30
     66 	u16 cipher_suites[MAX_CIPHER_COUNT];
     67 	size_t num_cipher_suites;
     68 
     69 	u16 prev_cipher_suite;
     70 
     71 	u8 *client_hello_ext;
     72 	size_t client_hello_ext_len;
     73 
     74 	/* The prime modulus used for Diffie-Hellman */
     75 	u8 *dh_p;
     76 	size_t dh_p_len;
     77 	/* The generator used for Diffie-Hellman */
     78 	u8 *dh_g;
     79 	size_t dh_g_len;
     80 	/* The server's Diffie-Hellman public value */
     81 	u8 *dh_ys;
     82 	size_t dh_ys_len;
     83 
     84 	struct x509_certificate *trusted_certs;
     85 	struct x509_certificate *client_cert;
     86 	struct crypto_private_key *client_key;
     87 };
     88 
     89 
     90 static int tls_derive_keys(struct tlsv1_client *conn,
     91 			   const u8 *pre_master_secret,
     92 			   size_t pre_master_secret_len);
     93 static int tls_process_server_key_exchange(struct tlsv1_client *conn, u8 ct,
     94 					   const u8 *in_data, size_t *in_len);
     95 static int tls_process_certificate_request(struct tlsv1_client *conn, u8 ct,
     96 					   const u8 *in_data, size_t *in_len);
     97 static int tls_process_server_hello_done(struct tlsv1_client *conn, u8 ct,
     98 					 const u8 *in_data, size_t *in_len);
     99 
    100 
    101 static void tls_alert(struct tlsv1_client *conn, u8 level, u8 description)
    102 {
    103 	conn->alert_level = level;
    104 	conn->alert_description = description;
    105 }
    106 
    107 
    108 static void tls_verify_hash_add(struct tlsv1_client *conn, const u8 *buf,
    109 				size_t len)
    110 {
    111 	if (conn->verify_md5_client && conn->verify_sha1_client) {
    112 		crypto_hash_update(conn->verify_md5_client, buf, len);
    113 		crypto_hash_update(conn->verify_sha1_client, buf, len);
    114 	}
    115 	if (conn->verify_md5_server && conn->verify_sha1_server) {
    116 		crypto_hash_update(conn->verify_md5_server, buf, len);
    117 		crypto_hash_update(conn->verify_sha1_server, buf, len);
    118 	}
    119 	if (conn->verify_md5_cert && conn->verify_sha1_cert) {
    120 		crypto_hash_update(conn->verify_md5_cert, buf, len);
    121 		crypto_hash_update(conn->verify_sha1_cert, buf, len);
    122 	}
    123 }
    124 
    125 
    126 static u8 * tls_send_alert(struct tlsv1_client *conn,
    127 			   u8 level, u8 description,
    128 			   size_t *out_len)
    129 {
    130 	u8 *alert, *pos, *length;
    131 
    132 	wpa_printf(MSG_DEBUG, "TLSv1: Send Alert(%d:%d)", level, description);
    133 	*out_len = 0;
    134 
    135 	alert = os_malloc(10);
    136 	if (alert == NULL)
    137 		return NULL;
    138 
    139 	pos = alert;
    140 
    141 	/* TLSPlaintext */
    142 	/* ContentType type */
    143 	*pos++ = TLS_CONTENT_TYPE_ALERT;
    144 	/* ProtocolVersion version */
    145 	WPA_PUT_BE16(pos, TLS_VERSION);
    146 	pos += 2;
    147 	/* uint16 length (to be filled) */
    148 	length = pos;
    149 	pos += 2;
    150 	/* opaque fragment[TLSPlaintext.length] */
    151 
    152 	/* Alert */
    153 	/* AlertLevel level */
    154 	*pos++ = level;
    155 	/* AlertDescription description */
    156 	*pos++ = description;
    157 
    158 	WPA_PUT_BE16(length, pos - length - 2);
    159 	*out_len = pos - alert;
    160 
    161 	return alert;
    162 }
    163 
    164 
    165 static u8 * tls_send_client_hello(struct tlsv1_client *conn,
    166 				  size_t *out_len)
    167 {
    168 	u8 *hello, *end, *pos, *hs_length, *hs_start, *rhdr;
    169 	struct os_time now;
    170 	size_t len, i;
    171 
    172 	wpa_printf(MSG_DEBUG, "TLSv1: Send ClientHello");
    173 	*out_len = 0;
    174 
    175 	os_get_time(&now);
    176 	WPA_PUT_BE32(conn->client_random, now.sec);
    177 	if (os_get_random(conn->client_random + 4, TLS_RANDOM_LEN - 4)) {
    178 		wpa_printf(MSG_ERROR, "TLSv1: Could not generate "
    179 			   "client_random");
    180 		return NULL;
    181 	}
    182 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: client_random",
    183 		    conn->client_random, TLS_RANDOM_LEN);
    184 
    185 	len = 100 + conn->num_cipher_suites * 2 + conn->client_hello_ext_len;
    186 	hello = os_malloc(len);
    187 	if (hello == NULL)
    188 		return NULL;
    189 	end = hello + len;
    190 
    191 	rhdr = hello;
    192 	pos = rhdr + TLS_RECORD_HEADER_LEN;
    193 
    194 	/* opaque fragment[TLSPlaintext.length] */
    195 
    196 	/* Handshake */
    197 	hs_start = pos;
    198 	/* HandshakeType msg_type */
    199 	*pos++ = TLS_HANDSHAKE_TYPE_CLIENT_HELLO;
    200 	/* uint24 length (to be filled) */
    201 	hs_length = pos;
    202 	pos += 3;
    203 	/* body - ClientHello */
    204 	/* ProtocolVersion client_version */
    205 	WPA_PUT_BE16(pos, TLS_VERSION);
    206 	pos += 2;
    207 	/* Random random: uint32 gmt_unix_time, opaque random_bytes */
    208 	os_memcpy(pos, conn->client_random, TLS_RANDOM_LEN);
    209 	pos += TLS_RANDOM_LEN;
    210 	/* SessionID session_id */
    211 	*pos++ = conn->session_id_len;
    212 	os_memcpy(pos, conn->session_id, conn->session_id_len);
    213 	pos += conn->session_id_len;
    214 	/* CipherSuite cipher_suites<2..2^16-1> */
    215 	WPA_PUT_BE16(pos, 2 * conn->num_cipher_suites);
    216 	pos += 2;
    217 	for (i = 0; i < conn->num_cipher_suites; i++) {
    218 		WPA_PUT_BE16(pos, conn->cipher_suites[i]);
    219 		pos += 2;
    220 	}
    221 	/* CompressionMethod compression_methods<1..2^8-1> */
    222 	*pos++ = 1;
    223 	*pos++ = TLS_COMPRESSION_NULL;
    224 
    225 	if (conn->client_hello_ext) {
    226 		os_memcpy(pos, conn->client_hello_ext,
    227 			  conn->client_hello_ext_len);
    228 		pos += conn->client_hello_ext_len;
    229 	}
    230 
    231 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
    232 	tls_verify_hash_add(conn, hs_start, pos - hs_start);
    233 
    234 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
    235 			      rhdr, end - rhdr, pos - hs_start, out_len) < 0) {
    236 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create TLS record");
    237 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    238 			  TLS_ALERT_INTERNAL_ERROR);
    239 		os_free(hello);
    240 		return NULL;
    241 	}
    242 
    243 	conn->state = SERVER_HELLO;
    244 
    245 	return hello;
    246 }
    247 
    248 
    249 static int tls_process_server_hello(struct tlsv1_client *conn, u8 ct,
    250 				    const u8 *in_data, size_t *in_len)
    251 {
    252 	const u8 *pos, *end;
    253 	size_t left, len, i;
    254 	u16 cipher_suite;
    255 
    256 	if (ct != TLS_CONTENT_TYPE_HANDSHAKE) {
    257 		wpa_printf(MSG_DEBUG, "TLSv1: Expected Handshake; "
    258 			   "received content type 0x%x", ct);
    259 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    260 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    261 		return -1;
    262 	}
    263 
    264 	pos = in_data;
    265 	left = *in_len;
    266 
    267 	if (left < 4)
    268 		goto decode_error;
    269 
    270 	/* HandshakeType msg_type */
    271 	if (*pos != TLS_HANDSHAKE_TYPE_SERVER_HELLO) {
    272 		wpa_printf(MSG_DEBUG, "TLSv1: Received unexpected handshake "
    273 			   "message %d (expected ServerHello)", *pos);
    274 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    275 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    276 		return -1;
    277 	}
    278 	wpa_printf(MSG_DEBUG, "TLSv1: Received ServerHello");
    279 	pos++;
    280 	/* uint24 length */
    281 	len = WPA_GET_BE24(pos);
    282 	pos += 3;
    283 	left -= 4;
    284 
    285 	if (len > left)
    286 		goto decode_error;
    287 
    288 	/* body - ServerHello */
    289 
    290 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: ServerHello", pos, len);
    291 	end = pos + len;
    292 
    293 	/* ProtocolVersion server_version */
    294 	if (end - pos < 2)
    295 		goto decode_error;
    296 	if (WPA_GET_BE16(pos) != TLS_VERSION) {
    297 		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected protocol version in "
    298 			   "ServerHello");
    299 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    300 			  TLS_ALERT_PROTOCOL_VERSION);
    301 		return -1;
    302 	}
    303 	pos += 2;
    304 
    305 	/* Random random */
    306 	if (end - pos < TLS_RANDOM_LEN)
    307 		goto decode_error;
    308 
    309 	os_memcpy(conn->server_random, pos, TLS_RANDOM_LEN);
    310 	pos += TLS_RANDOM_LEN;
    311 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: server_random",
    312 		    conn->server_random, TLS_RANDOM_LEN);
    313 
    314 	/* SessionID session_id */
    315 	if (end - pos < 1)
    316 		goto decode_error;
    317 	if (end - pos < 1 + *pos || *pos > TLS_SESSION_ID_MAX_LEN)
    318 		goto decode_error;
    319 	if (conn->session_id_len && conn->session_id_len == *pos &&
    320 	    os_memcmp(conn->session_id, pos + 1, conn->session_id_len) == 0) {
    321 		pos += 1 + conn->session_id_len;
    322 		wpa_printf(MSG_DEBUG, "TLSv1: Resuming old session");
    323 		conn->session_resumed = 1;
    324 	} else {
    325 		conn->session_id_len = *pos;
    326 		pos++;
    327 		os_memcpy(conn->session_id, pos, conn->session_id_len);
    328 		pos += conn->session_id_len;
    329 	}
    330 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: session_id",
    331 		    conn->session_id, conn->session_id_len);
    332 
    333 	/* CipherSuite cipher_suite */
    334 	if (end - pos < 2)
    335 		goto decode_error;
    336 	cipher_suite = WPA_GET_BE16(pos);
    337 	pos += 2;
    338 	for (i = 0; i < conn->num_cipher_suites; i++) {
    339 		if (cipher_suite == conn->cipher_suites[i])
    340 			break;
    341 	}
    342 	if (i == conn->num_cipher_suites) {
    343 		wpa_printf(MSG_INFO, "TLSv1: Server selected unexpected "
    344 			   "cipher suite 0x%04x", cipher_suite);
    345 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    346 			  TLS_ALERT_ILLEGAL_PARAMETER);
    347 		return -1;
    348 	}
    349 
    350 	if (conn->session_resumed && cipher_suite != conn->prev_cipher_suite) {
    351 		wpa_printf(MSG_DEBUG, "TLSv1: Server selected a different "
    352 			   "cipher suite for a resumed connection (0x%04x != "
    353 			   "0x%04x)", cipher_suite, conn->prev_cipher_suite);
    354 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    355 			  TLS_ALERT_ILLEGAL_PARAMETER);
    356 		return -1;
    357 	}
    358 
    359 	if (tlsv1_record_set_cipher_suite(&conn->rl, cipher_suite) < 0) {
    360 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to set CipherSuite for "
    361 			   "record layer");
    362 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    363 			  TLS_ALERT_INTERNAL_ERROR);
    364 		return -1;
    365 	}
    366 
    367 	conn->prev_cipher_suite = cipher_suite;
    368 
    369 	if (conn->session_resumed || conn->ticket_key)
    370 		tls_derive_keys(conn, NULL, 0);
    371 
    372 	/* CompressionMethod compression_method */
    373 	if (end - pos < 1)
    374 		goto decode_error;
    375 	if (*pos != TLS_COMPRESSION_NULL) {
    376 		wpa_printf(MSG_INFO, "TLSv1: Server selected unexpected "
    377 			   "compression 0x%02x", *pos);
    378 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    379 			  TLS_ALERT_ILLEGAL_PARAMETER);
    380 		return -1;
    381 	}
    382 	pos++;
    383 
    384 	if (end != pos) {
    385 		wpa_hexdump(MSG_DEBUG, "TLSv1: Unexpected extra data in the "
    386 			    "end of ServerHello", pos, end - pos);
    387 		goto decode_error;
    388 	}
    389 
    390 	*in_len = end - in_data;
    391 
    392 	conn->state = (conn->session_resumed || conn->ticket) ?
    393 		SERVER_CHANGE_CIPHER_SPEC : SERVER_CERTIFICATE;
    394 
    395 	return 0;
    396 
    397 decode_error:
    398 	wpa_printf(MSG_DEBUG, "TLSv1: Failed to decode ServerHello");
    399 	tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    400 	return -1;
    401 }
    402 
    403 
    404 static int tls_server_key_exchange_allowed(struct tlsv1_client *conn)
    405 {
    406 	const struct tls_cipher_suite *suite;
    407 
    408 	/* RFC 2246, Section 7.4.3 */
    409 	suite = tls_get_cipher_suite(conn->rl.cipher_suite);
    410 	if (suite == NULL)
    411 		return 0;
    412 
    413 	switch (suite->key_exchange) {
    414 	case TLS_KEY_X_DHE_DSS:
    415 	case TLS_KEY_X_DHE_DSS_EXPORT:
    416 	case TLS_KEY_X_DHE_RSA:
    417 	case TLS_KEY_X_DHE_RSA_EXPORT:
    418 	case TLS_KEY_X_DH_anon_EXPORT:
    419 	case TLS_KEY_X_DH_anon:
    420 		return 1;
    421 	case TLS_KEY_X_RSA_EXPORT:
    422 		return 1 /* FIX: public key len > 512 bits */;
    423 	default:
    424 		return 0;
    425 	}
    426 }
    427 
    428 
    429 static int tls_process_certificate(struct tlsv1_client *conn, u8 ct,
    430 				   const u8 *in_data, size_t *in_len)
    431 {
    432 	const u8 *pos, *end;
    433 	size_t left, len, list_len, cert_len, idx;
    434 	u8 type;
    435 	struct x509_certificate *chain = NULL, *last = NULL, *cert;
    436 	int reason;
    437 
    438 	if (ct != TLS_CONTENT_TYPE_HANDSHAKE) {
    439 		wpa_printf(MSG_DEBUG, "TLSv1: Expected Handshake; "
    440 			   "received content type 0x%x", ct);
    441 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    442 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    443 		return -1;
    444 	}
    445 
    446 	pos = in_data;
    447 	left = *in_len;
    448 
    449 	if (left < 4) {
    450 		wpa_printf(MSG_DEBUG, "TLSv1: Too short Certificate message "
    451 			   "(len=%lu)", (unsigned long) left);
    452 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    453 		return -1;
    454 	}
    455 
    456 	type = *pos++;
    457 	len = WPA_GET_BE24(pos);
    458 	pos += 3;
    459 	left -= 4;
    460 
    461 	if (len > left) {
    462 		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected Certificate message "
    463 			   "length (len=%lu != left=%lu)",
    464 			   (unsigned long) len, (unsigned long) left);
    465 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    466 		return -1;
    467 	}
    468 
    469 	if (type == TLS_HANDSHAKE_TYPE_SERVER_KEY_EXCHANGE)
    470 		return tls_process_server_key_exchange(conn, ct, in_data,
    471 						       in_len);
    472 	if (type == TLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST)
    473 		return tls_process_certificate_request(conn, ct, in_data,
    474 						       in_len);
    475 	if (type == TLS_HANDSHAKE_TYPE_SERVER_HELLO_DONE)
    476 		return tls_process_server_hello_done(conn, ct, in_data,
    477 						     in_len);
    478 	if (type != TLS_HANDSHAKE_TYPE_CERTIFICATE) {
    479 		wpa_printf(MSG_DEBUG, "TLSv1: Received unexpected handshake "
    480 			   "message %d (expected Certificate/"
    481 			   "ServerKeyExchange/CertificateRequest/"
    482 			   "ServerHelloDone)", type);
    483 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    484 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    485 		return -1;
    486 	}
    487 
    488 	wpa_printf(MSG_DEBUG,
    489 		   "TLSv1: Received Certificate (certificate_list len %lu)",
    490 		   (unsigned long) len);
    491 
    492 	/*
    493 	 * opaque ASN.1Cert<2^24-1>;
    494 	 *
    495 	 * struct {
    496 	 *     ASN.1Cert certificate_list<1..2^24-1>;
    497 	 * } Certificate;
    498 	 */
    499 
    500 	end = pos + len;
    501 
    502 	if (end - pos < 3) {
    503 		wpa_printf(MSG_DEBUG, "TLSv1: Too short Certificate "
    504 			   "(left=%lu)", (unsigned long) left);
    505 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    506 		return -1;
    507 	}
    508 
    509 	list_len = WPA_GET_BE24(pos);
    510 	pos += 3;
    511 
    512 	if ((size_t) (end - pos) != list_len) {
    513 		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected certificate_list "
    514 			   "length (len=%lu left=%lu)",
    515 			   (unsigned long) list_len,
    516 			   (unsigned long) (end - pos));
    517 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    518 		return -1;
    519 	}
    520 
    521 	idx = 0;
    522 	while (pos < end) {
    523 		if (end - pos < 3) {
    524 			wpa_printf(MSG_DEBUG, "TLSv1: Failed to parse "
    525 				   "certificate_list");
    526 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    527 				  TLS_ALERT_DECODE_ERROR);
    528 			x509_certificate_chain_free(chain);
    529 			return -1;
    530 		}
    531 
    532 		cert_len = WPA_GET_BE24(pos);
    533 		pos += 3;
    534 
    535 		if ((size_t) (end - pos) < cert_len) {
    536 			wpa_printf(MSG_DEBUG, "TLSv1: Unexpected certificate "
    537 				   "length (len=%lu left=%lu)",
    538 				   (unsigned long) cert_len,
    539 				   (unsigned long) (end - pos));
    540 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    541 				  TLS_ALERT_DECODE_ERROR);
    542 			x509_certificate_chain_free(chain);
    543 			return -1;
    544 		}
    545 
    546 		wpa_printf(MSG_DEBUG, "TLSv1: Certificate %lu (len %lu)",
    547 			   (unsigned long) idx, (unsigned long) cert_len);
    548 
    549 		if (idx == 0) {
    550 			crypto_public_key_free(conn->server_rsa_key);
    551 			if (tls_parse_cert(pos, cert_len,
    552 					   &conn->server_rsa_key)) {
    553 				wpa_printf(MSG_DEBUG, "TLSv1: Failed to parse "
    554 					   "the certificate");
    555 				tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    556 					  TLS_ALERT_BAD_CERTIFICATE);
    557 				x509_certificate_chain_free(chain);
    558 				return -1;
    559 			}
    560 		}
    561 
    562 		cert = x509_certificate_parse(pos, cert_len);
    563 		if (cert == NULL) {
    564 			wpa_printf(MSG_DEBUG, "TLSv1: Failed to parse "
    565 				   "the certificate");
    566 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    567 				  TLS_ALERT_BAD_CERTIFICATE);
    568 			x509_certificate_chain_free(chain);
    569 			return -1;
    570 		}
    571 
    572 		if (last == NULL)
    573 			chain = cert;
    574 		else
    575 			last->next = cert;
    576 		last = cert;
    577 
    578 		idx++;
    579 		pos += cert_len;
    580 	}
    581 
    582 	if (x509_certificate_chain_validate(conn->trusted_certs, chain,
    583 					    &reason) < 0) {
    584 		int tls_reason;
    585 		wpa_printf(MSG_DEBUG, "TLSv1: Server certificate chain "
    586 			   "validation failed (reason=%d)", reason);
    587 		switch (reason) {
    588 		case X509_VALIDATE_BAD_CERTIFICATE:
    589 			tls_reason = TLS_ALERT_BAD_CERTIFICATE;
    590 			break;
    591 		case X509_VALIDATE_UNSUPPORTED_CERTIFICATE:
    592 			tls_reason = TLS_ALERT_UNSUPPORTED_CERTIFICATE;
    593 			break;
    594 		case X509_VALIDATE_CERTIFICATE_REVOKED:
    595 			tls_reason = TLS_ALERT_CERTIFICATE_REVOKED;
    596 			break;
    597 		case X509_VALIDATE_CERTIFICATE_EXPIRED:
    598 			tls_reason = TLS_ALERT_CERTIFICATE_EXPIRED;
    599 			break;
    600 		case X509_VALIDATE_CERTIFICATE_UNKNOWN:
    601 			tls_reason = TLS_ALERT_CERTIFICATE_UNKNOWN;
    602 			break;
    603 		case X509_VALIDATE_UNKNOWN_CA:
    604 			tls_reason = TLS_ALERT_UNKNOWN_CA;
    605 			break;
    606 		default:
    607 			tls_reason = TLS_ALERT_BAD_CERTIFICATE;
    608 			break;
    609 		}
    610 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, tls_reason);
    611 		x509_certificate_chain_free(chain);
    612 		return -1;
    613 	}
    614 
    615 	x509_certificate_chain_free(chain);
    616 
    617 	*in_len = end - in_data;
    618 
    619 	conn->state = SERVER_KEY_EXCHANGE;
    620 
    621 	return 0;
    622 }
    623 
    624 
    625 static void tlsv1_client_free_dh(struct tlsv1_client *conn)
    626 {
    627 	os_free(conn->dh_p);
    628 	os_free(conn->dh_g);
    629 	os_free(conn->dh_ys);
    630 	conn->dh_p = conn->dh_g = conn->dh_ys = NULL;
    631 }
    632 
    633 
    634 static int tlsv1_process_diffie_hellman(struct tlsv1_client *conn,
    635 					const u8 *buf, size_t len)
    636 {
    637 	const u8 *pos, *end;
    638 
    639 	tlsv1_client_free_dh(conn);
    640 
    641 	pos = buf;
    642 	end = buf + len;
    643 
    644 	if (end - pos < 3)
    645 		goto fail;
    646 	conn->dh_p_len = WPA_GET_BE16(pos);
    647 	pos += 2;
    648 	if (conn->dh_p_len == 0 || end - pos < (int) conn->dh_p_len)
    649 		goto fail;
    650 	conn->dh_p = os_malloc(conn->dh_p_len);
    651 	if (conn->dh_p == NULL)
    652 		goto fail;
    653 	os_memcpy(conn->dh_p, pos, conn->dh_p_len);
    654 	pos += conn->dh_p_len;
    655 	wpa_hexdump(MSG_DEBUG, "TLSv1: DH p (prime)",
    656 		    conn->dh_p, conn->dh_p_len);
    657 
    658 	if (end - pos < 3)
    659 		goto fail;
    660 	conn->dh_g_len = WPA_GET_BE16(pos);
    661 	pos += 2;
    662 	if (conn->dh_g_len == 0 || end - pos < (int) conn->dh_g_len)
    663 		goto fail;
    664 	conn->dh_g = os_malloc(conn->dh_g_len);
    665 	if (conn->dh_g == NULL)
    666 		goto fail;
    667 	os_memcpy(conn->dh_g, pos, conn->dh_g_len);
    668 	pos += conn->dh_g_len;
    669 	wpa_hexdump(MSG_DEBUG, "TLSv1: DH g (generator)",
    670 		    conn->dh_g, conn->dh_g_len);
    671 	if (conn->dh_g_len == 1 && conn->dh_g[0] < 2)
    672 		goto fail;
    673 
    674 	if (end - pos < 3)
    675 		goto fail;
    676 	conn->dh_ys_len = WPA_GET_BE16(pos);
    677 	pos += 2;
    678 	if (conn->dh_ys_len == 0 || end - pos < (int) conn->dh_ys_len)
    679 		goto fail;
    680 	conn->dh_ys = os_malloc(conn->dh_ys_len);
    681 	if (conn->dh_ys == NULL)
    682 		goto fail;
    683 	os_memcpy(conn->dh_ys, pos, conn->dh_ys_len);
    684 	pos += conn->dh_ys_len;
    685 	wpa_hexdump(MSG_DEBUG, "TLSv1: DH Ys (server's public value)",
    686 		    conn->dh_ys, conn->dh_ys_len);
    687 
    688 	return 0;
    689 
    690 fail:
    691 	tlsv1_client_free_dh(conn);
    692 	return -1;
    693 }
    694 
    695 
    696 static int tls_process_server_key_exchange(struct tlsv1_client *conn, u8 ct,
    697 					   const u8 *in_data, size_t *in_len)
    698 {
    699 	const u8 *pos, *end;
    700 	size_t left, len;
    701 	u8 type;
    702 	const struct tls_cipher_suite *suite;
    703 
    704 	if (ct != TLS_CONTENT_TYPE_HANDSHAKE) {
    705 		wpa_printf(MSG_DEBUG, "TLSv1: Expected Handshake; "
    706 			   "received content type 0x%x", ct);
    707 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    708 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    709 		return -1;
    710 	}
    711 
    712 	pos = in_data;
    713 	left = *in_len;
    714 
    715 	if (left < 4) {
    716 		wpa_printf(MSG_DEBUG, "TLSv1: Too short ServerKeyExchange "
    717 			   "(Left=%lu)", (unsigned long) left);
    718 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    719 		return -1;
    720 	}
    721 
    722 	type = *pos++;
    723 	len = WPA_GET_BE24(pos);
    724 	pos += 3;
    725 	left -= 4;
    726 
    727 	if (len > left) {
    728 		wpa_printf(MSG_DEBUG, "TLSv1: Mismatch in ServerKeyExchange "
    729 			   "length (len=%lu != left=%lu)",
    730 			   (unsigned long) len, (unsigned long) left);
    731 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    732 		return -1;
    733 	}
    734 
    735 	end = pos + len;
    736 
    737 	if (type == TLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST)
    738 		return tls_process_certificate_request(conn, ct, in_data,
    739 						       in_len);
    740 	if (type == TLS_HANDSHAKE_TYPE_SERVER_HELLO_DONE)
    741 		return tls_process_server_hello_done(conn, ct, in_data,
    742 						     in_len);
    743 	if (type != TLS_HANDSHAKE_TYPE_SERVER_KEY_EXCHANGE) {
    744 		wpa_printf(MSG_DEBUG, "TLSv1: Received unexpected handshake "
    745 			   "message %d (expected ServerKeyExchange/"
    746 			   "CertificateRequest/ServerHelloDone)", type);
    747 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    748 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    749 		return -1;
    750 	}
    751 
    752 	wpa_printf(MSG_DEBUG, "TLSv1: Received ServerKeyExchange");
    753 
    754 	if (!tls_server_key_exchange_allowed(conn)) {
    755 		wpa_printf(MSG_DEBUG, "TLSv1: ServerKeyExchange not allowed "
    756 			   "with the selected cipher suite");
    757 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    758 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    759 		return -1;
    760 	}
    761 
    762 	wpa_hexdump(MSG_DEBUG, "TLSv1: ServerKeyExchange", pos, len);
    763 	suite = tls_get_cipher_suite(conn->rl.cipher_suite);
    764 	if (suite && suite->key_exchange == TLS_KEY_X_DH_anon) {
    765 		if (tlsv1_process_diffie_hellman(conn, pos, len) < 0) {
    766 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    767 				  TLS_ALERT_DECODE_ERROR);
    768 			return -1;
    769 		}
    770 	} else {
    771 		wpa_printf(MSG_DEBUG, "TLSv1: UnexpectedServerKeyExchange");
    772 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    773 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    774 		return -1;
    775 	}
    776 
    777 	*in_len = end - in_data;
    778 
    779 	conn->state = SERVER_CERTIFICATE_REQUEST;
    780 
    781 	return 0;
    782 }
    783 
    784 
    785 static int tls_process_certificate_request(struct tlsv1_client *conn, u8 ct,
    786 					   const u8 *in_data, size_t *in_len)
    787 {
    788 	const u8 *pos, *end;
    789 	size_t left, len;
    790 	u8 type;
    791 
    792 	if (ct != TLS_CONTENT_TYPE_HANDSHAKE) {
    793 		wpa_printf(MSG_DEBUG, "TLSv1: Expected Handshake; "
    794 			   "received content type 0x%x", ct);
    795 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    796 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    797 		return -1;
    798 	}
    799 
    800 	pos = in_data;
    801 	left = *in_len;
    802 
    803 	if (left < 4) {
    804 		wpa_printf(MSG_DEBUG, "TLSv1: Too short CertificateRequest "
    805 			   "(left=%lu)", (unsigned long) left);
    806 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    807 		return -1;
    808 	}
    809 
    810 	type = *pos++;
    811 	len = WPA_GET_BE24(pos);
    812 	pos += 3;
    813 	left -= 4;
    814 
    815 	if (len > left) {
    816 		wpa_printf(MSG_DEBUG, "TLSv1: Mismatch in CertificateRequest "
    817 			   "length (len=%lu != left=%lu)",
    818 			   (unsigned long) len, (unsigned long) left);
    819 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    820 		return -1;
    821 	}
    822 
    823 	end = pos + len;
    824 
    825 	if (type == TLS_HANDSHAKE_TYPE_SERVER_HELLO_DONE)
    826 		return tls_process_server_hello_done(conn, ct, in_data,
    827 						     in_len);
    828 	if (type != TLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST) {
    829 		wpa_printf(MSG_DEBUG, "TLSv1: Received unexpected handshake "
    830 			   "message %d (expected CertificateRequest/"
    831 			   "ServerHelloDone)", type);
    832 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    833 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    834 		return -1;
    835 	}
    836 
    837 	wpa_printf(MSG_DEBUG, "TLSv1: Received CertificateRequest");
    838 
    839 	conn->certificate_requested = 1;
    840 
    841 	*in_len = end - in_data;
    842 
    843 	conn->state = SERVER_HELLO_DONE;
    844 
    845 	return 0;
    846 }
    847 
    848 
    849 static int tls_process_server_hello_done(struct tlsv1_client *conn, u8 ct,
    850 					 const u8 *in_data, size_t *in_len)
    851 {
    852 	const u8 *pos, *end;
    853 	size_t left, len;
    854 	u8 type;
    855 
    856 	if (ct != TLS_CONTENT_TYPE_HANDSHAKE) {
    857 		wpa_printf(MSG_DEBUG, "TLSv1: Expected Handshake; "
    858 			   "received content type 0x%x", ct);
    859 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    860 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    861 		return -1;
    862 	}
    863 
    864 	pos = in_data;
    865 	left = *in_len;
    866 
    867 	if (left < 4) {
    868 		wpa_printf(MSG_DEBUG, "TLSv1: Too short ServerHelloDone "
    869 			   "(left=%lu)", (unsigned long) left);
    870 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    871 		return -1;
    872 	}
    873 
    874 	type = *pos++;
    875 	len = WPA_GET_BE24(pos);
    876 	pos += 3;
    877 	left -= 4;
    878 
    879 	if (len > left) {
    880 		wpa_printf(MSG_DEBUG, "TLSv1: Mismatch in ServerHelloDone "
    881 			   "length (len=%lu != left=%lu)",
    882 			   (unsigned long) len, (unsigned long) left);
    883 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    884 		return -1;
    885 	}
    886 	end = pos + len;
    887 
    888 	if (type != TLS_HANDSHAKE_TYPE_SERVER_HELLO_DONE) {
    889 		wpa_printf(MSG_DEBUG, "TLSv1: Received unexpected handshake "
    890 			   "message %d (expected ServerHelloDone)", type);
    891 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    892 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    893 		return -1;
    894 	}
    895 
    896 	wpa_printf(MSG_DEBUG, "TLSv1: Received ServerHelloDone");
    897 
    898 	*in_len = end - in_data;
    899 
    900 	conn->state = CLIENT_KEY_EXCHANGE;
    901 
    902 	return 0;
    903 }
    904 
    905 
    906 static int tls_process_server_change_cipher_spec(struct tlsv1_client *conn,
    907 						 u8 ct, const u8 *in_data,
    908 						 size_t *in_len)
    909 {
    910 	const u8 *pos;
    911 	size_t left;
    912 
    913 	if (ct != TLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC) {
    914 		wpa_printf(MSG_DEBUG, "TLSv1: Expected ChangeCipherSpec; "
    915 			   "received content type 0x%x", ct);
    916 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    917 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    918 		return -1;
    919 	}
    920 
    921 	pos = in_data;
    922 	left = *in_len;
    923 
    924 	if (left < 1) {
    925 		wpa_printf(MSG_DEBUG, "TLSv1: Too short ChangeCipherSpec");
    926 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
    927 		return -1;
    928 	}
    929 
    930 	if (*pos != TLS_CHANGE_CIPHER_SPEC) {
    931 		wpa_printf(MSG_DEBUG, "TLSv1: Expected ChangeCipherSpec; "
    932 			   "received data 0x%x", *pos);
    933 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    934 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    935 		return -1;
    936 	}
    937 
    938 	wpa_printf(MSG_DEBUG, "TLSv1: Received ChangeCipherSpec");
    939 	if (tlsv1_record_change_read_cipher(&conn->rl) < 0) {
    940 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to change read cipher "
    941 			   "for record layer");
    942 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    943 			  TLS_ALERT_INTERNAL_ERROR);
    944 		return -1;
    945 	}
    946 
    947 	*in_len = pos + 1 - in_data;
    948 
    949 	conn->state = SERVER_FINISHED;
    950 
    951 	return 0;
    952 }
    953 
    954 
    955 static int tls_process_server_finished(struct tlsv1_client *conn, u8 ct,
    956 				       const u8 *in_data, size_t *in_len)
    957 {
    958 	const u8 *pos, *end;
    959 	size_t left, len, hlen;
    960 	u8 verify_data[TLS_VERIFY_DATA_LEN];
    961 	u8 hash[MD5_MAC_LEN + SHA1_MAC_LEN];
    962 
    963 	if (ct != TLS_CONTENT_TYPE_HANDSHAKE) {
    964 		wpa_printf(MSG_DEBUG, "TLSv1: Expected Finished; "
    965 			   "received content type 0x%x", ct);
    966 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    967 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    968 		return -1;
    969 	}
    970 
    971 	pos = in_data;
    972 	left = *in_len;
    973 
    974 	if (left < 4) {
    975 		wpa_printf(MSG_DEBUG, "TLSv1: Too short record (left=%lu) for "
    976 			   "Finished",
    977 			   (unsigned long) left);
    978 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    979 			  TLS_ALERT_DECODE_ERROR);
    980 		return -1;
    981 	}
    982 
    983 	if (pos[0] != TLS_HANDSHAKE_TYPE_FINISHED) {
    984 		wpa_printf(MSG_DEBUG, "TLSv1: Expected Finished; received "
    985 			   "type 0x%x", pos[0]);
    986 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
    987 			  TLS_ALERT_UNEXPECTED_MESSAGE);
    988 		return -1;
    989 	}
    990 
    991 	len = WPA_GET_BE24(pos + 1);
    992 
    993 	pos += 4;
    994 	left -= 4;
    995 
    996 	if (len > left) {
    997 		wpa_printf(MSG_DEBUG, "TLSv1: Too short buffer for Finished "
    998 			   "(len=%lu > left=%lu)",
    999 			   (unsigned long) len, (unsigned long) left);
   1000 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1001 			  TLS_ALERT_DECODE_ERROR);
   1002 		return -1;
   1003 	}
   1004 	end = pos + len;
   1005 	if (len != TLS_VERIFY_DATA_LEN) {
   1006 		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected verify_data length "
   1007 			   "in Finished: %lu (expected %d)",
   1008 			   (unsigned long) len, TLS_VERIFY_DATA_LEN);
   1009 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1010 			  TLS_ALERT_DECODE_ERROR);
   1011 		return -1;
   1012 	}
   1013 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: verify_data in Finished",
   1014 		    pos, TLS_VERIFY_DATA_LEN);
   1015 
   1016 	hlen = MD5_MAC_LEN;
   1017 	if (conn->verify_md5_server == NULL ||
   1018 	    crypto_hash_finish(conn->verify_md5_server, hash, &hlen) < 0) {
   1019 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1020 			  TLS_ALERT_INTERNAL_ERROR);
   1021 		conn->verify_md5_server = NULL;
   1022 		crypto_hash_finish(conn->verify_sha1_server, NULL, NULL);
   1023 		conn->verify_sha1_server = NULL;
   1024 		return -1;
   1025 	}
   1026 	conn->verify_md5_server = NULL;
   1027 	hlen = SHA1_MAC_LEN;
   1028 	if (conn->verify_sha1_server == NULL ||
   1029 	    crypto_hash_finish(conn->verify_sha1_server, hash + MD5_MAC_LEN,
   1030 			       &hlen) < 0) {
   1031 		conn->verify_sha1_server = NULL;
   1032 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1033 			  TLS_ALERT_INTERNAL_ERROR);
   1034 		return -1;
   1035 	}
   1036 	conn->verify_sha1_server = NULL;
   1037 
   1038 	if (tls_prf(conn->master_secret, TLS_MASTER_SECRET_LEN,
   1039 		    "server finished", hash, MD5_MAC_LEN + SHA1_MAC_LEN,
   1040 		    verify_data, TLS_VERIFY_DATA_LEN)) {
   1041 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive verify_data");
   1042 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1043 			  TLS_ALERT_DECRYPT_ERROR);
   1044 		return -1;
   1045 	}
   1046 	wpa_hexdump_key(MSG_DEBUG, "TLSv1: verify_data (server)",
   1047 			verify_data, TLS_VERIFY_DATA_LEN);
   1048 
   1049 	if (os_memcmp(pos, verify_data, TLS_VERIFY_DATA_LEN) != 0) {
   1050 		wpa_printf(MSG_INFO, "TLSv1: Mismatch in verify_data");
   1051 		return -1;
   1052 	}
   1053 
   1054 	wpa_printf(MSG_DEBUG, "TLSv1: Received Finished");
   1055 
   1056 	*in_len = end - in_data;
   1057 
   1058 	conn->state = (conn->session_resumed || conn->ticket) ?
   1059 		CHANGE_CIPHER_SPEC : ACK_FINISHED;
   1060 
   1061 	return 0;
   1062 }
   1063 
   1064 
   1065 static int tls_derive_pre_master_secret(u8 *pre_master_secret)
   1066 {
   1067 	WPA_PUT_BE16(pre_master_secret, TLS_VERSION);
   1068 	if (os_get_random(pre_master_secret + 2,
   1069 			  TLS_PRE_MASTER_SECRET_LEN - 2))
   1070 		return -1;
   1071 	return 0;
   1072 }
   1073 
   1074 
   1075 static int tls_derive_keys(struct tlsv1_client *conn,
   1076 			   const u8 *pre_master_secret,
   1077 			   size_t pre_master_secret_len)
   1078 {
   1079 	u8 seed[2 * TLS_RANDOM_LEN];
   1080 	u8 key_block[TLS_MAX_KEY_BLOCK_LEN];
   1081 	u8 *pos;
   1082 	size_t key_block_len;
   1083 
   1084 	if (pre_master_secret) {
   1085 		wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: pre_master_secret",
   1086 				pre_master_secret, pre_master_secret_len);
   1087 		os_memcpy(seed, conn->client_random, TLS_RANDOM_LEN);
   1088 		os_memcpy(seed + TLS_RANDOM_LEN, conn->server_random,
   1089 			  TLS_RANDOM_LEN);
   1090 		if (tls_prf(pre_master_secret, pre_master_secret_len,
   1091 			    "master secret", seed, 2 * TLS_RANDOM_LEN,
   1092 			    conn->master_secret, TLS_MASTER_SECRET_LEN)) {
   1093 			wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive "
   1094 				   "master_secret");
   1095 			return -1;
   1096 		}
   1097 		wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: master_secret",
   1098 				conn->master_secret, TLS_MASTER_SECRET_LEN);
   1099 	}
   1100 
   1101 	os_memcpy(seed, conn->server_random, TLS_RANDOM_LEN);
   1102 	os_memcpy(seed + TLS_RANDOM_LEN, conn->client_random, TLS_RANDOM_LEN);
   1103 	key_block_len = 2 * (conn->rl.hash_size + conn->rl.key_material_len +
   1104 			     conn->rl.iv_size);
   1105 	if (tls_prf(conn->master_secret, TLS_MASTER_SECRET_LEN,
   1106 		    "key expansion", seed, 2 * TLS_RANDOM_LEN,
   1107 		    key_block, key_block_len)) {
   1108 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive key_block");
   1109 		return -1;
   1110 	}
   1111 	wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: key_block",
   1112 			key_block, key_block_len);
   1113 
   1114 	pos = key_block;
   1115 
   1116 	/* client_write_MAC_secret */
   1117 	os_memcpy(conn->rl.write_mac_secret, pos, conn->rl.hash_size);
   1118 	pos += conn->rl.hash_size;
   1119 	/* server_write_MAC_secret */
   1120 	os_memcpy(conn->rl.read_mac_secret, pos, conn->rl.hash_size);
   1121 	pos += conn->rl.hash_size;
   1122 
   1123 	/* client_write_key */
   1124 	os_memcpy(conn->rl.write_key, pos, conn->rl.key_material_len);
   1125 	pos += conn->rl.key_material_len;
   1126 	/* server_write_key */
   1127 	os_memcpy(conn->rl.read_key, pos, conn->rl.key_material_len);
   1128 	pos += conn->rl.key_material_len;
   1129 
   1130 	/* client_write_IV */
   1131 	os_memcpy(conn->rl.write_iv, pos, conn->rl.iv_size);
   1132 	pos += conn->rl.iv_size;
   1133 	/* server_write_IV */
   1134 	os_memcpy(conn->rl.read_iv, pos, conn->rl.iv_size);
   1135 	pos += conn->rl.iv_size;
   1136 
   1137 	return 0;
   1138 }
   1139 
   1140 
   1141 static int tls_write_client_certificate(struct tlsv1_client *conn,
   1142 					u8 **msgpos, u8 *end)
   1143 {
   1144 	u8 *pos, *rhdr, *hs_start, *hs_length, *cert_start;
   1145 	size_t rlen;
   1146 	struct x509_certificate *cert;
   1147 
   1148 	pos = *msgpos;
   1149 
   1150 	wpa_printf(MSG_DEBUG, "TLSv1: Send Certificate");
   1151 	rhdr = pos;
   1152 	pos += TLS_RECORD_HEADER_LEN;
   1153 
   1154 	/* opaque fragment[TLSPlaintext.length] */
   1155 
   1156 	/* Handshake */
   1157 	hs_start = pos;
   1158 	/* HandshakeType msg_type */
   1159 	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE;
   1160 	/* uint24 length (to be filled) */
   1161 	hs_length = pos;
   1162 	pos += 3;
   1163 	/* body - Certificate */
   1164 	/* uint24 length (to be filled) */
   1165 	cert_start = pos;
   1166 	pos += 3;
   1167 	cert = conn->client_cert;
   1168 	while (cert) {
   1169 		if (pos + 3 + cert->cert_len > end) {
   1170 			wpa_printf(MSG_DEBUG, "TLSv1: Not enough buffer space "
   1171 				   "for Certificate (cert_len=%lu left=%lu)",
   1172 				   (unsigned long) cert->cert_len,
   1173 				   (unsigned long) (end - pos));
   1174 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1175 				  TLS_ALERT_INTERNAL_ERROR);
   1176 			return -1;
   1177 		}
   1178 		WPA_PUT_BE24(pos, cert->cert_len);
   1179 		pos += 3;
   1180 		os_memcpy(pos, cert->cert_start, cert->cert_len);
   1181 		pos += cert->cert_len;
   1182 
   1183 		if (x509_certificate_self_signed(cert))
   1184 			break;
   1185 		cert = x509_certificate_get_subject(conn->trusted_certs,
   1186 						    &cert->issuer);
   1187 	}
   1188 	if (cert == conn->client_cert || cert == NULL) {
   1189 		/*
   1190 		 * Client was not configured with all the needed certificates
   1191 		 * to form a full certificate chain. The server may fail to
   1192 		 * validate the chain unless it is configured with all the
   1193 		 * missing CA certificates.
   1194 		 */
   1195 		wpa_printf(MSG_DEBUG, "TLSv1: Full client certificate chain "
   1196 			   "not configured - validation may fail");
   1197 	}
   1198 	WPA_PUT_BE24(cert_start, pos - cert_start - 3);
   1199 
   1200 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
   1201 
   1202 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
   1203 			      rhdr, end - rhdr, pos - hs_start, &rlen) < 0) {
   1204 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
   1205 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1206 			  TLS_ALERT_INTERNAL_ERROR);
   1207 		return -1;
   1208 	}
   1209 	pos = rhdr + rlen;
   1210 
   1211 	tls_verify_hash_add(conn, hs_start, pos - hs_start);
   1212 
   1213 	*msgpos = pos;
   1214 
   1215 	return 0;
   1216 }
   1217 
   1218 
   1219 static int tlsv1_key_x_anon_dh(struct tlsv1_client *conn, u8 **pos, u8 *end)
   1220 {
   1221 #ifdef EAP_FAST
   1222 	/* ClientDiffieHellmanPublic */
   1223 	u8 *csecret, *csecret_start, *dh_yc, *shared;
   1224 	size_t csecret_len, dh_yc_len, shared_len;
   1225 
   1226 	csecret_len = conn->dh_p_len;
   1227 	csecret = os_malloc(csecret_len);
   1228 	if (csecret == NULL) {
   1229 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to allocate "
   1230 			   "memory for Yc (Diffie-Hellman)");
   1231 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1232 			  TLS_ALERT_INTERNAL_ERROR);
   1233 		return -1;
   1234 	}
   1235 	if (os_get_random(csecret, csecret_len)) {
   1236 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to get random "
   1237 			   "data for Diffie-Hellman");
   1238 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1239 			  TLS_ALERT_INTERNAL_ERROR);
   1240 		os_free(csecret);
   1241 		return -1;
   1242 	}
   1243 
   1244 	if (os_memcmp(csecret, conn->dh_p, csecret_len) > 0)
   1245 		csecret[0] = 0; /* make sure Yc < p */
   1246 
   1247 	csecret_start = csecret;
   1248 	while (csecret_len > 1 && *csecret_start == 0) {
   1249 		csecret_start++;
   1250 		csecret_len--;
   1251 	}
   1252 	wpa_hexdump_key(MSG_DEBUG, "TLSv1: DH client's secret value",
   1253 			csecret_start, csecret_len);
   1254 
   1255 	/* Yc = g^csecret mod p */
   1256 	dh_yc_len = conn->dh_p_len;
   1257 	dh_yc = os_malloc(dh_yc_len);
   1258 	if (dh_yc == NULL) {
   1259 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to allocate "
   1260 			   "memory for Diffie-Hellman");
   1261 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1262 			  TLS_ALERT_INTERNAL_ERROR);
   1263 		os_free(csecret);
   1264 		return -1;
   1265 	}
   1266 	crypto_mod_exp(conn->dh_g, conn->dh_g_len,
   1267 		       csecret_start, csecret_len,
   1268 		       conn->dh_p, conn->dh_p_len,
   1269 		       dh_yc, &dh_yc_len);
   1270 
   1271 	wpa_hexdump(MSG_DEBUG, "TLSv1: DH Yc (client's public value)",
   1272 		    dh_yc, dh_yc_len);
   1273 
   1274 	WPA_PUT_BE16(*pos, dh_yc_len);
   1275 	*pos += 2;
   1276 	if (*pos + dh_yc_len > end) {
   1277 		wpa_printf(MSG_DEBUG, "TLSv1: Not enough room in the "
   1278 			   "message buffer for Yc");
   1279 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1280 			  TLS_ALERT_INTERNAL_ERROR);
   1281 		os_free(csecret);
   1282 		os_free(dh_yc);
   1283 		return -1;
   1284 	}
   1285 	os_memcpy(*pos, dh_yc, dh_yc_len);
   1286 	*pos += dh_yc_len;
   1287 	os_free(dh_yc);
   1288 
   1289 	shared_len = conn->dh_p_len;
   1290 	shared = os_malloc(shared_len);
   1291 	if (shared == NULL) {
   1292 		wpa_printf(MSG_DEBUG, "TLSv1: Could not allocate memory for "
   1293 			   "DH");
   1294 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1295 			  TLS_ALERT_INTERNAL_ERROR);
   1296 		os_free(csecret);
   1297 		return -1;
   1298 	}
   1299 
   1300 	/* shared = Ys^csecret mod p */
   1301 	crypto_mod_exp(conn->dh_ys, conn->dh_ys_len,
   1302 		       csecret_start, csecret_len,
   1303 		       conn->dh_p, conn->dh_p_len,
   1304 		       shared, &shared_len);
   1305 	wpa_hexdump_key(MSG_DEBUG, "TLSv1: Shared secret from DH key exchange",
   1306 			shared, shared_len);
   1307 
   1308 	os_memset(csecret_start, 0, csecret_len);
   1309 	os_free(csecret);
   1310 	if (tls_derive_keys(conn, shared, shared_len)) {
   1311 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive keys");
   1312 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1313 			  TLS_ALERT_INTERNAL_ERROR);
   1314 		os_free(shared);
   1315 		return -1;
   1316 	}
   1317 	os_memset(shared, 0, shared_len);
   1318 	os_free(shared);
   1319 	tlsv1_client_free_dh(conn);
   1320 	return 0;
   1321 #else /* EAP_FAST */
   1322 	tls_alert(conn, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_INTERNAL_ERROR);
   1323 	return -1;
   1324 #endif /* EAP_FAST */
   1325 }
   1326 
   1327 
   1328 static int tlsv1_key_x_rsa(struct tlsv1_client *conn, u8 **pos, u8 *end)
   1329 {
   1330 	u8 pre_master_secret[TLS_PRE_MASTER_SECRET_LEN];
   1331 	size_t clen;
   1332 	int res;
   1333 
   1334 	if (tls_derive_pre_master_secret(pre_master_secret) < 0 ||
   1335 	    tls_derive_keys(conn, pre_master_secret,
   1336 			    TLS_PRE_MASTER_SECRET_LEN)) {
   1337 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive keys");
   1338 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1339 			  TLS_ALERT_INTERNAL_ERROR);
   1340 		return -1;
   1341 	}
   1342 
   1343 	/* EncryptedPreMasterSecret */
   1344 	if (conn->server_rsa_key == NULL) {
   1345 		wpa_printf(MSG_DEBUG, "TLSv1: No server RSA key to "
   1346 			   "use for encrypting pre-master secret");
   1347 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1348 			  TLS_ALERT_INTERNAL_ERROR);
   1349 		return -1;
   1350 	}
   1351 
   1352 	/* RSA encrypted value is encoded with PKCS #1 v1.5 block type 2. */
   1353 	*pos += 2;
   1354 	clen = end - *pos;
   1355 	res = crypto_public_key_encrypt_pkcs1_v15(
   1356 		conn->server_rsa_key,
   1357 		pre_master_secret, TLS_PRE_MASTER_SECRET_LEN,
   1358 		*pos, &clen);
   1359 	os_memset(pre_master_secret, 0, TLS_PRE_MASTER_SECRET_LEN);
   1360 	if (res < 0) {
   1361 		wpa_printf(MSG_DEBUG, "TLSv1: RSA encryption failed");
   1362 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1363 			  TLS_ALERT_INTERNAL_ERROR);
   1364 		return -1;
   1365 	}
   1366 	WPA_PUT_BE16(*pos - 2, clen);
   1367 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: Encrypted pre_master_secret",
   1368 		    *pos, clen);
   1369 	*pos += clen;
   1370 
   1371 	return 0;
   1372 }
   1373 
   1374 
   1375 static int tls_write_client_key_exchange(struct tlsv1_client *conn,
   1376 					 u8 **msgpos, u8 *end)
   1377 {
   1378 	u8 *pos, *rhdr, *hs_start, *hs_length;
   1379 	size_t rlen;
   1380 	tls_key_exchange keyx;
   1381 	const struct tls_cipher_suite *suite;
   1382 
   1383 	suite = tls_get_cipher_suite(conn->rl.cipher_suite);
   1384 	if (suite == NULL)
   1385 		keyx = TLS_KEY_X_NULL;
   1386 	else
   1387 		keyx = suite->key_exchange;
   1388 
   1389 	pos = *msgpos;
   1390 
   1391 	wpa_printf(MSG_DEBUG, "TLSv1: Send ClientKeyExchange");
   1392 
   1393 	rhdr = pos;
   1394 	pos += TLS_RECORD_HEADER_LEN;
   1395 
   1396 	/* opaque fragment[TLSPlaintext.length] */
   1397 
   1398 	/* Handshake */
   1399 	hs_start = pos;
   1400 	/* HandshakeType msg_type */
   1401 	*pos++ = TLS_HANDSHAKE_TYPE_CLIENT_KEY_EXCHANGE;
   1402 	/* uint24 length (to be filled) */
   1403 	hs_length = pos;
   1404 	pos += 3;
   1405 	/* body - ClientKeyExchange */
   1406 	if (keyx == TLS_KEY_X_DH_anon) {
   1407 		if (tlsv1_key_x_anon_dh(conn, &pos, end) < 0)
   1408 			return -1;
   1409 	} else {
   1410 		if (tlsv1_key_x_rsa(conn, &pos, end) < 0)
   1411 			return -1;
   1412 	}
   1413 
   1414 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
   1415 
   1416 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
   1417 			      rhdr, end - rhdr, pos - hs_start, &rlen) < 0) {
   1418 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
   1419 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1420 			  TLS_ALERT_INTERNAL_ERROR);
   1421 		return -1;
   1422 	}
   1423 	pos = rhdr + rlen;
   1424 	tls_verify_hash_add(conn, hs_start, pos - hs_start);
   1425 
   1426 	*msgpos = pos;
   1427 
   1428 	return 0;
   1429 }
   1430 
   1431 
   1432 static int tls_write_client_certificate_verify(struct tlsv1_client *conn,
   1433 					       u8 **msgpos, u8 *end)
   1434 {
   1435 	u8 *pos, *rhdr, *hs_start, *hs_length, *signed_start;
   1436 	size_t rlen, hlen, clen;
   1437 	u8 hash[MD5_MAC_LEN + SHA1_MAC_LEN], *hpos;
   1438 	enum { SIGN_ALG_RSA, SIGN_ALG_DSA } alg = SIGN_ALG_RSA;
   1439 
   1440 	pos = *msgpos;
   1441 
   1442 	wpa_printf(MSG_DEBUG, "TLSv1: Send CertificateVerify");
   1443 	rhdr = pos;
   1444 	pos += TLS_RECORD_HEADER_LEN;
   1445 
   1446 	/* Handshake */
   1447 	hs_start = pos;
   1448 	/* HandshakeType msg_type */
   1449 	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY;
   1450 	/* uint24 length (to be filled) */
   1451 	hs_length = pos;
   1452 	pos += 3;
   1453 
   1454 	/*
   1455 	 * RFC 2246: 7.4.3 and 7.4.8:
   1456 	 * Signature signature
   1457 	 *
   1458 	 * RSA:
   1459 	 * digitally-signed struct {
   1460 	 *     opaque md5_hash[16];
   1461 	 *     opaque sha_hash[20];
   1462 	 * };
   1463 	 *
   1464 	 * DSA:
   1465 	 * digitally-signed struct {
   1466 	 *     opaque sha_hash[20];
   1467 	 * };
   1468 	 *
   1469 	 * The hash values are calculated over all handshake messages sent or
   1470 	 * received starting at ClientHello up to, but not including, this
   1471 	 * CertificateVerify message, including the type and length fields of
   1472 	 * the handshake messages.
   1473 	 */
   1474 
   1475 	hpos = hash;
   1476 
   1477 	if (alg == SIGN_ALG_RSA) {
   1478 		hlen = MD5_MAC_LEN;
   1479 		if (conn->verify_md5_cert == NULL ||
   1480 		    crypto_hash_finish(conn->verify_md5_cert, hpos, &hlen) < 0)
   1481 		{
   1482 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1483 				  TLS_ALERT_INTERNAL_ERROR);
   1484 			conn->verify_md5_cert = NULL;
   1485 			crypto_hash_finish(conn->verify_sha1_cert, NULL, NULL);
   1486 			conn->verify_sha1_cert = NULL;
   1487 			return -1;
   1488 		}
   1489 		hpos += MD5_MAC_LEN;
   1490 	} else
   1491 		crypto_hash_finish(conn->verify_md5_cert, NULL, NULL);
   1492 
   1493 	conn->verify_md5_cert = NULL;
   1494 	hlen = SHA1_MAC_LEN;
   1495 	if (conn->verify_sha1_cert == NULL ||
   1496 	    crypto_hash_finish(conn->verify_sha1_cert, hpos, &hlen) < 0) {
   1497 		conn->verify_sha1_cert = NULL;
   1498 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1499 			  TLS_ALERT_INTERNAL_ERROR);
   1500 		return -1;
   1501 	}
   1502 	conn->verify_sha1_cert = NULL;
   1503 
   1504 	if (alg == SIGN_ALG_RSA)
   1505 		hlen += MD5_MAC_LEN;
   1506 
   1507 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: CertificateVerify hash", hash, hlen);
   1508 
   1509 	/*
   1510 	 * RFC 2246, 4.7:
   1511 	 * In digital signing, one-way hash functions are used as input for a
   1512 	 * signing algorithm. A digitally-signed element is encoded as an
   1513 	 * opaque vector <0..2^16-1>, where the length is specified by the
   1514 	 * signing algorithm and key.
   1515 	 *
   1516 	 * In RSA signing, a 36-byte structure of two hashes (one SHA and one
   1517 	 * MD5) is signed (encrypted with the private key). It is encoded with
   1518 	 * PKCS #1 block type 0 or type 1 as described in [PKCS1].
   1519 	 */
   1520 	signed_start = pos; /* length to be filled */
   1521 	pos += 2;
   1522 	clen = end - pos;
   1523 	if (crypto_private_key_sign_pkcs1(conn->client_key, hash, hlen,
   1524 					  pos, &clen) < 0) {
   1525 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to sign hash (PKCS #1)");
   1526 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1527 			  TLS_ALERT_INTERNAL_ERROR);
   1528 		return -1;
   1529 	}
   1530 	WPA_PUT_BE16(signed_start, clen);
   1531 
   1532 	pos += clen;
   1533 
   1534 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
   1535 
   1536 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
   1537 			      rhdr, end - rhdr, pos - hs_start, &rlen) < 0) {
   1538 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
   1539 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1540 			  TLS_ALERT_INTERNAL_ERROR);
   1541 		return -1;
   1542 	}
   1543 	pos = rhdr + rlen;
   1544 
   1545 	tls_verify_hash_add(conn, hs_start, pos - hs_start);
   1546 
   1547 	*msgpos = pos;
   1548 
   1549 	return 0;
   1550 }
   1551 
   1552 
   1553 static int tls_write_client_change_cipher_spec(struct tlsv1_client *conn,
   1554 					       u8 **msgpos, u8 *end)
   1555 {
   1556 	u8 *pos, *rhdr;
   1557 	size_t rlen;
   1558 
   1559 	pos = *msgpos;
   1560 
   1561 	wpa_printf(MSG_DEBUG, "TLSv1: Send ChangeCipherSpec");
   1562 	rhdr = pos;
   1563 	pos += TLS_RECORD_HEADER_LEN;
   1564 	*pos = TLS_CHANGE_CIPHER_SPEC;
   1565 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC,
   1566 			      rhdr, end - rhdr, 1, &rlen) < 0) {
   1567 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
   1568 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1569 			  TLS_ALERT_INTERNAL_ERROR);
   1570 		return -1;
   1571 	}
   1572 
   1573 	if (tlsv1_record_change_write_cipher(&conn->rl) < 0) {
   1574 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to set write cipher for "
   1575 			   "record layer");
   1576 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1577 			  TLS_ALERT_INTERNAL_ERROR);
   1578 		return -1;
   1579 	}
   1580 
   1581 	*msgpos = rhdr + rlen;
   1582 
   1583 	return 0;
   1584 }
   1585 
   1586 
   1587 static int tls_write_client_finished(struct tlsv1_client *conn,
   1588 				     u8 **msgpos, u8 *end)
   1589 {
   1590 	u8 *pos, *rhdr, *hs_start, *hs_length;
   1591 	size_t rlen, hlen;
   1592 	u8 verify_data[TLS_VERIFY_DATA_LEN];
   1593 	u8 hash[MD5_MAC_LEN + SHA1_MAC_LEN];
   1594 
   1595 	pos = *msgpos;
   1596 
   1597 	wpa_printf(MSG_DEBUG, "TLSv1: Send Finished");
   1598 
   1599 	/* Encrypted Handshake Message: Finished */
   1600 
   1601 	hlen = MD5_MAC_LEN;
   1602 	if (conn->verify_md5_client == NULL ||
   1603 	    crypto_hash_finish(conn->verify_md5_client, hash, &hlen) < 0) {
   1604 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1605 			  TLS_ALERT_INTERNAL_ERROR);
   1606 		conn->verify_md5_client = NULL;
   1607 		crypto_hash_finish(conn->verify_sha1_client, NULL, NULL);
   1608 		conn->verify_sha1_client = NULL;
   1609 		return -1;
   1610 	}
   1611 	conn->verify_md5_client = NULL;
   1612 	hlen = SHA1_MAC_LEN;
   1613 	if (conn->verify_sha1_client == NULL ||
   1614 	    crypto_hash_finish(conn->verify_sha1_client, hash + MD5_MAC_LEN,
   1615 			       &hlen) < 0) {
   1616 		conn->verify_sha1_client = NULL;
   1617 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1618 			  TLS_ALERT_INTERNAL_ERROR);
   1619 		return -1;
   1620 	}
   1621 	conn->verify_sha1_client = NULL;
   1622 
   1623 	if (tls_prf(conn->master_secret, TLS_MASTER_SECRET_LEN,
   1624 		    "client finished", hash, MD5_MAC_LEN + SHA1_MAC_LEN,
   1625 		    verify_data, TLS_VERIFY_DATA_LEN)) {
   1626 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate verify_data");
   1627 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1628 			  TLS_ALERT_INTERNAL_ERROR);
   1629 		return -1;
   1630 	}
   1631 	wpa_hexdump_key(MSG_DEBUG, "TLSv1: verify_data (client)",
   1632 			verify_data, TLS_VERIFY_DATA_LEN);
   1633 
   1634 	rhdr = pos;
   1635 	pos += TLS_RECORD_HEADER_LEN;
   1636 	/* Handshake */
   1637 	hs_start = pos;
   1638 	/* HandshakeType msg_type */
   1639 	*pos++ = TLS_HANDSHAKE_TYPE_FINISHED;
   1640 	/* uint24 length (to be filled) */
   1641 	hs_length = pos;
   1642 	pos += 3;
   1643 	os_memcpy(pos, verify_data, TLS_VERIFY_DATA_LEN);
   1644 	pos += TLS_VERIFY_DATA_LEN;
   1645 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
   1646 	tls_verify_hash_add(conn, hs_start, pos - hs_start);
   1647 
   1648 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
   1649 			      rhdr, end - rhdr, pos - hs_start, &rlen) < 0) {
   1650 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
   1651 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1652 			  TLS_ALERT_INTERNAL_ERROR);
   1653 		return -1;
   1654 	}
   1655 
   1656 	pos = rhdr + rlen;
   1657 
   1658 	*msgpos = pos;
   1659 
   1660 	return 0;
   1661 }
   1662 
   1663 
   1664 static size_t tls_client_cert_chain_der_len(struct tlsv1_client *conn)
   1665 {
   1666 	size_t len = 0;
   1667 	struct x509_certificate *cert;
   1668 
   1669 	cert = conn->client_cert;
   1670 	while (cert) {
   1671 		len += 3 + cert->cert_len;
   1672 		if (x509_certificate_self_signed(cert))
   1673 			break;
   1674 		cert = x509_certificate_get_subject(conn->trusted_certs,
   1675 						    &cert->issuer);
   1676 	}
   1677 
   1678 	return len;
   1679 }
   1680 
   1681 
   1682 static u8 * tls_send_client_key_exchange(struct tlsv1_client *conn,
   1683 					 size_t *out_len)
   1684 {
   1685 	u8 *msg, *end, *pos;
   1686 	size_t msglen;
   1687 
   1688 	*out_len = 0;
   1689 
   1690 	msglen = 1000;
   1691 	if (conn->certificate_requested)
   1692 		msglen += tls_client_cert_chain_der_len(conn);
   1693 
   1694 	msg = os_malloc(msglen);
   1695 	if (msg == NULL)
   1696 		return NULL;
   1697 
   1698 	pos = msg;
   1699 	end = msg + msglen;
   1700 
   1701 	if (conn->certificate_requested) {
   1702 		if (tls_write_client_certificate(conn, &pos, end) < 0) {
   1703 			os_free(msg);
   1704 			return NULL;
   1705 		}
   1706 	}
   1707 
   1708 	if (tls_write_client_key_exchange(conn, &pos, end) < 0 ||
   1709 	    (conn->certificate_requested && conn->client_key &&
   1710 	     tls_write_client_certificate_verify(conn, &pos, end) < 0) ||
   1711 	    tls_write_client_change_cipher_spec(conn, &pos, end) < 0 ||
   1712 	    tls_write_client_finished(conn, &pos, end) < 0) {
   1713 		os_free(msg);
   1714 		return NULL;
   1715 	}
   1716 
   1717 	*out_len = pos - msg;
   1718 
   1719 	conn->state = SERVER_CHANGE_CIPHER_SPEC;
   1720 
   1721 	return msg;
   1722 }
   1723 
   1724 
   1725 static u8 * tls_send_change_cipher_spec(struct tlsv1_client *conn,
   1726 					size_t *out_len)
   1727 {
   1728 	u8 *msg, *end, *pos;
   1729 
   1730 	*out_len = 0;
   1731 
   1732 	msg = os_malloc(1000);
   1733 	if (msg == NULL)
   1734 		return NULL;
   1735 
   1736 	pos = msg;
   1737 	end = msg + 1000;
   1738 
   1739 	if (tls_write_client_change_cipher_spec(conn, &pos, end) < 0 ||
   1740 	    tls_write_client_finished(conn, &pos, end) < 0) {
   1741 		os_free(msg);
   1742 		return NULL;
   1743 	}
   1744 
   1745 	*out_len = pos - msg;
   1746 
   1747 	wpa_printf(MSG_DEBUG, "TLSv1: Session resumption completed "
   1748 		   "successfully");
   1749 	conn->state = ESTABLISHED;
   1750 
   1751 	return msg;
   1752 }
   1753 
   1754 
   1755 static int tlsv1_client_process_handshake(struct tlsv1_client *conn, u8 ct,
   1756 					  const u8 *buf, size_t *len)
   1757 {
   1758 	if (ct == TLS_CONTENT_TYPE_HANDSHAKE && *len >= 4 &&
   1759 	    buf[0] == TLS_HANDSHAKE_TYPE_HELLO_REQUEST) {
   1760 		size_t hr_len = WPA_GET_BE24(buf + 1);
   1761 		if (hr_len > *len - 4) {
   1762 			wpa_printf(MSG_DEBUG, "TLSv1: HelloRequest underflow");
   1763 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1764 				  TLS_ALERT_DECODE_ERROR);
   1765 			return -1;
   1766 		}
   1767 		wpa_printf(MSG_DEBUG, "TLSv1: Ignored HelloRequest");
   1768 		*len = 4 + hr_len;
   1769 		return 0;
   1770 	}
   1771 
   1772 	switch (conn->state) {
   1773 	case SERVER_HELLO:
   1774 		if (tls_process_server_hello(conn, ct, buf, len))
   1775 			return -1;
   1776 		break;
   1777 	case SERVER_CERTIFICATE:
   1778 		if (tls_process_certificate(conn, ct, buf, len))
   1779 			return -1;
   1780 		break;
   1781 	case SERVER_KEY_EXCHANGE:
   1782 		if (tls_process_server_key_exchange(conn, ct, buf, len))
   1783 			return -1;
   1784 		break;
   1785 	case SERVER_CERTIFICATE_REQUEST:
   1786 		if (tls_process_certificate_request(conn, ct, buf, len))
   1787 			return -1;
   1788 		break;
   1789 	case SERVER_HELLO_DONE:
   1790 		if (tls_process_server_hello_done(conn, ct, buf, len))
   1791 			return -1;
   1792 		break;
   1793 	case SERVER_CHANGE_CIPHER_SPEC:
   1794 		if (tls_process_server_change_cipher_spec(conn, ct, buf, len))
   1795 			return -1;
   1796 		break;
   1797 	case SERVER_FINISHED:
   1798 		if (tls_process_server_finished(conn, ct, buf, len))
   1799 			return -1;
   1800 		break;
   1801 	default:
   1802 		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected state %d "
   1803 			   "while processing received message",
   1804 			   conn->state);
   1805 		return -1;
   1806 	}
   1807 
   1808 	if (ct == TLS_CONTENT_TYPE_HANDSHAKE)
   1809 		tls_verify_hash_add(conn, buf, *len);
   1810 
   1811 	return 0;
   1812 }
   1813 
   1814 
   1815 /**
   1816  * tlsv1_client_handshake - Process TLS handshake
   1817  * @conn: TLSv1 client connection data from tlsv1_client_init()
   1818  * @in_data: Input data from TLS peer
   1819  * @in_len: Input data length
   1820  * @out_len: Length of the output buffer.
   1821  * Returns: Pointer to output data, %NULL on failure
   1822  */
   1823 u8 * tlsv1_client_handshake(struct tlsv1_client *conn,
   1824 			    const u8 *in_data, size_t in_len,
   1825 			    size_t *out_len)
   1826 {
   1827 	const u8 *pos, *end;
   1828 	u8 *msg = NULL, *in_msg, *in_pos, *in_end, alert, ct;
   1829 	size_t in_msg_len;
   1830 
   1831 	if (conn->state == CLIENT_HELLO) {
   1832 		if (in_len)
   1833 			return NULL;
   1834 		return tls_send_client_hello(conn, out_len);
   1835 	}
   1836 
   1837 	if (in_data == NULL || in_len == 0)
   1838 		return NULL;
   1839 
   1840 	pos = in_data;
   1841 	end = in_data + in_len;
   1842 	in_msg = os_malloc(in_len);
   1843 	if (in_msg == NULL)
   1844 		return NULL;
   1845 
   1846 	/* Each received packet may include multiple records */
   1847 	while (pos < end) {
   1848 		in_msg_len = in_len;
   1849 		if (tlsv1_record_receive(&conn->rl, pos, end - pos,
   1850 					 in_msg, &in_msg_len, &alert)) {
   1851 			wpa_printf(MSG_DEBUG, "TLSv1: Processing received "
   1852 				   "record failed");
   1853 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL, alert);
   1854 			goto failed;
   1855 		}
   1856 		ct = pos[0];
   1857 
   1858 		in_pos = in_msg;
   1859 		in_end = in_msg + in_msg_len;
   1860 
   1861 		/* Each received record may include multiple messages of the
   1862 		 * same ContentType. */
   1863 		while (in_pos < in_end) {
   1864 			in_msg_len = in_end - in_pos;
   1865 			if (tlsv1_client_process_handshake(conn, ct, in_pos,
   1866 							   &in_msg_len) < 0)
   1867 				goto failed;
   1868 			in_pos += in_msg_len;
   1869 		}
   1870 
   1871 		pos += TLS_RECORD_HEADER_LEN + WPA_GET_BE16(pos + 3);
   1872 	}
   1873 
   1874 	os_free(in_msg);
   1875 	in_msg = NULL;
   1876 
   1877 	switch (conn->state) {
   1878 	case CLIENT_KEY_EXCHANGE:
   1879 		msg = tls_send_client_key_exchange(conn, out_len);
   1880 		break;
   1881 	case CHANGE_CIPHER_SPEC:
   1882 		msg = tls_send_change_cipher_spec(conn, out_len);
   1883 		break;
   1884 	case ACK_FINISHED:
   1885 		wpa_printf(MSG_DEBUG, "TLSv1: Handshake completed "
   1886 			   "successfully");
   1887 		conn->state = ESTABLISHED;
   1888 		/* Need to return something to get final TLS ACK. */
   1889 		msg = os_malloc(1);
   1890 		*out_len = 0;
   1891 		break;
   1892 	default:
   1893 		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected state %d while "
   1894 			   "generating reply", conn->state);
   1895 		break;
   1896 	}
   1897 
   1898 failed:
   1899 	os_free(in_msg);
   1900 	if (conn->alert_level) {
   1901 		conn->state = FAILED;
   1902 		os_free(msg);
   1903 		msg = tls_send_alert(conn, conn->alert_level,
   1904 				     conn->alert_description, out_len);
   1905 	}
   1906 
   1907 	return msg;
   1908 }
   1909 
   1910 
   1911 /**
   1912  * tlsv1_client_encrypt - Encrypt data into TLS tunnel
   1913  * @conn: TLSv1 client connection data from tlsv1_client_init()
   1914  * @in_data: Pointer to plaintext data to be encrypted
   1915  * @in_len: Input buffer length
   1916  * @out_data: Pointer to output buffer (encrypted TLS data)
   1917  * @out_len: Maximum out_data length
   1918  * Returns: Number of bytes written to out_data, -1 on failure
   1919  *
   1920  * This function is used after TLS handshake has been completed successfully to
   1921  * send data in the encrypted tunnel.
   1922  */
   1923 int tlsv1_client_encrypt(struct tlsv1_client *conn,
   1924 			 const u8 *in_data, size_t in_len,
   1925 			 u8 *out_data, size_t out_len)
   1926 {
   1927 	size_t rlen;
   1928 
   1929 	wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: Plaintext AppData",
   1930 			in_data, in_len);
   1931 
   1932 	os_memcpy(out_data + TLS_RECORD_HEADER_LEN, in_data, in_len);
   1933 
   1934 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_APPLICATION_DATA,
   1935 			      out_data, out_len, in_len, &rlen) < 0) {
   1936 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
   1937 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1938 			  TLS_ALERT_INTERNAL_ERROR);
   1939 		return -1;
   1940 	}
   1941 
   1942 	return rlen;
   1943 }
   1944 
   1945 
   1946 /**
   1947  * tlsv1_client_decrypt - Decrypt data from TLS tunnel
   1948  * @conn: TLSv1 client connection data from tlsv1_client_init()
   1949  * @in_data: Pointer to input buffer (encrypted TLS data)
   1950  * @in_len: Input buffer length
   1951  * @out_data: Pointer to output buffer (decrypted data from TLS tunnel)
   1952  * @out_len: Maximum out_data length
   1953  * Returns: Number of bytes written to out_data, -1 on failure
   1954  *
   1955  * This function is used after TLS handshake has been completed successfully to
   1956  * receive data from the encrypted tunnel.
   1957  */
   1958 int tlsv1_client_decrypt(struct tlsv1_client *conn,
   1959 			 const u8 *in_data, size_t in_len,
   1960 			 u8 *out_data, size_t out_len)
   1961 {
   1962 	const u8 *in_end, *pos;
   1963 	int res;
   1964 	u8 alert, *out_end, *out_pos;
   1965 	size_t olen;
   1966 
   1967 	pos = in_data;
   1968 	in_end = in_data + in_len;
   1969 	out_pos = out_data;
   1970 	out_end = out_data + out_len;
   1971 
   1972 	while (pos < in_end) {
   1973 		if (pos[0] != TLS_CONTENT_TYPE_APPLICATION_DATA) {
   1974 			wpa_printf(MSG_DEBUG, "TLSv1: Unexpected content type "
   1975 				   "0x%x", pos[0]);
   1976 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1977 				  TLS_ALERT_UNEXPECTED_MESSAGE);
   1978 			return -1;
   1979 		}
   1980 
   1981 		olen = out_end - out_pos;
   1982 		res = tlsv1_record_receive(&conn->rl, pos, in_end - pos,
   1983 					   out_pos, &olen, &alert);
   1984 		if (res < 0) {
   1985 			wpa_printf(MSG_DEBUG, "TLSv1: Record layer processing "
   1986 				   "failed");
   1987 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL, alert);
   1988 			return -1;
   1989 		}
   1990 		out_pos += olen;
   1991 		if (out_pos > out_end) {
   1992 			wpa_printf(MSG_DEBUG, "TLSv1: Buffer not large enough "
   1993 				   "for processing the received record");
   1994 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
   1995 				  TLS_ALERT_INTERNAL_ERROR);
   1996 			return -1;
   1997 		}
   1998 
   1999 		pos += TLS_RECORD_HEADER_LEN + WPA_GET_BE16(pos + 3);
   2000 	}
   2001 
   2002 	return out_pos - out_data;
   2003 }
   2004 
   2005 
   2006 /**
   2007  * tlsv1_client_global_init - Initialize TLSv1 client
   2008  * Returns: 0 on success, -1 on failure
   2009  *
   2010  * This function must be called before using any other TLSv1 client functions.
   2011  */
   2012 int tlsv1_client_global_init(void)
   2013 {
   2014 	return crypto_global_init();
   2015 }
   2016 
   2017 
   2018 /**
   2019  * tlsv1_client_global_deinit - Deinitialize TLSv1 client
   2020  *
   2021  * This function can be used to deinitialize the TLSv1 client that was
   2022  * initialized by calling tlsv1_client_global_init(). No TLSv1 client functions
   2023  * can be called after this before calling tlsv1_client_global_init() again.
   2024  */
   2025 void tlsv1_client_global_deinit(void)
   2026 {
   2027 	crypto_global_deinit();
   2028 }
   2029 
   2030 
   2031 static void tlsv1_client_free_verify_hashes(struct tlsv1_client *conn)
   2032 {
   2033 	crypto_hash_finish(conn->verify_md5_client, NULL, NULL);
   2034 	crypto_hash_finish(conn->verify_md5_server, NULL, NULL);
   2035 	crypto_hash_finish(conn->verify_md5_cert, NULL, NULL);
   2036 	crypto_hash_finish(conn->verify_sha1_client, NULL, NULL);
   2037 	crypto_hash_finish(conn->verify_sha1_server, NULL, NULL);
   2038 	crypto_hash_finish(conn->verify_sha1_cert, NULL, NULL);
   2039 	conn->verify_md5_client = NULL;
   2040 	conn->verify_md5_server = NULL;
   2041 	conn->verify_md5_cert = NULL;
   2042 	conn->verify_sha1_client = NULL;
   2043 	conn->verify_sha1_server = NULL;
   2044 	conn->verify_sha1_cert = NULL;
   2045 }
   2046 
   2047 
   2048 static int tlsv1_client_init_verify_hashes(struct tlsv1_client *conn)
   2049 {
   2050 	conn->verify_md5_client = crypto_hash_init(CRYPTO_HASH_ALG_MD5, NULL,
   2051 						   0);
   2052 	conn->verify_md5_server = crypto_hash_init(CRYPTO_HASH_ALG_MD5, NULL,
   2053 						   0);
   2054 	conn->verify_md5_cert = crypto_hash_init(CRYPTO_HASH_ALG_MD5, NULL, 0);
   2055 	conn->verify_sha1_client = crypto_hash_init(CRYPTO_HASH_ALG_SHA1, NULL,
   2056 						    0);
   2057 	conn->verify_sha1_server = crypto_hash_init(CRYPTO_HASH_ALG_SHA1, NULL,
   2058 						    0);
   2059 	conn->verify_sha1_cert = crypto_hash_init(CRYPTO_HASH_ALG_SHA1, NULL,
   2060 						  0);
   2061 	if (conn->verify_md5_client == NULL ||
   2062 	    conn->verify_md5_server == NULL ||
   2063 	    conn->verify_md5_cert == NULL ||
   2064 	    conn->verify_sha1_client == NULL ||
   2065 	    conn->verify_sha1_server == NULL ||
   2066 	    conn->verify_sha1_cert == NULL) {
   2067 		tlsv1_client_free_verify_hashes(conn);
   2068 		return -1;
   2069 	}
   2070 	return 0;
   2071 }
   2072 
   2073 
   2074 /**
   2075  * tlsv1_client_init - Initialize TLSv1 client connection
   2076  * Returns: Pointer to TLSv1 client connection data or %NULL on failure
   2077  */
   2078 struct tlsv1_client * tlsv1_client_init(void)
   2079 {
   2080 	struct tlsv1_client *conn;
   2081 	size_t count;
   2082 	u16 *suites;
   2083 
   2084 	conn = os_zalloc(sizeof(*conn));
   2085 	if (conn == NULL)
   2086 		return NULL;
   2087 
   2088 	conn->state = CLIENT_HELLO;
   2089 
   2090 	if (tlsv1_client_init_verify_hashes(conn) < 0) {
   2091 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to initialize verify "
   2092 			   "hash");
   2093 		os_free(conn);
   2094 		return NULL;
   2095 	}
   2096 
   2097 	count = 0;
   2098 	suites = conn->cipher_suites;
   2099 #ifndef CONFIG_CRYPTO_INTERNAL
   2100 	suites[count++] = TLS_RSA_WITH_AES_256_CBC_SHA;
   2101 #endif /* CONFIG_CRYPTO_INTERNAL */
   2102 	suites[count++] = TLS_RSA_WITH_AES_128_CBC_SHA;
   2103 	suites[count++] = TLS_RSA_WITH_3DES_EDE_CBC_SHA;
   2104 	suites[count++] = TLS_RSA_WITH_RC4_128_SHA;
   2105 	suites[count++] = TLS_RSA_WITH_RC4_128_MD5;
   2106 	conn->num_cipher_suites = count;
   2107 
   2108 	return conn;
   2109 }
   2110 
   2111 
   2112 /**
   2113  * tlsv1_client_deinit - Deinitialize TLSv1 client connection
   2114  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2115  */
   2116 void tlsv1_client_deinit(struct tlsv1_client *conn)
   2117 {
   2118 	crypto_public_key_free(conn->server_rsa_key);
   2119 	tlsv1_record_set_cipher_suite(&conn->rl, TLS_NULL_WITH_NULL_NULL);
   2120 	tlsv1_record_change_write_cipher(&conn->rl);
   2121 	tlsv1_record_change_read_cipher(&conn->rl);
   2122 	tlsv1_client_free_verify_hashes(conn);
   2123 	os_free(conn->client_hello_ext);
   2124 	tlsv1_client_free_dh(conn);
   2125 	x509_certificate_chain_free(conn->trusted_certs);
   2126 	x509_certificate_chain_free(conn->client_cert);
   2127 	crypto_private_key_free(conn->client_key);
   2128 	os_free(conn);
   2129 }
   2130 
   2131 
   2132 /**
   2133  * tlsv1_client_established - Check whether connection has been established
   2134  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2135  * Returns: 1 if connection is established, 0 if not
   2136  */
   2137 int tlsv1_client_established(struct tlsv1_client *conn)
   2138 {
   2139 	return conn->state == ESTABLISHED;
   2140 }
   2141 
   2142 
   2143 /**
   2144  * tlsv1_client_prf - Use TLS-PRF to derive keying material
   2145  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2146  * @label: Label (e.g., description of the key) for PRF
   2147  * @server_random_first: seed is 0 = client_random|server_random,
   2148  * 1 = server_random|client_random
   2149  * @out: Buffer for output data from TLS-PRF
   2150  * @out_len: Length of the output buffer
   2151  * Returns: 0 on success, -1 on failure
   2152  */
   2153 int tlsv1_client_prf(struct tlsv1_client *conn, const char *label,
   2154 		     int server_random_first, u8 *out, size_t out_len)
   2155 {
   2156 	u8 seed[2 * TLS_RANDOM_LEN];
   2157 
   2158 	if (conn->state != ESTABLISHED)
   2159 		return -1;
   2160 
   2161 	if (server_random_first) {
   2162 		os_memcpy(seed, conn->server_random, TLS_RANDOM_LEN);
   2163 		os_memcpy(seed + TLS_RANDOM_LEN, conn->client_random,
   2164 			  TLS_RANDOM_LEN);
   2165 	} else {
   2166 		os_memcpy(seed, conn->client_random, TLS_RANDOM_LEN);
   2167 		os_memcpy(seed + TLS_RANDOM_LEN, conn->server_random,
   2168 			  TLS_RANDOM_LEN);
   2169 	}
   2170 
   2171 	return tls_prf(conn->master_secret, TLS_MASTER_SECRET_LEN,
   2172 		       label, seed, 2 * TLS_RANDOM_LEN, out, out_len);
   2173 }
   2174 
   2175 
   2176 /**
   2177  * tlsv1_client_get_cipher - Get current cipher name
   2178  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2179  * @buf: Buffer for the cipher name
   2180  * @buflen: buf size
   2181  * Returns: 0 on success, -1 on failure
   2182  *
   2183  * Get the name of the currently used cipher.
   2184  */
   2185 int tlsv1_client_get_cipher(struct tlsv1_client *conn, char *buf,
   2186 			    size_t buflen)
   2187 {
   2188 	char *cipher;
   2189 
   2190 	switch (conn->rl.cipher_suite) {
   2191 	case TLS_RSA_WITH_RC4_128_MD5:
   2192 		cipher = "RC4-MD5";
   2193 		break;
   2194 	case TLS_RSA_WITH_RC4_128_SHA:
   2195 		cipher = "RC4-SHA";
   2196 		break;
   2197 	case TLS_RSA_WITH_DES_CBC_SHA:
   2198 		cipher = "DES-CBC-SHA";
   2199 		break;
   2200 	case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
   2201 		cipher = "DES-CBC3-SHA";
   2202 		break;
   2203 	default:
   2204 		return -1;
   2205 	}
   2206 
   2207 	os_snprintf(buf, buflen, "%s", cipher);
   2208 	return 0;
   2209 }
   2210 
   2211 
   2212 /**
   2213  * tlsv1_client_shutdown - Shutdown TLS connection
   2214  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2215  * Returns: 0 on success, -1 on failure
   2216  */
   2217 int tlsv1_client_shutdown(struct tlsv1_client *conn)
   2218 {
   2219 	conn->state = CLIENT_HELLO;
   2220 
   2221 	tlsv1_client_free_verify_hashes(conn);
   2222 	if (tlsv1_client_init_verify_hashes(conn) < 0) {
   2223 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to re-initialize verify "
   2224 			   "hash");
   2225 		return -1;
   2226 	}
   2227 
   2228 	tlsv1_record_set_cipher_suite(&conn->rl, TLS_NULL_WITH_NULL_NULL);
   2229 	tlsv1_record_change_write_cipher(&conn->rl);
   2230 	tlsv1_record_change_read_cipher(&conn->rl);
   2231 
   2232 	conn->certificate_requested = 0;
   2233 	crypto_public_key_free(conn->server_rsa_key);
   2234 	conn->server_rsa_key = NULL;
   2235 	conn->session_resumed = 0;
   2236 
   2237 	return 0;
   2238 }
   2239 
   2240 
   2241 /**
   2242  * tlsv1_client_resumed - Was session resumption used
   2243  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2244  * Returns: 1 if current session used session resumption, 0 if not
   2245  */
   2246 int tlsv1_client_resumed(struct tlsv1_client *conn)
   2247 {
   2248 	return !!conn->session_resumed;
   2249 }
   2250 
   2251 
   2252 /**
   2253  * tlsv1_client_hello_ext - Set TLS extension for ClientHello
   2254  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2255  * @ext_type: Extension type
   2256  * @data: Extension payload (%NULL to remove extension)
   2257  * @data_len: Extension payload length
   2258  * Returns: 0 on success, -1 on failure
   2259  */
   2260 int tlsv1_client_hello_ext(struct tlsv1_client *conn, int ext_type,
   2261 			   const u8 *data, size_t data_len)
   2262 {
   2263 	u8 *pos;
   2264 
   2265 	conn->ticket = 0;
   2266 	os_free(conn->client_hello_ext);
   2267 	conn->client_hello_ext = NULL;
   2268 	conn->client_hello_ext_len = 0;
   2269 
   2270 	if (data == NULL || data_len == 0)
   2271 		return 0;
   2272 
   2273 	pos = conn->client_hello_ext = os_malloc(6 + data_len);
   2274 	if (pos == NULL)
   2275 		return -1;
   2276 
   2277 	WPA_PUT_BE16(pos, 4 + data_len);
   2278 	pos += 2;
   2279 	WPA_PUT_BE16(pos, ext_type);
   2280 	pos += 2;
   2281 	WPA_PUT_BE16(pos, data_len);
   2282 	pos += 2;
   2283 	os_memcpy(pos, data, data_len);
   2284 	conn->client_hello_ext_len = 6 + data_len;
   2285 
   2286 	if (ext_type == TLS_EXT_PAC_OPAQUE) {
   2287 		conn->ticket = 1;
   2288 		wpa_printf(MSG_DEBUG, "TLSv1: Using session ticket");
   2289 	}
   2290 
   2291 	return 0;
   2292 }
   2293 
   2294 
   2295 /**
   2296  * tlsv1_client_get_keys - Get master key and random data from TLS connection
   2297  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2298  * @keys: Structure of key/random data (filled on success)
   2299  * Returns: 0 on success, -1 on failure
   2300  */
   2301 int tlsv1_client_get_keys(struct tlsv1_client *conn, struct tls_keys *keys)
   2302 {
   2303 	os_memset(keys, 0, sizeof(*keys));
   2304 	if (conn->state == CLIENT_HELLO)
   2305 		return -1;
   2306 
   2307 	keys->client_random = conn->client_random;
   2308 	keys->client_random_len = TLS_RANDOM_LEN;
   2309 
   2310 	if (conn->state != SERVER_HELLO) {
   2311 		keys->server_random = conn->server_random;
   2312 		keys->server_random_len = TLS_RANDOM_LEN;
   2313 		keys->master_key = conn->master_secret;
   2314 		keys->master_key_len = TLS_MASTER_SECRET_LEN;
   2315 	}
   2316 
   2317 	return 0;
   2318 }
   2319 
   2320 
   2321 /**
   2322  * tlsv1_client_set_master_key - Configure master secret for TLS connection
   2323  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2324  * @key: TLS pre-master-secret
   2325  * @key_len: length of key in bytes
   2326  * Returns: 0 on success, -1 on failure
   2327  */
   2328 int tlsv1_client_set_master_key(struct tlsv1_client *conn,
   2329 				const u8 *key, size_t key_len)
   2330 {
   2331 	if (key_len > TLS_MASTER_SECRET_LEN)
   2332 		return -1;
   2333 	wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: master_secret from session "
   2334 			"ticket", key, key_len);
   2335 	os_memcpy(conn->master_secret, key, key_len);
   2336 	conn->ticket_key = 1;
   2337 
   2338 	return 0;
   2339 }
   2340 
   2341 
   2342 /**
   2343  * tlsv1_client_get_keyblock_size - Get TLS key_block size
   2344  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2345  * Returns: Size of the key_block for the negotiated cipher suite or -1 on
   2346  * failure
   2347  */
   2348 int tlsv1_client_get_keyblock_size(struct tlsv1_client *conn)
   2349 {
   2350 	if (conn->state == CLIENT_HELLO || conn->state == SERVER_HELLO)
   2351 		return -1;
   2352 
   2353 	return 2 * (conn->rl.hash_size + conn->rl.key_material_len +
   2354 		    conn->rl.iv_size);
   2355 }
   2356 
   2357 
   2358 /**
   2359  * tlsv1_client_set_cipher_list - Configure acceptable cipher suites
   2360  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2361  * @ciphers: Zero (TLS_CIPHER_NONE) terminated list of allowed ciphers
   2362  * (TLS_CIPHER_*).
   2363  * Returns: 0 on success, -1 on failure
   2364  */
   2365 int tlsv1_client_set_cipher_list(struct tlsv1_client *conn, u8 *ciphers)
   2366 {
   2367 #ifdef EAP_FAST
   2368 	size_t count;
   2369 	u16 *suites;
   2370 
   2371 	/* TODO: implement proper configuration of cipher suites */
   2372 	if (ciphers[0] == TLS_CIPHER_ANON_DH_AES128_SHA) {
   2373 		count = 0;
   2374 		suites = conn->cipher_suites;
   2375 		suites[count++] = TLS_DH_anon_WITH_AES_256_CBC_SHA;
   2376 		suites[count++] = TLS_DH_anon_WITH_AES_128_CBC_SHA;
   2377 		suites[count++] = TLS_DH_anon_WITH_3DES_EDE_CBC_SHA;
   2378 		suites[count++] = TLS_DH_anon_WITH_RC4_128_MD5;
   2379 		suites[count++] = TLS_DH_anon_WITH_DES_CBC_SHA;
   2380 		conn->num_cipher_suites = count;
   2381 	}
   2382 
   2383 	return 0;
   2384 #else /* EAP_FAST */
   2385 	return -1;
   2386 #endif /* EAP_FAST */
   2387 }
   2388 
   2389 
   2390 static int tlsv1_client_add_cert_der(struct x509_certificate **chain,
   2391 				     const u8 *buf, size_t len)
   2392 {
   2393 	struct x509_certificate *cert;
   2394 	char name[128];
   2395 
   2396 	cert = x509_certificate_parse(buf, len);
   2397 	if (cert == NULL) {
   2398 		wpa_printf(MSG_INFO, "TLSv1: %s - failed to parse certificate",
   2399 			   __func__);
   2400 		return -1;
   2401 	}
   2402 
   2403 	cert->next = *chain;
   2404 	*chain = cert;
   2405 
   2406 	x509_name_string(&cert->subject, name, sizeof(name));
   2407 	wpa_printf(MSG_DEBUG, "TLSv1: Added certificate: %s", name);
   2408 
   2409 	return 0;
   2410 }
   2411 
   2412 
   2413 static const char *pem_cert_begin = "-----BEGIN CERTIFICATE-----";
   2414 static const char *pem_cert_end = "-----END CERTIFICATE-----";
   2415 
   2416 
   2417 static const u8 * search_tag(const char *tag, const u8 *buf, size_t len)
   2418 {
   2419 	size_t i, plen;
   2420 
   2421 	plen = os_strlen(tag);
   2422 	if (len < plen)
   2423 		return NULL;
   2424 
   2425 	for (i = 0; i < len - plen; i++) {
   2426 		if (os_memcmp(buf + i, tag, plen) == 0)
   2427 			return buf + i;
   2428 	}
   2429 
   2430 	return NULL;
   2431 }
   2432 
   2433 
   2434 static int tlsv1_client_add_cert(struct x509_certificate **chain,
   2435 				 const u8 *buf, size_t len)
   2436 {
   2437 	const u8 *pos, *end;
   2438 	unsigned char *der;
   2439 	size_t der_len;
   2440 
   2441 	pos = search_tag(pem_cert_begin, buf, len);
   2442 	if (!pos) {
   2443 		wpa_printf(MSG_DEBUG, "TLSv1: No PEM certificate tag found - "
   2444 			   "assume DER format");
   2445 		return tlsv1_client_add_cert_der(chain, buf, len);
   2446 	}
   2447 
   2448 	wpa_printf(MSG_DEBUG, "TLSv1: Converting PEM format certificate into "
   2449 		   "DER format");
   2450 
   2451 	while (pos) {
   2452 		pos += os_strlen(pem_cert_begin);
   2453 		end = search_tag(pem_cert_end, pos, buf + len - pos);
   2454 		if (end == NULL) {
   2455 			wpa_printf(MSG_INFO, "TLSv1: Could not find PEM "
   2456 				   "certificate end tag (%s)", pem_cert_end);
   2457 			return -1;
   2458 		}
   2459 
   2460 		der = base64_decode(pos, end - pos, &der_len);
   2461 		if (der == NULL) {
   2462 			wpa_printf(MSG_INFO, "TLSv1: Could not decode PEM "
   2463 				   "certificate");
   2464 			return -1;
   2465 		}
   2466 
   2467 		if (tlsv1_client_add_cert_der(chain, der, der_len) < 0) {
   2468 			wpa_printf(MSG_INFO, "TLSv1: Failed to parse PEM "
   2469 				   "certificate after DER conversion");
   2470 			os_free(der);
   2471 			return -1;
   2472 		}
   2473 
   2474 		os_free(der);
   2475 
   2476 		end += os_strlen(pem_cert_end);
   2477 		pos = search_tag(pem_cert_begin, end, buf + len - end);
   2478 	}
   2479 
   2480 	return 0;
   2481 }
   2482 
   2483 
   2484 static int tlsv1_client_set_cert_chain(struct x509_certificate **chain,
   2485 				       const char *cert, const u8 *cert_blob,
   2486 				       size_t cert_blob_len)
   2487 {
   2488 	if (cert_blob)
   2489 		return tlsv1_client_add_cert(chain, cert_blob, cert_blob_len);
   2490 
   2491 	if (cert) {
   2492 		u8 *buf;
   2493 		size_t len;
   2494 		int ret;
   2495 
   2496 		buf = (u8 *) os_readfile(cert, &len);
   2497 		if (buf == NULL) {
   2498 			wpa_printf(MSG_INFO, "TLSv1: Failed to read '%s'",
   2499 				   cert);
   2500 			return -1;
   2501 		}
   2502 
   2503 		ret = tlsv1_client_add_cert(chain, buf, len);
   2504 		os_free(buf);
   2505 		return ret;
   2506 	}
   2507 
   2508 	return 0;
   2509 }
   2510 
   2511 
   2512 /**
   2513  * tlsv1_client_set_ca_cert - Set trusted CA certificate(s)
   2514  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2515  * @cert: File or reference name for X.509 certificate in PEM or DER format
   2516  * @cert_blob: cert as inlined data or %NULL if not used
   2517  * @cert_blob_len: ca_cert_blob length
   2518  * @path: Path to CA certificates (not yet supported)
   2519  * Returns: 0 on success, -1 on failure
   2520  */
   2521 int tlsv1_client_set_ca_cert(struct tlsv1_client *conn, const char *cert,
   2522 			     const u8 *cert_blob, size_t cert_blob_len,
   2523 			     const char *path)
   2524 {
   2525 	if (tlsv1_client_set_cert_chain(&conn->trusted_certs, cert,
   2526 					cert_blob, cert_blob_len) < 0)
   2527 		return -1;
   2528 
   2529 	if (path) {
   2530 		/* TODO: add support for reading number of certificate files */
   2531 		wpa_printf(MSG_INFO, "TLSv1: Use of CA certificate directory "
   2532 			   "not yet supported");
   2533 		return -1;
   2534 	}
   2535 
   2536 	return 0;
   2537 }
   2538 
   2539 
   2540 /**
   2541  * tlsv1_client_set_client_cert - Set client certificate
   2542  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2543  * @cert: File or reference name for X.509 certificate in PEM or DER format
   2544  * @cert_blob: cert as inlined data or %NULL if not used
   2545  * @cert_blob_len: ca_cert_blob length
   2546  * Returns: 0 on success, -1 on failure
   2547  */
   2548 int tlsv1_client_set_client_cert(struct tlsv1_client *conn, const char *cert,
   2549 				 const u8 *cert_blob, size_t cert_blob_len)
   2550 {
   2551 	return tlsv1_client_set_cert_chain(&conn->client_cert, cert,
   2552 					   cert_blob, cert_blob_len);
   2553 }
   2554 
   2555 
   2556 static int tlsv1_client_set_key(struct tlsv1_client *conn,
   2557 				const u8 *key, size_t len)
   2558 {
   2559 	conn->client_key = crypto_private_key_import(key, len);
   2560 	if (conn->client_key == NULL) {
   2561 		wpa_printf(MSG_INFO, "TLSv1: Failed to parse private key");
   2562 		return -1;
   2563 	}
   2564 	return 0;
   2565 }
   2566 
   2567 
   2568 /**
   2569  * tlsv1_client_set_private_key - Set client private key
   2570  * @conn: TLSv1 client connection data from tlsv1_client_init()
   2571  * @private_key: File or reference name for the key in PEM or DER format
   2572  * @private_key_passwd: Passphrase for decrypted private key, %NULL if no
   2573  * passphrase is used.
   2574  * @private_key_blob: private_key as inlined data or %NULL if not used
   2575  * @private_key_blob_len: private_key_blob length
   2576  * Returns: 0 on success, -1 on failure
   2577  */
   2578 int tlsv1_client_set_private_key(struct tlsv1_client *conn,
   2579 				 const char *private_key,
   2580 				 const char *private_key_passwd,
   2581 				 const u8 *private_key_blob,
   2582 				 size_t private_key_blob_len)
   2583 {
   2584 	crypto_private_key_free(conn->client_key);
   2585 	conn->client_key = NULL;
   2586 
   2587 	if (private_key_blob)
   2588 		return tlsv1_client_set_key(conn, private_key_blob,
   2589 					    private_key_blob_len);
   2590 
   2591 	if (private_key) {
   2592 		u8 *buf;
   2593 		size_t len;
   2594 		int ret;
   2595 
   2596 		buf = (u8 *) os_readfile(private_key, &len);
   2597 		if (buf == NULL) {
   2598 			wpa_printf(MSG_INFO, "TLSv1: Failed to read '%s'",
   2599 				   private_key);
   2600 			return -1;
   2601 		}
   2602 
   2603 		ret = tlsv1_client_set_key(conn, buf, len);
   2604 		os_free(buf);
   2605 		return ret;
   2606 	}
   2607 
   2608 	return 0;
   2609 }
   2610