1 /*
2  * Wrapper functions for OpenSSL libcrypto
3  * Copyright (c) 2004-2017, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 #include <openssl/opensslv.h>
11 #include <openssl/err.h>
12 #include <openssl/des.h>
13 #include <openssl/aes.h>
14 #include <openssl/bn.h>
15 #include <openssl/evp.h>
16 #include <openssl/dh.h>
17 #include <openssl/hmac.h>
18 #include <openssl/rand.h>
19 #ifdef CONFIG_OPENSSL_CMAC
20 #include <openssl/cmac.h>
21 #endif /* CONFIG_OPENSSL_CMAC */
22 #ifdef CONFIG_ECC
23 #include <openssl/ec.h>
24 #include <openssl/x509.h>
25 #include <openssl/pem.h>
26 #endif /* CONFIG_ECC */
27 
28 #include "common.h"
29 #include "utils/const_time.h"
30 #include "wpabuf.h"
31 #include "dh_group5.h"
32 #include "sha1.h"
33 #include "sha256.h"
34 #include "sha384.h"
35 #include "sha512.h"
36 #include "md5.h"
37 #include "aes_wrap.h"
38 #include "crypto.h"
39 
40 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
41 	(defined(LIBRESSL_VERSION_NUMBER) && \
42 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
43 /* Compatibility wrappers for older versions. */
44 
45 static HMAC_CTX * HMAC_CTX_new(void)
46 {
47 	HMAC_CTX *ctx;
48 
49 	ctx = os_zalloc(sizeof(*ctx));
50 	if (ctx)
51 		HMAC_CTX_init(ctx);
52 	return ctx;
53 }
54 
55 
56 static void HMAC_CTX_free(HMAC_CTX *ctx)
57 {
58 	if (!ctx)
59 		return;
60 	HMAC_CTX_cleanup(ctx);
61 	bin_clear_free(ctx, sizeof(*ctx));
62 }
63 
64 
65 static EVP_MD_CTX * EVP_MD_CTX_new(void)
66 {
67 	EVP_MD_CTX *ctx;
68 
69 	ctx = os_zalloc(sizeof(*ctx));
70 	if (ctx)
71 		EVP_MD_CTX_init(ctx);
72 	return ctx;
73 }
74 
75 
76 static void EVP_MD_CTX_free(EVP_MD_CTX *ctx)
77 {
78 	if (!ctx)
79 		return;
80 	EVP_MD_CTX_cleanup(ctx);
81 	bin_clear_free(ctx, sizeof(*ctx));
82 }
83 
84 
85 #ifdef CONFIG_ECC
86 
87 static EC_KEY * EVP_PKEY_get0_EC_KEY(EVP_PKEY *pkey)
88 {
89 	if (pkey->type != EVP_PKEY_EC)
90 		return NULL;
91 	return pkey->pkey.ec;
92 }
93 
94 
95 static int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s)
96 {
97 	sig->r = r;
98 	sig->s = s;
99 	return 1;
100 }
101 
102 
103 static void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr,
104 			   const BIGNUM **ps)
105 {
106 	if (pr)
107 		*pr = sig->r;
108 	if (ps)
109 		*ps = sig->s;
110 }
111 
112 #endif /* CONFIG_ECC */
113 
114 static const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
115 {
116 	return ASN1_STRING_data((ASN1_STRING *) x);
117 }
118 #endif /* OpenSSL version < 1.1.0 */
119 
120 static BIGNUM * get_group5_prime(void)
121 {
122 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
123 	!(defined(LIBRESSL_VERSION_NUMBER) && \
124 	  LIBRESSL_VERSION_NUMBER < 0x20700000L)
125 	return BN_get_rfc3526_prime_1536(NULL);
126 #elif !defined(OPENSSL_IS_BORINGSSL)
127 	return get_rfc3526_prime_1536(NULL);
128 #else
129 	static const unsigned char RFC3526_PRIME_1536[] = {
130 		0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xC9,0x0F,0xDA,0xA2,
131 		0x21,0x68,0xC2,0x34,0xC4,0xC6,0x62,0x8B,0x80,0xDC,0x1C,0xD1,
132 		0x29,0x02,0x4E,0x08,0x8A,0x67,0xCC,0x74,0x02,0x0B,0xBE,0xA6,
133 		0x3B,0x13,0x9B,0x22,0x51,0x4A,0x08,0x79,0x8E,0x34,0x04,0xDD,
134 		0xEF,0x95,0x19,0xB3,0xCD,0x3A,0x43,0x1B,0x30,0x2B,0x0A,0x6D,
135 		0xF2,0x5F,0x14,0x37,0x4F,0xE1,0x35,0x6D,0x6D,0x51,0xC2,0x45,
136 		0xE4,0x85,0xB5,0x76,0x62,0x5E,0x7E,0xC6,0xF4,0x4C,0x42,0xE9,
137 		0xA6,0x37,0xED,0x6B,0x0B,0xFF,0x5C,0xB6,0xF4,0x06,0xB7,0xED,
138 		0xEE,0x38,0x6B,0xFB,0x5A,0x89,0x9F,0xA5,0xAE,0x9F,0x24,0x11,
139 		0x7C,0x4B,0x1F,0xE6,0x49,0x28,0x66,0x51,0xEC,0xE4,0x5B,0x3D,
140 		0xC2,0x00,0x7C,0xB8,0xA1,0x63,0xBF,0x05,0x98,0xDA,0x48,0x36,
141 		0x1C,0x55,0xD3,0x9A,0x69,0x16,0x3F,0xA8,0xFD,0x24,0xCF,0x5F,
142 		0x83,0x65,0x5D,0x23,0xDC,0xA3,0xAD,0x96,0x1C,0x62,0xF3,0x56,
143 		0x20,0x85,0x52,0xBB,0x9E,0xD5,0x29,0x07,0x70,0x96,0x96,0x6D,
144 		0x67,0x0C,0x35,0x4E,0x4A,0xBC,0x98,0x04,0xF1,0x74,0x6C,0x08,
145 		0xCA,0x23,0x73,0x27,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
146 	};
147         return BN_bin2bn(RFC3526_PRIME_1536, sizeof(RFC3526_PRIME_1536), NULL);
148 #endif
149 }
150 
151 
152 static BIGNUM * get_group5_order(void)
153 {
154 	static const unsigned char RFC3526_ORDER_1536[] = {
155 		0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xE4,0x87,0xED,0x51,
156 		0x10,0xB4,0x61,0x1A,0x62,0x63,0x31,0x45,0xC0,0x6E,0x0E,0x68,
157 		0x94,0x81,0x27,0x04,0x45,0x33,0xE6,0x3A,0x01,0x05,0xDF,0x53,
158 		0x1D,0x89,0xCD,0x91,0x28,0xA5,0x04,0x3C,0xC7,0x1A,0x02,0x6E,
159 		0xF7,0xCA,0x8C,0xD9,0xE6,0x9D,0x21,0x8D,0x98,0x15,0x85,0x36,
160 		0xF9,0x2F,0x8A,0x1B,0xA7,0xF0,0x9A,0xB6,0xB6,0xA8,0xE1,0x22,
161 		0xF2,0x42,0xDA,0xBB,0x31,0x2F,0x3F,0x63,0x7A,0x26,0x21,0x74,
162 		0xD3,0x1B,0xF6,0xB5,0x85,0xFF,0xAE,0x5B,0x7A,0x03,0x5B,0xF6,
163 		0xF7,0x1C,0x35,0xFD,0xAD,0x44,0xCF,0xD2,0xD7,0x4F,0x92,0x08,
164 		0xBE,0x25,0x8F,0xF3,0x24,0x94,0x33,0x28,0xF6,0x72,0x2D,0x9E,
165 		0xE1,0x00,0x3E,0x5C,0x50,0xB1,0xDF,0x82,0xCC,0x6D,0x24,0x1B,
166 		0x0E,0x2A,0xE9,0xCD,0x34,0x8B,0x1F,0xD4,0x7E,0x92,0x67,0xAF,
167 		0xC1,0xB2,0xAE,0x91,0xEE,0x51,0xD6,0xCB,0x0E,0x31,0x79,0xAB,
168 		0x10,0x42,0xA9,0x5D,0xCF,0x6A,0x94,0x83,0xB8,0x4B,0x4B,0x36,
169 		0xB3,0x86,0x1A,0xA7,0x25,0x5E,0x4C,0x02,0x78,0xBA,0x36,0x04,
170 		0x65,0x11,0xB9,0x93,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
171 	};
172 	return BN_bin2bn(RFC3526_ORDER_1536, sizeof(RFC3526_ORDER_1536), NULL);
173 }
174 
175 
176 #ifdef OPENSSL_NO_SHA256
177 #define NO_SHA256_WRAPPER
178 #endif
179 #ifdef OPENSSL_NO_SHA512
180 #define NO_SHA384_WRAPPER
181 #endif
182 
183 static int openssl_digest_vector(const EVP_MD *type, size_t num_elem,
184 				 const u8 *addr[], const size_t *len, u8 *mac)
185 {
186 	EVP_MD_CTX *ctx;
187 	size_t i;
188 	unsigned int mac_len;
189 
190 	if (TEST_FAIL())
191 		return -1;
192 
193 	ctx = EVP_MD_CTX_new();
194 	if (!ctx)
195 		return -1;
196 	if (!EVP_DigestInit_ex(ctx, type, NULL)) {
197 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DigestInit_ex failed: %s",
198 			   ERR_error_string(ERR_get_error(), NULL));
199 		EVP_MD_CTX_free(ctx);
200 		return -1;
201 	}
202 	for (i = 0; i < num_elem; i++) {
203 		if (!EVP_DigestUpdate(ctx, addr[i], len[i])) {
204 			wpa_printf(MSG_ERROR, "OpenSSL: EVP_DigestUpdate "
205 				   "failed: %s",
206 				   ERR_error_string(ERR_get_error(), NULL));
207 			EVP_MD_CTX_free(ctx);
208 			return -1;
209 		}
210 	}
211 	if (!EVP_DigestFinal(ctx, mac, &mac_len)) {
212 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DigestFinal failed: %s",
213 			   ERR_error_string(ERR_get_error(), NULL));
214 		EVP_MD_CTX_free(ctx);
215 		return -1;
216 	}
217 	EVP_MD_CTX_free(ctx);
218 
219 	return 0;
220 }
221 
222 
223 #ifndef CONFIG_FIPS
224 int md4_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
225 {
226 	return openssl_digest_vector(EVP_md4(), num_elem, addr, len, mac);
227 }
228 #endif /* CONFIG_FIPS */
229 
230 
231 int des_encrypt(const u8 *clear, const u8 *key, u8 *cypher)
232 {
233 	u8 pkey[8], next, tmp;
234 	int i, plen, ret = -1;
235 	EVP_CIPHER_CTX *ctx;
236 
237 	/* Add parity bits to the key */
238 	next = 0;
239 	for (i = 0; i < 7; i++) {
240 		tmp = key[i];
241 		pkey[i] = (tmp >> i) | next | 1;
242 		next = tmp << (7 - i);
243 	}
244 	pkey[i] = next | 1;
245 
246 	ctx = EVP_CIPHER_CTX_new();
247 	if (ctx &&
248 	    EVP_EncryptInit_ex(ctx, EVP_des_ecb(), NULL, pkey, NULL) == 1 &&
249 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
250 	    EVP_EncryptUpdate(ctx, cypher, &plen, clear, 8) == 1 &&
251 	    EVP_EncryptFinal_ex(ctx, &cypher[plen], &plen) == 1)
252 		ret = 0;
253 	else
254 		wpa_printf(MSG_ERROR, "OpenSSL: DES encrypt failed");
255 
256 	if (ctx)
257 		EVP_CIPHER_CTX_free(ctx);
258 	return ret;
259 }
260 
261 
262 #ifndef CONFIG_NO_RC4
263 int rc4_skip(const u8 *key, size_t keylen, size_t skip,
264 	     u8 *data, size_t data_len)
265 {
266 #ifdef OPENSSL_NO_RC4
267 	return -1;
268 #else /* OPENSSL_NO_RC4 */
269 	EVP_CIPHER_CTX *ctx;
270 	int outl;
271 	int res = -1;
272 	unsigned char skip_buf[16];
273 
274 	ctx = EVP_CIPHER_CTX_new();
275 	if (!ctx ||
276 	    !EVP_CipherInit_ex(ctx, EVP_rc4(), NULL, NULL, NULL, 1) ||
277 	    !EVP_CIPHER_CTX_set_padding(ctx, 0) ||
278 	    !EVP_CIPHER_CTX_set_key_length(ctx, keylen) ||
279 	    !EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, 1))
280 		goto out;
281 
282 	while (skip >= sizeof(skip_buf)) {
283 		size_t len = skip;
284 		if (len > sizeof(skip_buf))
285 			len = sizeof(skip_buf);
286 		if (!EVP_CipherUpdate(ctx, skip_buf, &outl, skip_buf, len))
287 			goto out;
288 		skip -= len;
289 	}
290 
291 	if (EVP_CipherUpdate(ctx, data, &outl, data, data_len))
292 		res = 0;
293 
294 out:
295 	if (ctx)
296 		EVP_CIPHER_CTX_free(ctx);
297 	return res;
298 #endif /* OPENSSL_NO_RC4 */
299 }
300 #endif /* CONFIG_NO_RC4 */
301 
302 
303 #ifndef CONFIG_FIPS
304 int md5_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
305 {
306 	return openssl_digest_vector(EVP_md5(), num_elem, addr, len, mac);
307 }
308 #endif /* CONFIG_FIPS */
309 
310 
311 int sha1_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
312 {
313 	return openssl_digest_vector(EVP_sha1(), num_elem, addr, len, mac);
314 }
315 
316 
317 #ifndef NO_SHA256_WRAPPER
318 int sha256_vector(size_t num_elem, const u8 *addr[], const size_t *len,
319 		  u8 *mac)
320 {
321 	return openssl_digest_vector(EVP_sha256(), num_elem, addr, len, mac);
322 }
323 #endif /* NO_SHA256_WRAPPER */
324 
325 
326 #ifndef NO_SHA384_WRAPPER
327 int sha384_vector(size_t num_elem, const u8 *addr[], const size_t *len,
328 		  u8 *mac)
329 {
330 	return openssl_digest_vector(EVP_sha384(), num_elem, addr, len, mac);
331 }
332 #endif /* NO_SHA384_WRAPPER */
333 
334 
335 #ifndef NO_SHA512_WRAPPER
336 int sha512_vector(size_t num_elem, const u8 *addr[], const size_t *len,
337 		  u8 *mac)
338 {
339 	return openssl_digest_vector(EVP_sha512(), num_elem, addr, len, mac);
340 }
341 #endif /* NO_SHA512_WRAPPER */
342 
343 
344 static const EVP_CIPHER * aes_get_evp_cipher(size_t keylen)
345 {
346 	switch (keylen) {
347 	case 16:
348 		return EVP_aes_128_ecb();
349 	case 24:
350 		return EVP_aes_192_ecb();
351 	case 32:
352 		return EVP_aes_256_ecb();
353 	}
354 
355 	return NULL;
356 }
357 
358 
359 void * aes_encrypt_init(const u8 *key, size_t len)
360 {
361 	EVP_CIPHER_CTX *ctx;
362 	const EVP_CIPHER *type;
363 
364 	if (TEST_FAIL())
365 		return NULL;
366 
367 	type = aes_get_evp_cipher(len);
368 	if (!type) {
369 		wpa_printf(MSG_INFO, "%s: Unsupported len=%u",
370 			   __func__, (unsigned int) len);
371 		return NULL;
372 	}
373 
374 	ctx = EVP_CIPHER_CTX_new();
375 	if (ctx == NULL)
376 		return NULL;
377 	if (EVP_EncryptInit_ex(ctx, type, NULL, key, NULL) != 1) {
378 		os_free(ctx);
379 		return NULL;
380 	}
381 	EVP_CIPHER_CTX_set_padding(ctx, 0);
382 	return ctx;
383 }
384 
385 
386 int aes_encrypt(void *ctx, const u8 *plain, u8 *crypt)
387 {
388 	EVP_CIPHER_CTX *c = ctx;
389 	int clen = 16;
390 	if (EVP_EncryptUpdate(c, crypt, &clen, plain, 16) != 1) {
391 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_EncryptUpdate failed: %s",
392 			   ERR_error_string(ERR_get_error(), NULL));
393 		return -1;
394 	}
395 	return 0;
396 }
397 
398 
399 void aes_encrypt_deinit(void *ctx)
400 {
401 	EVP_CIPHER_CTX *c = ctx;
402 	u8 buf[16];
403 	int len = sizeof(buf);
404 	if (EVP_EncryptFinal_ex(c, buf, &len) != 1) {
405 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_EncryptFinal_ex failed: "
406 			   "%s", ERR_error_string(ERR_get_error(), NULL));
407 	}
408 	if (len != 0) {
409 		wpa_printf(MSG_ERROR, "OpenSSL: Unexpected padding length %d "
410 			   "in AES encrypt", len);
411 	}
412 	EVP_CIPHER_CTX_free(c);
413 }
414 
415 
416 void * aes_decrypt_init(const u8 *key, size_t len)
417 {
418 	EVP_CIPHER_CTX *ctx;
419 	const EVP_CIPHER *type;
420 
421 	if (TEST_FAIL())
422 		return NULL;
423 
424 	type = aes_get_evp_cipher(len);
425 	if (!type) {
426 		wpa_printf(MSG_INFO, "%s: Unsupported len=%u",
427 			   __func__, (unsigned int) len);
428 		return NULL;
429 	}
430 
431 	ctx = EVP_CIPHER_CTX_new();
432 	if (ctx == NULL)
433 		return NULL;
434 	if (EVP_DecryptInit_ex(ctx, type, NULL, key, NULL) != 1) {
435 		EVP_CIPHER_CTX_free(ctx);
436 		return NULL;
437 	}
438 	EVP_CIPHER_CTX_set_padding(ctx, 0);
439 	return ctx;
440 }
441 
442 
443 int aes_decrypt(void *ctx, const u8 *crypt, u8 *plain)
444 {
445 	EVP_CIPHER_CTX *c = ctx;
446 	int plen = 16;
447 	if (EVP_DecryptUpdate(c, plain, &plen, crypt, 16) != 1) {
448 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DecryptUpdate failed: %s",
449 			   ERR_error_string(ERR_get_error(), NULL));
450 		return -1;
451 	}
452 	return 0;
453 }
454 
455 
456 void aes_decrypt_deinit(void *ctx)
457 {
458 	EVP_CIPHER_CTX *c = ctx;
459 	u8 buf[16];
460 	int len = sizeof(buf);
461 	if (EVP_DecryptFinal_ex(c, buf, &len) != 1) {
462 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DecryptFinal_ex failed: "
463 			   "%s", ERR_error_string(ERR_get_error(), NULL));
464 	}
465 	if (len != 0) {
466 		wpa_printf(MSG_ERROR, "OpenSSL: Unexpected padding length %d "
467 			   "in AES decrypt", len);
468 	}
469 	EVP_CIPHER_CTX_free(c);
470 }
471 
472 
473 #ifndef CONFIG_FIPS
474 #ifndef CONFIG_OPENSSL_INTERNAL_AES_WRAP
475 
476 int aes_wrap(const u8 *kek, size_t kek_len, int n, const u8 *plain, u8 *cipher)
477 {
478 	AES_KEY actx;
479 	int res;
480 
481 	if (TEST_FAIL())
482 		return -1;
483 	if (AES_set_encrypt_key(kek, kek_len << 3, &actx))
484 		return -1;
485 	res = AES_wrap_key(&actx, NULL, cipher, plain, n * 8);
486 	OPENSSL_cleanse(&actx, sizeof(actx));
487 	return res <= 0 ? -1 : 0;
488 }
489 
490 
491 int aes_unwrap(const u8 *kek, size_t kek_len, int n, const u8 *cipher,
492 	       u8 *plain)
493 {
494 	AES_KEY actx;
495 	int res;
496 
497 	if (TEST_FAIL())
498 		return -1;
499 	if (AES_set_decrypt_key(kek, kek_len << 3, &actx))
500 		return -1;
501 	res = AES_unwrap_key(&actx, NULL, plain, cipher, (n + 1) * 8);
502 	OPENSSL_cleanse(&actx, sizeof(actx));
503 	return res <= 0 ? -1 : 0;
504 }
505 
506 #endif /* CONFIG_OPENSSL_INTERNAL_AES_WRAP */
507 #endif /* CONFIG_FIPS */
508 
509 
510 int aes_128_cbc_encrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
511 {
512 	EVP_CIPHER_CTX *ctx;
513 	int clen, len;
514 	u8 buf[16];
515 	int res = -1;
516 
517 	if (TEST_FAIL())
518 		return -1;
519 
520 	ctx = EVP_CIPHER_CTX_new();
521 	if (!ctx)
522 		return -1;
523 	clen = data_len;
524 	len = sizeof(buf);
525 	if (EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv) == 1 &&
526 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
527 	    EVP_EncryptUpdate(ctx, data, &clen, data, data_len) == 1 &&
528 	    clen == (int) data_len &&
529 	    EVP_EncryptFinal_ex(ctx, buf, &len) == 1 && len == 0)
530 		res = 0;
531 	EVP_CIPHER_CTX_free(ctx);
532 
533 	return res;
534 }
535 
536 
537 int aes_128_cbc_decrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
538 {
539 	EVP_CIPHER_CTX *ctx;
540 	int plen, len;
541 	u8 buf[16];
542 	int res = -1;
543 
544 	if (TEST_FAIL())
545 		return -1;
546 
547 	ctx = EVP_CIPHER_CTX_new();
548 	if (!ctx)
549 		return -1;
550 	plen = data_len;
551 	len = sizeof(buf);
552 	if (EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv) == 1 &&
553 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
554 	    EVP_DecryptUpdate(ctx, data, &plen, data, data_len) == 1 &&
555 	    plen == (int) data_len &&
556 	    EVP_DecryptFinal_ex(ctx, buf, &len) == 1 && len == 0)
557 		res = 0;
558 	EVP_CIPHER_CTX_free(ctx);
559 
560 	return res;
561 
562 }
563 
564 
565 int crypto_dh_init(u8 generator, const u8 *prime, size_t prime_len, u8 *privkey,
566 		   u8 *pubkey)
567 {
568 	size_t pubkey_len, pad;
569 
570 	if (os_get_random(privkey, prime_len) < 0)
571 		return -1;
572 	if (os_memcmp(privkey, prime, prime_len) > 0) {
573 		/* Make sure private value is smaller than prime */
574 		privkey[0] = 0;
575 	}
576 
577 	pubkey_len = prime_len;
578 	if (crypto_mod_exp(&generator, 1, privkey, prime_len, prime, prime_len,
579 			   pubkey, &pubkey_len) < 0)
580 		return -1;
581 	if (pubkey_len < prime_len) {
582 		pad = prime_len - pubkey_len;
583 		os_memmove(pubkey + pad, pubkey, pubkey_len);
584 		os_memset(pubkey, 0, pad);
585 	}
586 
587 	return 0;
588 }
589 
590 
591 int crypto_dh_derive_secret(u8 generator, const u8 *prime, size_t prime_len,
592 			    const u8 *order, size_t order_len,
593 			    const u8 *privkey, size_t privkey_len,
594 			    const u8 *pubkey, size_t pubkey_len,
595 			    u8 *secret, size_t *len)
596 {
597 	BIGNUM *pub, *p;
598 	int res = -1;
599 
600 	pub = BN_bin2bn(pubkey, pubkey_len, NULL);
601 	p = BN_bin2bn(prime, prime_len, NULL);
602 	if (!pub || !p || BN_is_zero(pub) || BN_is_one(pub) ||
603 	    BN_cmp(pub, p) >= 0)
604 		goto fail;
605 
606 	if (order) {
607 		BN_CTX *ctx;
608 		BIGNUM *q, *tmp;
609 		int failed;
610 
611 		/* verify: pubkey^q == 1 mod p */
612 		q = BN_bin2bn(order, order_len, NULL);
613 		ctx = BN_CTX_new();
614 		tmp = BN_new();
615 		failed = !q || !ctx || !tmp ||
616 			!BN_mod_exp(tmp, pub, q, p, ctx) ||
617 			!BN_is_one(tmp);
618 		BN_clear_free(q);
619 		BN_clear_free(tmp);
620 		BN_CTX_free(ctx);
621 		if (failed)
622 			goto fail;
623 	}
624 
625 	res = crypto_mod_exp(pubkey, pubkey_len, privkey, privkey_len,
626 			     prime, prime_len, secret, len);
627 fail:
628 	BN_clear_free(pub);
629 	BN_clear_free(p);
630 	return res;
631 }
632 
633 
634 int crypto_mod_exp(const u8 *base, size_t base_len,
635 		   const u8 *power, size_t power_len,
636 		   const u8 *modulus, size_t modulus_len,
637 		   u8 *result, size_t *result_len)
638 {
639 	BIGNUM *bn_base, *bn_exp, *bn_modulus, *bn_result;
640 	int ret = -1;
641 	BN_CTX *ctx;
642 
643 	ctx = BN_CTX_new();
644 	if (ctx == NULL)
645 		return -1;
646 
647 	bn_base = BN_bin2bn(base, base_len, NULL);
648 	bn_exp = BN_bin2bn(power, power_len, NULL);
649 	bn_modulus = BN_bin2bn(modulus, modulus_len, NULL);
650 	bn_result = BN_new();
651 
652 	if (bn_base == NULL || bn_exp == NULL || bn_modulus == NULL ||
653 	    bn_result == NULL)
654 		goto error;
655 
656 	if (BN_mod_exp_mont_consttime(bn_result, bn_base, bn_exp, bn_modulus,
657 				      ctx, NULL) != 1)
658 		goto error;
659 
660 	*result_len = BN_bn2bin(bn_result, result);
661 	ret = 0;
662 
663 error:
664 	BN_clear_free(bn_base);
665 	BN_clear_free(bn_exp);
666 	BN_clear_free(bn_modulus);
667 	BN_clear_free(bn_result);
668 	BN_CTX_free(ctx);
669 	return ret;
670 }
671 
672 
673 struct crypto_cipher {
674 	EVP_CIPHER_CTX *enc;
675 	EVP_CIPHER_CTX *dec;
676 };
677 
678 
679 struct crypto_cipher * crypto_cipher_init(enum crypto_cipher_alg alg,
680 					  const u8 *iv, const u8 *key,
681 					  size_t key_len)
682 {
683 	struct crypto_cipher *ctx;
684 	const EVP_CIPHER *cipher;
685 
686 	ctx = os_zalloc(sizeof(*ctx));
687 	if (ctx == NULL)
688 		return NULL;
689 
690 	switch (alg) {
691 #ifndef CONFIG_NO_RC4
692 #ifndef OPENSSL_NO_RC4
693 	case CRYPTO_CIPHER_ALG_RC4:
694 		cipher = EVP_rc4();
695 		break;
696 #endif /* OPENSSL_NO_RC4 */
697 #endif /* CONFIG_NO_RC4 */
698 #ifndef OPENSSL_NO_AES
699 	case CRYPTO_CIPHER_ALG_AES:
700 		switch (key_len) {
701 		case 16:
702 			cipher = EVP_aes_128_cbc();
703 			break;
704 #ifndef OPENSSL_IS_BORINGSSL
705 		case 24:
706 			cipher = EVP_aes_192_cbc();
707 			break;
708 #endif /* OPENSSL_IS_BORINGSSL */
709 		case 32:
710 			cipher = EVP_aes_256_cbc();
711 			break;
712 		default:
713 			os_free(ctx);
714 			return NULL;
715 		}
716 		break;
717 #endif /* OPENSSL_NO_AES */
718 #ifndef OPENSSL_NO_DES
719 	case CRYPTO_CIPHER_ALG_3DES:
720 		cipher = EVP_des_ede3_cbc();
721 		break;
722 	case CRYPTO_CIPHER_ALG_DES:
723 		cipher = EVP_des_cbc();
724 		break;
725 #endif /* OPENSSL_NO_DES */
726 #ifndef OPENSSL_NO_RC2
727 	case CRYPTO_CIPHER_ALG_RC2:
728 		cipher = EVP_rc2_ecb();
729 		break;
730 #endif /* OPENSSL_NO_RC2 */
731 	default:
732 		os_free(ctx);
733 		return NULL;
734 	}
735 
736 	if (!(ctx->enc = EVP_CIPHER_CTX_new()) ||
737 	    !EVP_EncryptInit_ex(ctx->enc, cipher, NULL, NULL, NULL) ||
738 	    !EVP_CIPHER_CTX_set_padding(ctx->enc, 0) ||
739 	    !EVP_CIPHER_CTX_set_key_length(ctx->enc, key_len) ||
740 	    !EVP_EncryptInit_ex(ctx->enc, NULL, NULL, key, iv)) {
741 		if (ctx->enc)
742 			EVP_CIPHER_CTX_free(ctx->enc);
743 		os_free(ctx);
744 		return NULL;
745 	}
746 
747 	if (!(ctx->dec = EVP_CIPHER_CTX_new()) ||
748 	    !EVP_DecryptInit_ex(ctx->dec, cipher, NULL, NULL, NULL) ||
749 	    !EVP_CIPHER_CTX_set_padding(ctx->dec, 0) ||
750 	    !EVP_CIPHER_CTX_set_key_length(ctx->dec, key_len) ||
751 	    !EVP_DecryptInit_ex(ctx->dec, NULL, NULL, key, iv)) {
752 		EVP_CIPHER_CTX_free(ctx->enc);
753 		if (ctx->dec)
754 			EVP_CIPHER_CTX_free(ctx->dec);
755 		os_free(ctx);
756 		return NULL;
757 	}
758 
759 	return ctx;
760 }
761 
762 
763 int crypto_cipher_encrypt(struct crypto_cipher *ctx, const u8 *plain,
764 			  u8 *crypt, size_t len)
765 {
766 	int outl;
767 	if (!EVP_EncryptUpdate(ctx->enc, crypt, &outl, plain, len))
768 		return -1;
769 	return 0;
770 }
771 
772 
773 int crypto_cipher_decrypt(struct crypto_cipher *ctx, const u8 *crypt,
774 			  u8 *plain, size_t len)
775 {
776 	int outl;
777 	outl = len;
778 	if (!EVP_DecryptUpdate(ctx->dec, plain, &outl, crypt, len))
779 		return -1;
780 	return 0;
781 }
782 
783 
784 void crypto_cipher_deinit(struct crypto_cipher *ctx)
785 {
786 	EVP_CIPHER_CTX_free(ctx->enc);
787 	EVP_CIPHER_CTX_free(ctx->dec);
788 	os_free(ctx);
789 }
790 
791 
792 void * dh5_init(struct wpabuf **priv, struct wpabuf **publ)
793 {
794 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
795 	(defined(LIBRESSL_VERSION_NUMBER) && \
796 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
797 	DH *dh;
798 	struct wpabuf *pubkey = NULL, *privkey = NULL;
799 	size_t publen, privlen;
800 
801 	*priv = NULL;
802 	wpabuf_free(*publ);
803 	*publ = NULL;
804 
805 	dh = DH_new();
806 	if (dh == NULL)
807 		return NULL;
808 
809 	dh->g = BN_new();
810 	if (dh->g == NULL || BN_set_word(dh->g, 2) != 1)
811 		goto err;
812 
813 	dh->p = get_group5_prime();
814 	if (dh->p == NULL)
815 		goto err;
816 
817 	dh->q = get_group5_order();
818 	if (!dh->q)
819 		goto err;
820 
821 	if (DH_generate_key(dh) != 1)
822 		goto err;
823 
824 	publen = BN_num_bytes(dh->pub_key);
825 	pubkey = wpabuf_alloc(publen);
826 	if (pubkey == NULL)
827 		goto err;
828 	privlen = BN_num_bytes(dh->priv_key);
829 	privkey = wpabuf_alloc(privlen);
830 	if (privkey == NULL)
831 		goto err;
832 
833 	BN_bn2bin(dh->pub_key, wpabuf_put(pubkey, publen));
834 	BN_bn2bin(dh->priv_key, wpabuf_put(privkey, privlen));
835 
836 	*priv = privkey;
837 	*publ = pubkey;
838 	return dh;
839 
840 err:
841 	wpabuf_clear_free(pubkey);
842 	wpabuf_clear_free(privkey);
843 	DH_free(dh);
844 	return NULL;
845 #else
846 	DH *dh;
847 	struct wpabuf *pubkey = NULL, *privkey = NULL;
848 	size_t publen, privlen;
849 	BIGNUM *p, *g, *q;
850 	const BIGNUM *priv_key = NULL, *pub_key = NULL;
851 
852 	*priv = NULL;
853 	wpabuf_free(*publ);
854 	*publ = NULL;
855 
856 	dh = DH_new();
857 	if (dh == NULL)
858 		return NULL;
859 
860 	g = BN_new();
861 	p = get_group5_prime();
862 	q = get_group5_order();
863 	if (!g || BN_set_word(g, 2) != 1 || !p || !q ||
864 	    DH_set0_pqg(dh, p, q, g) != 1)
865 		goto err;
866 	p = NULL;
867 	q = NULL;
868 	g = NULL;
869 
870 	if (DH_generate_key(dh) != 1)
871 		goto err;
872 
873 	DH_get0_key(dh, &pub_key, &priv_key);
874 	publen = BN_num_bytes(pub_key);
875 	pubkey = wpabuf_alloc(publen);
876 	if (!pubkey)
877 		goto err;
878 	privlen = BN_num_bytes(priv_key);
879 	privkey = wpabuf_alloc(privlen);
880 	if (!privkey)
881 		goto err;
882 
883 	BN_bn2bin(pub_key, wpabuf_put(pubkey, publen));
884 	BN_bn2bin(priv_key, wpabuf_put(privkey, privlen));
885 
886 	*priv = privkey;
887 	*publ = pubkey;
888 	return dh;
889 
890 err:
891 	BN_free(p);
892 	BN_free(q);
893 	BN_free(g);
894 	wpabuf_clear_free(pubkey);
895 	wpabuf_clear_free(privkey);
896 	DH_free(dh);
897 	return NULL;
898 #endif
899 }
900 
901 
902 void * dh5_init_fixed(const struct wpabuf *priv, const struct wpabuf *publ)
903 {
904 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
905 	(defined(LIBRESSL_VERSION_NUMBER) && \
906 	 LIBRESSL_VERSION_NUMBER < 0x20700000L)
907 	DH *dh;
908 
909 	dh = DH_new();
910 	if (dh == NULL)
911 		return NULL;
912 
913 	dh->g = BN_new();
914 	if (dh->g == NULL || BN_set_word(dh->g, 2) != 1)
915 		goto err;
916 
917 	dh->p = get_group5_prime();
918 	if (dh->p == NULL)
919 		goto err;
920 
921 	dh->priv_key = BN_bin2bn(wpabuf_head(priv), wpabuf_len(priv), NULL);
922 	if (dh->priv_key == NULL)
923 		goto err;
924 
925 	dh->pub_key = BN_bin2bn(wpabuf_head(publ), wpabuf_len(publ), NULL);
926 	if (dh->pub_key == NULL)
927 		goto err;
928 
929 	if (DH_generate_key(dh) != 1)
930 		goto err;
931 
932 	return dh;
933 
934 err:
935 	DH_free(dh);
936 	return NULL;
937 #else
938 	DH *dh;
939 	BIGNUM *p = NULL, *g, *priv_key = NULL, *pub_key = NULL;
940 
941 	dh = DH_new();
942 	if (dh == NULL)
943 		return NULL;
944 
945 	g = BN_new();
946 	p = get_group5_prime();
947 	if (!g || BN_set_word(g, 2) != 1 || !p ||
948 	    DH_set0_pqg(dh, p, NULL, g) != 1)
949 		goto err;
950 	p = NULL;
951 	g = NULL;
952 
953 	priv_key = BN_bin2bn(wpabuf_head(priv), wpabuf_len(priv), NULL);
954 	pub_key = BN_bin2bn(wpabuf_head(publ), wpabuf_len(publ), NULL);
955 	if (!priv_key || !pub_key || DH_set0_key(dh, pub_key, priv_key) != 1)
956 		goto err;
957 	pub_key = NULL;
958 	priv_key = NULL;
959 
960 	if (DH_generate_key(dh) != 1)
961 		goto err;
962 
963 	return dh;
964 
965 err:
966 	BN_free(p);
967 	BN_free(g);
968 	BN_free(pub_key);
969 	BN_clear_free(priv_key);
970 	DH_free(dh);
971 	return NULL;
972 #endif
973 }
974 
975 
976 struct wpabuf * dh5_derive_shared(void *ctx, const struct wpabuf *peer_public,
977 				  const struct wpabuf *own_private)
978 {
979 	BIGNUM *pub_key;
980 	struct wpabuf *res = NULL;
981 	size_t rlen;
982 	DH *dh = ctx;
983 	int keylen;
984 
985 	if (ctx == NULL)
986 		return NULL;
987 
988 	pub_key = BN_bin2bn(wpabuf_head(peer_public), wpabuf_len(peer_public),
989 			    NULL);
990 	if (pub_key == NULL)
991 		return NULL;
992 
993 	rlen = DH_size(dh);
994 	res = wpabuf_alloc(rlen);
995 	if (res == NULL)
996 		goto err;
997 
998 	keylen = DH_compute_key(wpabuf_mhead(res), pub_key, dh);
999 	if (keylen < 0)
1000 		goto err;
1001 	wpabuf_put(res, keylen);
1002 	BN_clear_free(pub_key);
1003 
1004 	return res;
1005 
1006 err:
1007 	BN_clear_free(pub_key);
1008 	wpabuf_clear_free(res);
1009 	return NULL;
1010 }
1011 
1012 
1013 void dh5_free(void *ctx)
1014 {
1015 	DH *dh;
1016 	if (ctx == NULL)
1017 		return;
1018 	dh = ctx;
1019 	DH_free(dh);
1020 }
1021 
1022 
1023 struct crypto_hash {
1024 	HMAC_CTX *ctx;
1025 };
1026 
1027 
1028 struct crypto_hash * crypto_hash_init(enum crypto_hash_alg alg, const u8 *key,
1029 				      size_t key_len)
1030 {
1031 	struct crypto_hash *ctx;
1032 	const EVP_MD *md;
1033 
1034 	switch (alg) {
1035 #ifndef OPENSSL_NO_MD5
1036 	case CRYPTO_HASH_ALG_HMAC_MD5:
1037 		md = EVP_md5();
1038 		break;
1039 #endif /* OPENSSL_NO_MD5 */
1040 #ifndef OPENSSL_NO_SHA
1041 	case CRYPTO_HASH_ALG_HMAC_SHA1:
1042 		md = EVP_sha1();
1043 		break;
1044 #endif /* OPENSSL_NO_SHA */
1045 #ifndef OPENSSL_NO_SHA256
1046 #ifdef CONFIG_SHA256
1047 	case CRYPTO_HASH_ALG_HMAC_SHA256:
1048 		md = EVP_sha256();
1049 		break;
1050 #endif /* CONFIG_SHA256 */
1051 #endif /* OPENSSL_NO_SHA256 */
1052 	default:
1053 		return NULL;
1054 	}
1055 
1056 	ctx = os_zalloc(sizeof(*ctx));
1057 	if (ctx == NULL)
1058 		return NULL;
1059 	ctx->ctx = HMAC_CTX_new();
1060 	if (!ctx->ctx) {
1061 		os_free(ctx);
1062 		return NULL;
1063 	}
1064 
1065 	if (HMAC_Init_ex(ctx->ctx, key, key_len, md, NULL) != 1) {
1066 		HMAC_CTX_free(ctx->ctx);
1067 		bin_clear_free(ctx, sizeof(*ctx));
1068 		return NULL;
1069 	}
1070 
1071 	return ctx;
1072 }
1073 
1074 
1075 void crypto_hash_update(struct crypto_hash *ctx, const u8 *data, size_t len)
1076 {
1077 	if (ctx == NULL)
1078 		return;
1079 	HMAC_Update(ctx->ctx, data, len);
1080 }
1081 
1082 
1083 int crypto_hash_finish(struct crypto_hash *ctx, u8 *mac, size_t *len)
1084 {
1085 	unsigned int mdlen;
1086 	int res;
1087 
1088 	if (ctx == NULL)
1089 		return -2;
1090 
1091 	if (mac == NULL || len == NULL) {
1092 		HMAC_CTX_free(ctx->ctx);
1093 		bin_clear_free(ctx, sizeof(*ctx));
1094 		return 0;
1095 	}
1096 
1097 	mdlen = *len;
1098 	res = HMAC_Final(ctx->ctx, mac, &mdlen);
1099 	HMAC_CTX_free(ctx->ctx);
1100 	bin_clear_free(ctx, sizeof(*ctx));
1101 
1102 	if (TEST_FAIL())
1103 		return -1;
1104 
1105 	if (res == 1) {
1106 		*len = mdlen;
1107 		return 0;
1108 	}
1109 
1110 	return -1;
1111 }
1112 
1113 
1114 static int openssl_hmac_vector(const EVP_MD *type, const u8 *key,
1115 			       size_t key_len, size_t num_elem,
1116 			       const u8 *addr[], const size_t *len, u8 *mac,
1117 			       unsigned int mdlen)
1118 {
1119 	HMAC_CTX *ctx;
1120 	size_t i;
1121 	int res;
1122 
1123 	if (TEST_FAIL())
1124 		return -1;
1125 
1126 	ctx = HMAC_CTX_new();
1127 	if (!ctx)
1128 		return -1;
1129 	res = HMAC_Init_ex(ctx, key, key_len, type, NULL);
1130 	if (res != 1)
1131 		goto done;
1132 
1133 	for (i = 0; i < num_elem; i++)
1134 		HMAC_Update(ctx, addr[i], len[i]);
1135 
1136 	res = HMAC_Final(ctx, mac, &mdlen);
1137 done:
1138 	HMAC_CTX_free(ctx);
1139 
1140 	return res == 1 ? 0 : -1;
1141 }
1142 
1143 
1144 #ifndef CONFIG_FIPS
1145 
1146 int hmac_md5_vector(const u8 *key, size_t key_len, size_t num_elem,
1147 		    const u8 *addr[], const size_t *len, u8 *mac)
1148 {
1149 	return openssl_hmac_vector(EVP_md5(), key ,key_len, num_elem, addr, len,
1150 				   mac, 16);
1151 }
1152 
1153 
1154 int hmac_md5(const u8 *key, size_t key_len, const u8 *data, size_t data_len,
1155 	     u8 *mac)
1156 {
1157 	return hmac_md5_vector(key, key_len, 1, &data, &data_len, mac);
1158 }
1159 
1160 #endif /* CONFIG_FIPS */
1161 
1162 
1163 int pbkdf2_sha1(const char *passphrase, const u8 *ssid, size_t ssid_len,
1164 		int iterations, u8 *buf, size_t buflen)
1165 {
1166 	if (PKCS5_PBKDF2_HMAC_SHA1(passphrase, os_strlen(passphrase), ssid,
1167 				   ssid_len, iterations, buflen, buf) != 1)
1168 		return -1;
1169 	return 0;
1170 }
1171 
1172 
1173 int hmac_sha1_vector(const u8 *key, size_t key_len, size_t num_elem,
1174 		     const u8 *addr[], const size_t *len, u8 *mac)
1175 {
1176 	return openssl_hmac_vector(EVP_sha1(), key, key_len, num_elem, addr,
1177 				   len, mac, 20);
1178 }
1179 
1180 
1181 int hmac_sha1(const u8 *key, size_t key_len, const u8 *data, size_t data_len,
1182 	       u8 *mac)
1183 {
1184 	return hmac_sha1_vector(key, key_len, 1, &data, &data_len, mac);
1185 }
1186 
1187 
1188 #ifdef CONFIG_SHA256
1189 
1190 int hmac_sha256_vector(const u8 *key, size_t key_len, size_t num_elem,
1191 		       const u8 *addr[], const size_t *len, u8 *mac)
1192 {
1193 	return openssl_hmac_vector(EVP_sha256(), key, key_len, num_elem, addr,
1194 				   len, mac, 32);
1195 }
1196 
1197 
1198 int hmac_sha256(const u8 *key, size_t key_len, const u8 *data,
1199 		size_t data_len, u8 *mac)
1200 {
1201 	return hmac_sha256_vector(key, key_len, 1, &data, &data_len, mac);
1202 }
1203 
1204 #endif /* CONFIG_SHA256 */
1205 
1206 
1207 #ifdef CONFIG_SHA384
1208 
1209 int hmac_sha384_vector(const u8 *key, size_t key_len, size_t num_elem,
1210 		       const u8 *addr[], const size_t *len, u8 *mac)
1211 {
1212 	return openssl_hmac_vector(EVP_sha384(), key, key_len, num_elem, addr,
1213 				   len, mac, 48);
1214 }
1215 
1216 
1217 int hmac_sha384(const u8 *key, size_t key_len, const u8 *data,
1218 		size_t data_len, u8 *mac)
1219 {
1220 	return hmac_sha384_vector(key, key_len, 1, &data, &data_len, mac);
1221 }
1222 
1223 #endif /* CONFIG_SHA384 */
1224 
1225 
1226 #ifdef CONFIG_SHA512
1227 
1228 int hmac_sha512_vector(const u8 *key, size_t key_len, size_t num_elem,
1229 		       const u8 *addr[], const size_t *len, u8 *mac)
1230 {
1231 	return openssl_hmac_vector(EVP_sha512(), key, key_len, num_elem, addr,
1232 				   len, mac, 64);
1233 }
1234 
1235 
1236 int hmac_sha512(const u8 *key, size_t key_len, const u8 *data,
1237 		size_t data_len, u8 *mac)
1238 {
1239 	return hmac_sha512_vector(key, key_len, 1, &data, &data_len, mac);
1240 }
1241 
1242 #endif /* CONFIG_SHA512 */
1243 
1244 
1245 int crypto_get_random(void *buf, size_t len)
1246 {
1247 	if (RAND_bytes(buf, len) != 1)
1248 		return -1;
1249 	return 0;
1250 }
1251 
1252 
1253 #ifdef CONFIG_OPENSSL_CMAC
1254 int omac1_aes_vector(const u8 *key, size_t key_len, size_t num_elem,
1255 		     const u8 *addr[], const size_t *len, u8 *mac)
1256 {
1257 	CMAC_CTX *ctx;
1258 	int ret = -1;
1259 	size_t outlen, i;
1260 
1261 	if (TEST_FAIL())
1262 		return -1;
1263 
1264 	ctx = CMAC_CTX_new();
1265 	if (ctx == NULL)
1266 		return -1;
1267 
1268 	if (key_len == 32) {
1269 		if (!CMAC_Init(ctx, key, 32, EVP_aes_256_cbc(), NULL))
1270 			goto fail;
1271 	} else if (key_len == 16) {
1272 		if (!CMAC_Init(ctx, key, 16, EVP_aes_128_cbc(), NULL))
1273 			goto fail;
1274 	} else {
1275 		goto fail;
1276 	}
1277 	for (i = 0; i < num_elem; i++) {
1278 		if (!CMAC_Update(ctx, addr[i], len[i]))
1279 			goto fail;
1280 	}
1281 	if (!CMAC_Final(ctx, mac, &outlen) || outlen != 16)
1282 		goto fail;
1283 
1284 	ret = 0;
1285 fail:
1286 	CMAC_CTX_free(ctx);
1287 	return ret;
1288 }
1289 
1290 
1291 int omac1_aes_128_vector(const u8 *key, size_t num_elem,
1292 			 const u8 *addr[], const size_t *len, u8 *mac)
1293 {
1294 	return omac1_aes_vector(key, 16, num_elem, addr, len, mac);
1295 }
1296 
1297 
1298 int omac1_aes_128(const u8 *key, const u8 *data, size_t data_len, u8 *mac)
1299 {
1300 	return omac1_aes_128_vector(key, 1, &data, &data_len, mac);
1301 }
1302 
1303 
1304 int omac1_aes_256(const u8 *key, const u8 *data, size_t data_len, u8 *mac)
1305 {
1306 	return omac1_aes_vector(key, 32, 1, &data, &data_len, mac);
1307 }
1308 #endif /* CONFIG_OPENSSL_CMAC */
1309 
1310 
1311 struct crypto_bignum * crypto_bignum_init(void)
1312 {
1313 	if (TEST_FAIL())
1314 		return NULL;
1315 	return (struct crypto_bignum *) BN_new();
1316 }
1317 
1318 
1319 struct crypto_bignum * crypto_bignum_init_set(const u8 *buf, size_t len)
1320 {
1321 	BIGNUM *bn;
1322 
1323 	if (TEST_FAIL())
1324 		return NULL;
1325 
1326 	bn = BN_bin2bn(buf, len, NULL);
1327 	return (struct crypto_bignum *) bn;
1328 }
1329 
1330 
1331 struct crypto_bignum * crypto_bignum_init_uint(unsigned int val)
1332 {
1333 	BIGNUM *bn;
1334 
1335 	if (TEST_FAIL())
1336 		return NULL;
1337 
1338 	bn = BN_new();
1339 	if (!bn)
1340 		return NULL;
1341 	if (BN_set_word(bn, val) != 1) {
1342 		BN_free(bn);
1343 		return NULL;
1344 	}
1345 	return (struct crypto_bignum *) bn;
1346 }
1347 
1348 
1349 void crypto_bignum_deinit(struct crypto_bignum *n, int clear)
1350 {
1351 	if (clear)
1352 		BN_clear_free((BIGNUM *) n);
1353 	else
1354 		BN_free((BIGNUM *) n);
1355 }
1356 
1357 
1358 int crypto_bignum_to_bin(const struct crypto_bignum *a,
1359 			 u8 *buf, size_t buflen, size_t padlen)
1360 {
1361 	int num_bytes, offset;
1362 
1363 	if (TEST_FAIL())
1364 		return -1;
1365 
1366 	if (padlen > buflen)
1367 		return -1;
1368 
1369 	if (padlen) {
1370 #ifdef OPENSSL_IS_BORINGSSL
1371 		if (BN_bn2bin_padded(buf, padlen, (const BIGNUM *) a) == 0)
1372 			return -1;
1373 		return padlen;
1374 #else /* OPENSSL_IS_BORINGSSL */
1375 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
1376 		return BN_bn2binpad((const BIGNUM *) a, buf, padlen);
1377 #endif
1378 #endif
1379 	}
1380 
1381 	num_bytes = BN_num_bytes((const BIGNUM *) a);
1382 	if ((size_t) num_bytes > buflen)
1383 		return -1;
1384 	if (padlen > (size_t) num_bytes)
1385 		offset = padlen - num_bytes;
1386 	else
1387 		offset = 0;
1388 
1389 	os_memset(buf, 0, offset);
1390 	BN_bn2bin((const BIGNUM *) a, buf + offset);
1391 
1392 	return num_bytes + offset;
1393 }
1394 
1395 
1396 int crypto_bignum_rand(struct crypto_bignum *r, const struct crypto_bignum *m)
1397 {
1398 	if (TEST_FAIL())
1399 		return -1;
1400 	return BN_rand_range((BIGNUM *) r, (const BIGNUM *) m) == 1 ? 0 : -1;
1401 }
1402 
1403 
1404 int crypto_bignum_add(const struct crypto_bignum *a,
1405 		      const struct crypto_bignum *b,
1406 		      struct crypto_bignum *c)
1407 {
1408 	return BN_add((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b) ?
1409 		0 : -1;
1410 }
1411 
1412 
1413 int crypto_bignum_mod(const struct crypto_bignum *a,
1414 		      const struct crypto_bignum *b,
1415 		      struct crypto_bignum *c)
1416 {
1417 	int res;
1418 	BN_CTX *bnctx;
1419 
1420 	bnctx = BN_CTX_new();
1421 	if (bnctx == NULL)
1422 		return -1;
1423 	res = BN_mod((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b,
1424 		     bnctx);
1425 	BN_CTX_free(bnctx);
1426 
1427 	return res ? 0 : -1;
1428 }
1429 
1430 
1431 int crypto_bignum_exptmod(const struct crypto_bignum *a,
1432 			  const struct crypto_bignum *b,
1433 			  const struct crypto_bignum *c,
1434 			  struct crypto_bignum *d)
1435 {
1436 	int res;
1437 	BN_CTX *bnctx;
1438 
1439 	if (TEST_FAIL())
1440 		return -1;
1441 
1442 	bnctx = BN_CTX_new();
1443 	if (bnctx == NULL)
1444 		return -1;
1445 	res = BN_mod_exp_mont_consttime((BIGNUM *) d, (const BIGNUM *) a,
1446 					(const BIGNUM *) b, (const BIGNUM *) c,
1447 					bnctx, NULL);
1448 	BN_CTX_free(bnctx);
1449 
1450 	return res ? 0 : -1;
1451 }
1452 
1453 
1454 int crypto_bignum_inverse(const struct crypto_bignum *a,
1455 			  const struct crypto_bignum *b,
1456 			  struct crypto_bignum *c)
1457 {
1458 	BIGNUM *res;
1459 	BN_CTX *bnctx;
1460 
1461 	if (TEST_FAIL())
1462 		return -1;
1463 	bnctx = BN_CTX_new();
1464 	if (bnctx == NULL)
1465 		return -1;
1466 #ifdef OPENSSL_IS_BORINGSSL
1467 	/* TODO: use BN_mod_inverse_blinded() ? */
1468 #else /* OPENSSL_IS_BORINGSSL */
1469 	BN_set_flags((BIGNUM *) a, BN_FLG_CONSTTIME);
1470 #endif /* OPENSSL_IS_BORINGSSL */
1471 	res = BN_mod_inverse((BIGNUM *) c, (const BIGNUM *) a,
1472 			     (const BIGNUM *) b, bnctx);
1473 	BN_CTX_free(bnctx);
1474 
1475 	return res ? 0 : -1;
1476 }
1477 
1478 
1479 int crypto_bignum_sub(const struct crypto_bignum *a,
1480 		      const struct crypto_bignum *b,
1481 		      struct crypto_bignum *c)
1482 {
1483 	if (TEST_FAIL())
1484 		return -1;
1485 	return BN_sub((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b) ?
1486 		0 : -1;
1487 }
1488 
1489 
1490 int crypto_bignum_div(const struct crypto_bignum *a,
1491 		      const struct crypto_bignum *b,
1492 		      struct crypto_bignum *c)
1493 {
1494 	int res;
1495 
1496 	BN_CTX *bnctx;
1497 
1498 	if (TEST_FAIL())
1499 		return -1;
1500 
1501 	bnctx = BN_CTX_new();
1502 	if (bnctx == NULL)
1503 		return -1;
1504 #ifndef OPENSSL_IS_BORINGSSL
1505 	BN_set_flags((BIGNUM *) a, BN_FLG_CONSTTIME);
1506 #endif /* OPENSSL_IS_BORINGSSL */
1507 	res = BN_div((BIGNUM *) c, NULL, (const BIGNUM *) a,
1508 		     (const BIGNUM *) b, bnctx);
1509 	BN_CTX_free(bnctx);
1510 
1511 	return res ? 0 : -1;
1512 }
1513 
1514 
1515 int crypto_bignum_addmod(const struct crypto_bignum *a,
1516 			 const struct crypto_bignum *b,
1517 			 const struct crypto_bignum *c,
1518 			 struct crypto_bignum *d)
1519 {
1520 	int res;
1521 	BN_CTX *bnctx;
1522 
1523 	if (TEST_FAIL())
1524 		return -1;
1525 
1526 	bnctx = BN_CTX_new();
1527 	if (!bnctx)
1528 		return -1;
1529 	res = BN_mod_add((BIGNUM *) d, (const BIGNUM *) a, (const BIGNUM *) b,
1530 			 (const BIGNUM *) c, bnctx);
1531 	BN_CTX_free(bnctx);
1532 
1533 	return res ? 0 : -1;
1534 }
1535 
1536 
1537 int crypto_bignum_mulmod(const struct crypto_bignum *a,
1538 			 const struct crypto_bignum *b,
1539 			 const struct crypto_bignum *c,
1540 			 struct crypto_bignum *d)
1541 {
1542 	int res;
1543 
1544 	BN_CTX *bnctx;
1545 
1546 	if (TEST_FAIL())
1547 		return -1;
1548 
1549 	bnctx = BN_CTX_new();
1550 	if (bnctx == NULL)
1551 		return -1;
1552 	res = BN_mod_mul((BIGNUM *) d, (const BIGNUM *) a, (const BIGNUM *) b,
1553 			 (const BIGNUM *) c, bnctx);
1554 	BN_CTX_free(bnctx);
1555 
1556 	return res ? 0 : -1;
1557 }
1558 
1559 
1560 int crypto_bignum_sqrmod(const struct crypto_bignum *a,
1561 			 const struct crypto_bignum *b,
1562 			 struct crypto_bignum *c)
1563 {
1564 	int res;
1565 	BN_CTX *bnctx;
1566 
1567 	if (TEST_FAIL())
1568 		return -1;
1569 
1570 	bnctx = BN_CTX_new();
1571 	if (!bnctx)
1572 		return -1;
1573 	res = BN_mod_sqr((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b,
1574 			 bnctx);
1575 	BN_CTX_free(bnctx);
1576 
1577 	return res ? 0 : -1;
1578 }
1579 
1580 
1581 int crypto_bignum_rshift(const struct crypto_bignum *a, int n,
1582 			 struct crypto_bignum *r)
1583 {
1584 	/* Note: BN_rshift() does not modify the first argument even though it
1585 	 * has not been marked const. */
1586 	return BN_rshift((BIGNUM *) a, (BIGNUM *) r, n) == 1 ? 0 : -1;
1587 }
1588 
1589 
1590 int crypto_bignum_cmp(const struct crypto_bignum *a,
1591 		      const struct crypto_bignum *b)
1592 {
1593 	return BN_cmp((const BIGNUM *) a, (const BIGNUM *) b);
1594 }
1595 
1596 
1597 int crypto_bignum_is_zero(const struct crypto_bignum *a)
1598 {
1599 	return BN_is_zero((const BIGNUM *) a);
1600 }
1601 
1602 
1603 int crypto_bignum_is_one(const struct crypto_bignum *a)
1604 {
1605 	return BN_is_one((const BIGNUM *) a);
1606 }
1607 
1608 
1609 int crypto_bignum_is_odd(const struct crypto_bignum *a)
1610 {
1611 	return BN_is_odd((const BIGNUM *) a);
1612 }
1613 
1614 
1615 int crypto_bignum_legendre(const struct crypto_bignum *a,
1616 			   const struct crypto_bignum *p)
1617 {
1618 	BN_CTX *bnctx;
1619 	BIGNUM *exp = NULL, *tmp = NULL;
1620 	int res = -2;
1621 	unsigned int mask;
1622 
1623 	if (TEST_FAIL())
1624 		return -2;
1625 
1626 	bnctx = BN_CTX_new();
1627 	if (bnctx == NULL)
1628 		return -2;
1629 
1630 	exp = BN_new();
1631 	tmp = BN_new();
1632 	if (!exp || !tmp ||
1633 	    /* exp = (p-1) / 2 */
1634 	    !BN_sub(exp, (const BIGNUM *) p, BN_value_one()) ||
1635 	    !BN_rshift1(exp, exp) ||
1636 	    !BN_mod_exp_mont_consttime(tmp, (const BIGNUM *) a, exp,
1637 				       (const BIGNUM *) p, bnctx, NULL))
1638 		goto fail;
1639 
1640 	/* Return 1 if tmp == 1, 0 if tmp == 0, or -1 otherwise. Need to use
1641 	 * constant time selection to avoid branches here. */
1642 	res = -1;
1643 	mask = const_time_eq(BN_is_word(tmp, 1), 1);
1644 	res = const_time_select_int(mask, 1, res);
1645 	mask = const_time_eq(BN_is_zero(tmp), 1);
1646 	res = const_time_select_int(mask, 0, res);
1647 
1648 fail:
1649 	BN_clear_free(tmp);
1650 	BN_clear_free(exp);
1651 	BN_CTX_free(bnctx);
1652 	return res;
1653 }
1654 
1655 
1656 #ifdef CONFIG_ECC
1657 
1658 struct crypto_ec {
1659 	EC_GROUP *group;
1660 	int nid;
1661 	BN_CTX *bnctx;
1662 	BIGNUM *prime;
1663 	BIGNUM *order;
1664 	BIGNUM *a;
1665 	BIGNUM *b;
1666 };
1667 
1668 
1669 static int crypto_ec_group_2_nid(int group)
1670 {
1671 	/* Map from IANA registry for IKE D-H groups to OpenSSL NID */
1672 	switch (group) {
1673 	case 19:
1674 		return NID_X9_62_prime256v1;
1675 	case 20:
1676 		return NID_secp384r1;
1677 	case 21:
1678 		return NID_secp521r1;
1679 	case 25:
1680 		return NID_X9_62_prime192v1;
1681 	case 26:
1682 		return NID_secp224r1;
1683 #ifdef NID_brainpoolP224r1
1684 	case 27:
1685 		return NID_brainpoolP224r1;
1686 #endif /* NID_brainpoolP224r1 */
1687 #ifdef NID_brainpoolP256r1
1688 	case 28:
1689 		return NID_brainpoolP256r1;
1690 #endif /* NID_brainpoolP256r1 */
1691 #ifdef NID_brainpoolP384r1
1692 	case 29:
1693 		return NID_brainpoolP384r1;
1694 #endif /* NID_brainpoolP384r1 */
1695 #ifdef NID_brainpoolP512r1
1696 	case 30:
1697 		return NID_brainpoolP512r1;
1698 #endif /* NID_brainpoolP512r1 */
1699 	default:
1700 		return -1;
1701 	}
1702 }
1703 
1704 
1705 struct crypto_ec * crypto_ec_init(int group)
1706 {
1707 	struct crypto_ec *e;
1708 	int nid;
1709 
1710 	nid = crypto_ec_group_2_nid(group);
1711 	if (nid < 0)
1712 		return NULL;
1713 
1714 	e = os_zalloc(sizeof(*e));
1715 	if (e == NULL)
1716 		return NULL;
1717 
1718 	e->nid = nid;
1719 	e->bnctx = BN_CTX_new();
1720 	e->group = EC_GROUP_new_by_curve_name(nid);
1721 	e->prime = BN_new();
1722 	e->order = BN_new();
1723 	e->a = BN_new();
1724 	e->b = BN_new();
1725 	if (e->group == NULL || e->bnctx == NULL || e->prime == NULL ||
1726 	    e->order == NULL || e->a == NULL || e->b == NULL ||
1727 	    !EC_GROUP_get_curve_GFp(e->group, e->prime, e->a, e->b, e->bnctx) ||
1728 	    !EC_GROUP_get_order(e->group, e->order, e->bnctx)) {
1729 		crypto_ec_deinit(e);
1730 		e = NULL;
1731 	}
1732 
1733 	return e;
1734 }
1735 
1736 
1737 void crypto_ec_deinit(struct crypto_ec *e)
1738 {
1739 	if (e == NULL)
1740 		return;
1741 	BN_clear_free(e->b);
1742 	BN_clear_free(e->a);
1743 	BN_clear_free(e->order);
1744 	BN_clear_free(e->prime);
1745 	EC_GROUP_free(e->group);
1746 	BN_CTX_free(e->bnctx);
1747 	os_free(e);
1748 }
1749 
1750 
1751 struct crypto_ec_point * crypto_ec_point_init(struct crypto_ec *e)
1752 {
1753 	if (TEST_FAIL())
1754 		return NULL;
1755 	if (e == NULL)
1756 		return NULL;
1757 	return (struct crypto_ec_point *) EC_POINT_new(e->group);
1758 }
1759 
1760 
1761 size_t crypto_ec_prime_len(struct crypto_ec *e)
1762 {
1763 	return BN_num_bytes(e->prime);
1764 }
1765 
1766 
1767 size_t crypto_ec_prime_len_bits(struct crypto_ec *e)
1768 {
1769 	return BN_num_bits(e->prime);
1770 }
1771 
1772 
1773 size_t crypto_ec_order_len(struct crypto_ec *e)
1774 {
1775 	return BN_num_bytes(e->order);
1776 }
1777 
1778 
1779 const struct crypto_bignum * crypto_ec_get_prime(struct crypto_ec *e)
1780 {
1781 	return (const struct crypto_bignum *) e->prime;
1782 }
1783 
1784 
1785 const struct crypto_bignum * crypto_ec_get_order(struct crypto_ec *e)
1786 {
1787 	return (const struct crypto_bignum *) e->order;
1788 }
1789 
1790 
1791 const struct crypto_bignum * crypto_ec_get_a(struct crypto_ec *e)
1792 {
1793 	return (const struct crypto_bignum *) e->a;
1794 }
1795 
1796 
1797 const struct crypto_bignum * crypto_ec_get_b(struct crypto_ec *e)
1798 {
1799 	return (const struct crypto_bignum *) e->b;
1800 }
1801 
1802 
1803 const struct crypto_ec_point * crypto_ec_get_generator(struct crypto_ec *e)
1804 {
1805 	return (const struct crypto_ec_point *)
1806 		EC_GROUP_get0_generator(e->group);
1807 }
1808 
1809 
1810 void crypto_ec_point_deinit(struct crypto_ec_point *p, int clear)
1811 {
1812 	if (clear)
1813 		EC_POINT_clear_free((EC_POINT *) p);
1814 	else
1815 		EC_POINT_free((EC_POINT *) p);
1816 }
1817 
1818 
1819 int crypto_ec_point_x(struct crypto_ec *e, const struct crypto_ec_point *p,
1820 		      struct crypto_bignum *x)
1821 {
1822 	return EC_POINT_get_affine_coordinates_GFp(e->group,
1823 						   (const EC_POINT *) p,
1824 						   (BIGNUM *) x, NULL,
1825 						   e->bnctx) == 1 ? 0 : -1;
1826 }
1827 
1828 
1829 int crypto_ec_point_to_bin(struct crypto_ec *e,
1830 			   const struct crypto_ec_point *point, u8 *x, u8 *y)
1831 {
1832 	BIGNUM *x_bn, *y_bn;
1833 	int ret = -1;
1834 	int len = BN_num_bytes(e->prime);
1835 
1836 	if (TEST_FAIL())
1837 		return -1;
1838 
1839 	x_bn = BN_new();
1840 	y_bn = BN_new();
1841 
1842 	if (x_bn && y_bn &&
1843 	    EC_POINT_get_affine_coordinates_GFp(e->group, (EC_POINT *) point,
1844 						x_bn, y_bn, e->bnctx)) {
1845 		if (x) {
1846 			crypto_bignum_to_bin((struct crypto_bignum *) x_bn,
1847 					     x, len, len);
1848 		}
1849 		if (y) {
1850 			crypto_bignum_to_bin((struct crypto_bignum *) y_bn,
1851 					     y, len, len);
1852 		}
1853 		ret = 0;
1854 	}
1855 
1856 	BN_clear_free(x_bn);
1857 	BN_clear_free(y_bn);
1858 	return ret;
1859 }
1860 
1861 
1862 struct crypto_ec_point * crypto_ec_point_from_bin(struct crypto_ec *e,
1863 						  const u8 *val)
1864 {
1865 	BIGNUM *x, *y;
1866 	EC_POINT *elem;
1867 	int len = BN_num_bytes(e->prime);
1868 
1869 	if (TEST_FAIL())
1870 		return NULL;
1871 
1872 	x = BN_bin2bn(val, len, NULL);
1873 	y = BN_bin2bn(val + len, len, NULL);
1874 	elem = EC_POINT_new(e->group);
1875 	if (x == NULL || y == NULL || elem == NULL) {
1876 		BN_clear_free(x);
1877 		BN_clear_free(y);
1878 		EC_POINT_clear_free(elem);
1879 		return NULL;
1880 	}
1881 
1882 	if (!EC_POINT_set_affine_coordinates_GFp(e->group, elem, x, y,
1883 						 e->bnctx)) {
1884 		EC_POINT_clear_free(elem);
1885 		elem = NULL;
1886 	}
1887 
1888 	BN_clear_free(x);
1889 	BN_clear_free(y);
1890 
1891 	return (struct crypto_ec_point *) elem;
1892 }
1893 
1894 
1895 int crypto_ec_point_add(struct crypto_ec *e, const struct crypto_ec_point *a,
1896 			const struct crypto_ec_point *b,
1897 			struct crypto_ec_point *c)
1898 {
1899 	if (TEST_FAIL())
1900 		return -1;
1901 	return EC_POINT_add(e->group, (EC_POINT *) c, (const EC_POINT *) a,
1902 			    (const EC_POINT *) b, e->bnctx) ? 0 : -1;
1903 }
1904 
1905 
1906 int crypto_ec_point_mul(struct crypto_ec *e, const struct crypto_ec_point *p,
1907 			const struct crypto_bignum *b,
1908 			struct crypto_ec_point *res)
1909 {
1910 	if (TEST_FAIL())
1911 		return -1;
1912 	return EC_POINT_mul(e->group, (EC_POINT *) res, NULL,
1913 			    (const EC_POINT *) p, (const BIGNUM *) b, e->bnctx)
1914 		? 0 : -1;
1915 }
1916 
1917 
1918 int crypto_ec_point_invert(struct crypto_ec *e, struct crypto_ec_point *p)
1919 {
1920 	if (TEST_FAIL())
1921 		return -1;
1922 	return EC_POINT_invert(e->group, (EC_POINT *) p, e->bnctx) ? 0 : -1;
1923 }
1924 
1925 
1926 int crypto_ec_point_solve_y_coord(struct crypto_ec *e,
1927 				  struct crypto_ec_point *p,
1928 				  const struct crypto_bignum *x, int y_bit)
1929 {
1930 	if (TEST_FAIL())
1931 		return -1;
1932 	if (!EC_POINT_set_compressed_coordinates_GFp(e->group, (EC_POINT *) p,
1933 						     (const BIGNUM *) x, y_bit,
1934 						     e->bnctx) ||
1935 	    !EC_POINT_is_on_curve(e->group, (EC_POINT *) p, e->bnctx))
1936 		return -1;
1937 	return 0;
1938 }
1939 
1940 
1941 struct crypto_bignum *
1942 crypto_ec_point_compute_y_sqr(struct crypto_ec *e,
1943 			      const struct crypto_bignum *x)
1944 {
1945 	BIGNUM *tmp, *tmp2, *y_sqr = NULL;
1946 
1947 	if (TEST_FAIL())
1948 		return NULL;
1949 
1950 	tmp = BN_new();
1951 	tmp2 = BN_new();
1952 
1953 	/* y^2 = x^3 + ax + b */
1954 	if (tmp && tmp2 &&
1955 	    BN_mod_sqr(tmp, (const BIGNUM *) x, e->prime, e->bnctx) &&
1956 	    BN_mod_mul(tmp, tmp, (const BIGNUM *) x, e->prime, e->bnctx) &&
1957 	    BN_mod_mul(tmp2, e->a, (const BIGNUM *) x, e->prime, e->bnctx) &&
1958 	    BN_mod_add_quick(tmp2, tmp2, tmp, e->prime) &&
1959 	    BN_mod_add_quick(tmp2, tmp2, e->b, e->prime)) {
1960 		y_sqr = tmp2;
1961 		tmp2 = NULL;
1962 	}
1963 
1964 	BN_clear_free(tmp);
1965 	BN_clear_free(tmp2);
1966 
1967 	return (struct crypto_bignum *) y_sqr;
1968 }
1969 
1970 
1971 int crypto_ec_point_is_at_infinity(struct crypto_ec *e,
1972 				   const struct crypto_ec_point *p)
1973 {
1974 	return EC_POINT_is_at_infinity(e->group, (const EC_POINT *) p);
1975 }
1976 
1977 
1978 int crypto_ec_point_is_on_curve(struct crypto_ec *e,
1979 				const struct crypto_ec_point *p)
1980 {
1981 	return EC_POINT_is_on_curve(e->group, (const EC_POINT *) p,
1982 				    e->bnctx) == 1;
1983 }
1984 
1985 
1986 int crypto_ec_point_cmp(const struct crypto_ec *e,
1987 			const struct crypto_ec_point *a,
1988 			const struct crypto_ec_point *b)
1989 {
1990 	return EC_POINT_cmp(e->group, (const EC_POINT *) a,
1991 			    (const EC_POINT *) b, e->bnctx);
1992 }
1993 
1994 
1995 void crypto_ec_point_debug_print(const struct crypto_ec *e,
1996 				 const struct crypto_ec_point *p,
1997 				 const char *title)
1998 {
1999 	BIGNUM *x, *y;
2000 	char *x_str = NULL, *y_str = NULL;
2001 
2002 	x = BN_new();
2003 	y = BN_new();
2004 	if (!x || !y ||
2005 	    EC_POINT_get_affine_coordinates_GFp(e->group, (const EC_POINT *) p,
2006 						x, y, e->bnctx) != 1)
2007 		goto fail;
2008 
2009 	x_str = BN_bn2hex(x);
2010 	y_str = BN_bn2hex(y);
2011 	if (!x_str || !y_str)
2012 		goto fail;
2013 
2014 	wpa_printf(MSG_DEBUG, "%s (%s,%s)", title, x_str, y_str);
2015 
2016 fail:
2017 	OPENSSL_free(x_str);
2018 	OPENSSL_free(y_str);
2019 	BN_free(x);
2020 	BN_free(y);
2021 }
2022 
2023 
2024 struct crypto_ecdh {
2025 	struct crypto_ec *ec;
2026 	EVP_PKEY *pkey;
2027 };
2028 
2029 struct crypto_ecdh * crypto_ecdh_init(int group)
2030 {
2031 	struct crypto_ecdh *ecdh;
2032 	EVP_PKEY *params = NULL;
2033 	EC_KEY *ec_params = NULL;
2034 	EVP_PKEY_CTX *kctx = NULL;
2035 
2036 	ecdh = os_zalloc(sizeof(*ecdh));
2037 	if (!ecdh)
2038 		goto fail;
2039 
2040 	ecdh->ec = crypto_ec_init(group);
2041 	if (!ecdh->ec)
2042 		goto fail;
2043 
2044 	ec_params = EC_KEY_new_by_curve_name(ecdh->ec->nid);
2045 	if (!ec_params) {
2046 		wpa_printf(MSG_ERROR,
2047 			   "OpenSSL: Failed to generate EC_KEY parameters");
2048 		goto fail;
2049 	}
2050 	EC_KEY_set_asn1_flag(ec_params, OPENSSL_EC_NAMED_CURVE);
2051 	params = EVP_PKEY_new();
2052 	if (!params || EVP_PKEY_set1_EC_KEY(params, ec_params) != 1) {
2053 		wpa_printf(MSG_ERROR,
2054 			   "OpenSSL: Failed to generate EVP_PKEY parameters");
2055 		goto fail;
2056 	}
2057 
2058 	kctx = EVP_PKEY_CTX_new(params, NULL);
2059 	if (!kctx)
2060 		goto fail;
2061 
2062 	if (EVP_PKEY_keygen_init(kctx) != 1) {
2063 		wpa_printf(MSG_ERROR,
2064 			   "OpenSSL: EVP_PKEY_keygen_init failed: %s",
2065 			   ERR_error_string(ERR_get_error(), NULL));
2066 		goto fail;
2067 	}
2068 
2069 	if (EVP_PKEY_keygen(kctx, &ecdh->pkey) != 1) {
2070 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_PKEY_keygen failed: %s",
2071 			   ERR_error_string(ERR_get_error(), NULL));
2072 		goto fail;
2073 	}
2074 
2075 done:
2076 	EC_KEY_free(ec_params);
2077 	EVP_PKEY_free(params);
2078 	EVP_PKEY_CTX_free(kctx);
2079 
2080 	return ecdh;
2081 fail:
2082 	crypto_ecdh_deinit(ecdh);
2083 	ecdh = NULL;
2084 	goto done;
2085 }
2086 
2087 
2088 struct crypto_ecdh * crypto_ecdh_init2(int group, struct crypto_ec_key *own_key)
2089 {
2090 	struct crypto_ecdh *ecdh;
2091 
2092 	ecdh = os_zalloc(sizeof(*ecdh));
2093 	if (!ecdh)
2094 		goto fail;
2095 
2096 	ecdh->ec = crypto_ec_init(group);
2097 	if (!ecdh->ec)
2098 		goto fail;
2099 
2100 	ecdh->pkey = EVP_PKEY_new();
2101 	if (!ecdh->pkey ||
2102 	    EVP_PKEY_assign_EC_KEY(ecdh->pkey,
2103 				   EVP_PKEY_get1_EC_KEY((EVP_PKEY *) own_key))
2104 	    != 1)
2105 		goto fail;
2106 
2107 	return ecdh;
2108 fail:
2109 	crypto_ecdh_deinit(ecdh);
2110 	return NULL;
2111 }
2112 
2113 
2114 struct wpabuf * crypto_ecdh_get_pubkey(struct crypto_ecdh *ecdh, int inc_y)
2115 {
2116 	struct wpabuf *buf = NULL;
2117 	EC_KEY *eckey;
2118 	const EC_POINT *pubkey;
2119 	BIGNUM *x, *y = NULL;
2120 	int len = BN_num_bytes(ecdh->ec->prime);
2121 	int res;
2122 
2123 	eckey = EVP_PKEY_get1_EC_KEY(ecdh->pkey);
2124 	if (!eckey)
2125 		return NULL;
2126 
2127 	pubkey = EC_KEY_get0_public_key(eckey);
2128 	if (!pubkey)
2129 		return NULL;
2130 
2131 	x = BN_new();
2132 	if (inc_y) {
2133 		y = BN_new();
2134 		if (!y)
2135 			goto fail;
2136 	}
2137 	buf = wpabuf_alloc(inc_y ? 2 * len : len);
2138 	if (!x || !buf)
2139 		goto fail;
2140 
2141 	if (EC_POINT_get_affine_coordinates_GFp(ecdh->ec->group, pubkey,
2142 						x, y, ecdh->ec->bnctx) != 1) {
2143 		wpa_printf(MSG_ERROR,
2144 			   "OpenSSL: EC_POINT_get_affine_coordinates_GFp failed: %s",
2145 			   ERR_error_string(ERR_get_error(), NULL));
2146 		goto fail;
2147 	}
2148 
2149 	res = crypto_bignum_to_bin((struct crypto_bignum *) x,
2150 				   wpabuf_put(buf, len), len, len);
2151 	if (res < 0)
2152 		goto fail;
2153 
2154 	if (inc_y) {
2155 		res = crypto_bignum_to_bin((struct crypto_bignum *) y,
2156 					   wpabuf_put(buf, len), len, len);
2157 		if (res < 0)
2158 			goto fail;
2159 	}
2160 
2161 done:
2162 	BN_clear_free(x);
2163 	BN_clear_free(y);
2164 	EC_KEY_free(eckey);
2165 
2166 	return buf;
2167 fail:
2168 	wpabuf_free(buf);
2169 	buf = NULL;
2170 	goto done;
2171 }
2172 
2173 
2174 struct wpabuf * crypto_ecdh_set_peerkey(struct crypto_ecdh *ecdh, int inc_y,
2175 					const u8 *key, size_t len)
2176 {
2177 	BIGNUM *x, *y = NULL;
2178 	EVP_PKEY_CTX *ctx = NULL;
2179 	EVP_PKEY *peerkey = NULL;
2180 	struct wpabuf *secret = NULL;
2181 	size_t secret_len;
2182 	EC_POINT *pub;
2183 	EC_KEY *eckey = NULL;
2184 
2185 	x = BN_bin2bn(key, inc_y ? len / 2 : len, NULL);
2186 	pub = EC_POINT_new(ecdh->ec->group);
2187 	if (!x || !pub)
2188 		goto fail;
2189 
2190 	if (inc_y) {
2191 		y = BN_bin2bn(key + len / 2, len / 2, NULL);
2192 		if (!y)
2193 			goto fail;
2194 		if (!EC_POINT_set_affine_coordinates_GFp(ecdh->ec->group, pub,
2195 							 x, y,
2196 							 ecdh->ec->bnctx)) {
2197 			wpa_printf(MSG_ERROR,
2198 				   "OpenSSL: EC_POINT_set_affine_coordinates_GFp failed: %s",
2199 				   ERR_error_string(ERR_get_error(), NULL));
2200 			goto fail;
2201 		}
2202 	} else if (!EC_POINT_set_compressed_coordinates_GFp(ecdh->ec->group,
2203 							    pub, x, 0,
2204 							    ecdh->ec->bnctx)) {
2205 		wpa_printf(MSG_ERROR,
2206 			   "OpenSSL: EC_POINT_set_compressed_coordinates_GFp failed: %s",
2207 			   ERR_error_string(ERR_get_error(), NULL));
2208 		goto fail;
2209 	}
2210 
2211 	if (!EC_POINT_is_on_curve(ecdh->ec->group, pub, ecdh->ec->bnctx)) {
2212 		wpa_printf(MSG_ERROR,
2213 			   "OpenSSL: ECDH peer public key is not on curve");
2214 		goto fail;
2215 	}
2216 
2217 	eckey = EC_KEY_new_by_curve_name(ecdh->ec->nid);
2218 	if (!eckey || EC_KEY_set_public_key(eckey, pub) != 1) {
2219 		wpa_printf(MSG_ERROR,
2220 			   "OpenSSL: EC_KEY_set_public_key failed: %s",
2221 			   ERR_error_string(ERR_get_error(), NULL));
2222 		goto fail;
2223 	}
2224 
2225 	peerkey = EVP_PKEY_new();
2226 	if (!peerkey || EVP_PKEY_set1_EC_KEY(peerkey, eckey) != 1)
2227 		goto fail;
2228 
2229 	ctx = EVP_PKEY_CTX_new(ecdh->pkey, NULL);
2230 	if (!ctx || EVP_PKEY_derive_init(ctx) != 1 ||
2231 	    EVP_PKEY_derive_set_peer(ctx, peerkey) != 1 ||
2232 	    EVP_PKEY_derive(ctx, NULL, &secret_len) != 1) {
2233 		wpa_printf(MSG_ERROR,
2234 			   "OpenSSL: EVP_PKEY_derive(1) failed: %s",
2235 			   ERR_error_string(ERR_get_error(), NULL));
2236 		goto fail;
2237 	}
2238 
2239 	secret = wpabuf_alloc(secret_len);
2240 	if (!secret)
2241 		goto fail;
2242 	if (EVP_PKEY_derive(ctx, wpabuf_put(secret, 0), &secret_len) != 1) {
2243 		wpa_printf(MSG_ERROR,
2244 			   "OpenSSL: EVP_PKEY_derive(2) failed: %s",
2245 			   ERR_error_string(ERR_get_error(), NULL));
2246 		goto fail;
2247 	}
2248 	if (secret->size != secret_len)
2249 		wpa_printf(MSG_DEBUG,
2250 			   "OpenSSL: EVP_PKEY_derive(2) changed secret_len %d -> %d",
2251 			   (int) secret->size, (int) secret_len);
2252 	wpabuf_put(secret, secret_len);
2253 
2254 done:
2255 	BN_free(x);
2256 	BN_free(y);
2257 	EC_KEY_free(eckey);
2258 	EC_POINT_free(pub);
2259 	EVP_PKEY_CTX_free(ctx);
2260 	EVP_PKEY_free(peerkey);
2261 	return secret;
2262 fail:
2263 	wpabuf_free(secret);
2264 	secret = NULL;
2265 	goto done;
2266 }
2267 
2268 
2269 void crypto_ecdh_deinit(struct crypto_ecdh *ecdh)
2270 {
2271 	if (ecdh) {
2272 		crypto_ec_deinit(ecdh->ec);
2273 		EVP_PKEY_free(ecdh->pkey);
2274 		os_free(ecdh);
2275 	}
2276 }
2277 
2278 
2279 size_t crypto_ecdh_prime_len(struct crypto_ecdh *ecdh)
2280 {
2281 	return crypto_ec_prime_len(ecdh->ec);
2282 }
2283 
2284 
2285 struct crypto_ec_key * crypto_ec_key_parse_priv(const u8 *der, size_t der_len)
2286 {
2287 	EVP_PKEY *pkey = NULL;
2288 	EC_KEY *eckey;
2289 
2290 	eckey = d2i_ECPrivateKey(NULL, &der, der_len);
2291 	if (!eckey) {
2292 		wpa_printf(MSG_INFO, "OpenSSL: d2i_ECPrivateKey() failed: %s",
2293 			   ERR_error_string(ERR_get_error(), NULL));
2294 		goto fail;
2295 	}
2296 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
2297 
2298 	pkey = EVP_PKEY_new();
2299 	if (!pkey || EVP_PKEY_assign_EC_KEY(pkey, eckey) != 1) {
2300 		EC_KEY_free(eckey);
2301 		goto fail;
2302 	}
2303 
2304 	return (struct crypto_ec_key *) pkey;
2305 fail:
2306 	crypto_ec_key_deinit((struct crypto_ec_key *) pkey);
2307 	return NULL;
2308 }
2309 
2310 
2311 struct crypto_ec_key * crypto_ec_key_parse_pub(const u8 *der, size_t der_len)
2312 {
2313 	EVP_PKEY *pkey;
2314 
2315 	pkey = d2i_PUBKEY(NULL, &der, der_len);
2316 	if (!pkey) {
2317 		wpa_printf(MSG_INFO, "OpenSSL: d2i_PUBKEY() failed: %s",
2318 			   ERR_error_string(ERR_get_error(), NULL));
2319 		goto fail;
2320 	}
2321 
2322 	/* Ensure this is an EC key */
2323 	if (!EVP_PKEY_get0_EC_KEY(pkey))
2324 		goto fail;
2325 	return (struct crypto_ec_key *) pkey;
2326 fail:
2327 	crypto_ec_key_deinit((struct crypto_ec_key *) pkey);
2328 	return NULL;
2329 }
2330 
2331 
2332 struct crypto_ec_key * crypto_ec_key_set_pub(int group, const u8 *buf_x,
2333 					     const u8 *buf_y, size_t len)
2334 {
2335 	EC_KEY *eckey = NULL;
2336 	EVP_PKEY *pkey = NULL;
2337 	EC_GROUP *ec_group = NULL;
2338 	BN_CTX *ctx;
2339 	EC_POINT *point = NULL;
2340 	BIGNUM *x = NULL, *y = NULL;
2341 	int nid;
2342 
2343 	if (!buf_x || !buf_y)
2344 		return NULL;
2345 
2346 	nid = crypto_ec_group_2_nid(group);
2347 	if (nid < 0) {
2348 		wpa_printf(MSG_ERROR, "OpenSSL: Unsupported group %d", group);
2349 		return NULL;
2350 	}
2351 
2352 	ctx = BN_CTX_new();
2353 	if (!ctx)
2354 		goto fail;
2355 
2356 	ec_group = EC_GROUP_new_by_curve_name(nid);
2357 	if (!ec_group)
2358 		goto fail;
2359 
2360 	x = BN_bin2bn(buf_x, len, NULL);
2361 	y = BN_bin2bn(buf_y, len, NULL);
2362 	point = EC_POINT_new(ec_group);
2363 	if (!x || !y || !point)
2364 		goto fail;
2365 
2366 	if (!EC_POINT_set_affine_coordinates_GFp(ec_group, point, x, y, ctx)) {
2367 		wpa_printf(MSG_ERROR,
2368 			   "OpenSSL: EC_POINT_set_affine_coordinates_GFp failed: %s",
2369 			   ERR_error_string(ERR_get_error(), NULL));
2370 		goto fail;
2371 	}
2372 
2373 	if (!EC_POINT_is_on_curve(ec_group, point, ctx) ||
2374 	    EC_POINT_is_at_infinity(ec_group, point)) {
2375 		wpa_printf(MSG_ERROR, "OpenSSL: Invalid point");
2376 		goto fail;
2377 	}
2378 
2379 	eckey = EC_KEY_new();
2380 	if (!eckey ||
2381 	    EC_KEY_set_group(eckey, ec_group) != 1 ||
2382 	    EC_KEY_set_public_key(eckey, point) != 1) {
2383 		wpa_printf(MSG_ERROR,
2384 			   "OpenSSL: Failed to set EC_KEY: %s",
2385 			   ERR_error_string(ERR_get_error(), NULL));
2386 		goto fail;
2387 	}
2388 	EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
2389 
2390 	pkey = EVP_PKEY_new();
2391 	if (!pkey || EVP_PKEY_assign_EC_KEY(pkey, eckey) != 1) {
2392 		wpa_printf(MSG_ERROR, "OpenSSL: Could not create EVP_PKEY");
2393 		goto fail;
2394 	}
2395 
2396 out:
2397 	EC_GROUP_free(ec_group);
2398 	BN_free(x);
2399 	BN_free(y);
2400 	EC_POINT_free(point);
2401 	BN_CTX_free(ctx);
2402 	return (struct crypto_ec_key *) pkey;
2403 
2404 fail:
2405 	EC_KEY_free(eckey);
2406 	EVP_PKEY_free(pkey);
2407 	pkey = NULL;
2408 	goto out;
2409 }
2410 
2411 
2412 struct crypto_ec_key *
2413 crypto_ec_key_set_pub_point(struct crypto_ec *ec,
2414 			    const struct crypto_ec_point *pub)
2415 {
2416 	EC_KEY *eckey;
2417 	EVP_PKEY *pkey = NULL;
2418 
2419 	eckey = EC_KEY_new();
2420 	if (!eckey ||
2421 	    EC_KEY_set_group(eckey, ec->group) != 1 ||
2422 	    EC_KEY_set_public_key(eckey, (const EC_POINT *) pub) != 1) {
2423 		wpa_printf(MSG_ERROR,
2424 			   "OpenSSL: Failed to set EC_KEY: %s",
2425 			   ERR_error_string(ERR_get_error(), NULL));
2426 		goto fail;
2427 	}
2428 	EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
2429 
2430 	pkey = EVP_PKEY_new();
2431 	if (!pkey || EVP_PKEY_assign_EC_KEY(pkey, eckey) != 1) {
2432 		wpa_printf(MSG_ERROR, "OpenSSL: Could not create EVP_PKEY");
2433 		goto fail;
2434 	}
2435 
2436 out:
2437 	return (struct crypto_ec_key *) pkey;
2438 
2439 fail:
2440 	EVP_PKEY_free(pkey);
2441 	EC_KEY_free(eckey);
2442 	pkey = NULL;
2443 	goto out;
2444 }
2445 
2446 
2447 struct crypto_ec_key * crypto_ec_key_gen(int group)
2448 {
2449 	EVP_PKEY_CTX *kctx = NULL;
2450 	EC_KEY *ec_params = NULL, *eckey;
2451 	EVP_PKEY *params = NULL, *key = NULL;
2452 	int nid;
2453 
2454 	nid = crypto_ec_group_2_nid(group);
2455 	if (nid < 0) {
2456 		wpa_printf(MSG_ERROR, "OpenSSL: Unsupported group %d", group);
2457 		return NULL;
2458 	}
2459 
2460 	ec_params = EC_KEY_new_by_curve_name(nid);
2461 	if (!ec_params) {
2462 		wpa_printf(MSG_ERROR,
2463 			   "OpenSSL: Failed to generate EC_KEY parameters");
2464 		goto fail;
2465 	}
2466 	EC_KEY_set_asn1_flag(ec_params, OPENSSL_EC_NAMED_CURVE);
2467 	params = EVP_PKEY_new();
2468 	if (!params || EVP_PKEY_set1_EC_KEY(params, ec_params) != 1) {
2469 		wpa_printf(MSG_ERROR,
2470 			   "OpenSSL: Failed to generate EVP_PKEY parameters");
2471 		goto fail;
2472 	}
2473 
2474 	kctx = EVP_PKEY_CTX_new(params, NULL);
2475 	if (!kctx ||
2476 	    EVP_PKEY_keygen_init(kctx) != 1 ||
2477 	    EVP_PKEY_keygen(kctx, &key) != 1) {
2478 		wpa_printf(MSG_ERROR, "OpenSSL: Failed to generate EC key");
2479 		key = NULL;
2480 		goto fail;
2481 	}
2482 
2483 	eckey = EVP_PKEY_get0_EC_KEY(key);
2484 	if (!eckey) {
2485 		key = NULL;
2486 		goto fail;
2487 	}
2488 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
2489 
2490 fail:
2491 	EC_KEY_free(ec_params);
2492 	EVP_PKEY_free(params);
2493 	EVP_PKEY_CTX_free(kctx);
2494 	return (struct crypto_ec_key *) key;
2495 }
2496 
2497 
2498 void crypto_ec_key_deinit(struct crypto_ec_key *key)
2499 {
2500 	EVP_PKEY_free((EVP_PKEY *) key);
2501 }
2502 
2503 
2504 #ifdef OPENSSL_IS_BORINGSSL
2505 
2506 /* BoringSSL version of i2d_PUBKEY() always outputs public EC key using
2507  * uncompressed form so define a custom function to export EC pubkey using
2508  * the compressed format that is explicitly required for some protocols. */
2509 
2510 #include <openssl/asn1.h>
2511 #include <openssl/asn1t.h>
2512 
2513 typedef struct {
2514 	/* AlgorithmIdentifier ecPublicKey with optional parameters present
2515 	 * as an OID identifying the curve */
2516 	X509_ALGOR *alg;
2517 	/* Compressed format public key per ANSI X9.63 */
2518 	ASN1_BIT_STRING *pub_key;
2519 } EC_COMP_PUBKEY;
2520 
2521 ASN1_SEQUENCE(EC_COMP_PUBKEY) = {
2522 	ASN1_SIMPLE(EC_COMP_PUBKEY, alg, X509_ALGOR),
2523 	ASN1_SIMPLE(EC_COMP_PUBKEY, pub_key, ASN1_BIT_STRING)
2524 } ASN1_SEQUENCE_END(EC_COMP_PUBKEY);
2525 
2526 IMPLEMENT_ASN1_FUNCTIONS(EC_COMP_PUBKEY);
2527 
2528 #endif /* OPENSSL_IS_BORINGSSL */
2529 
2530 
2531 struct wpabuf * crypto_ec_key_get_subject_public_key(struct crypto_ec_key *key)
2532 {
2533 #ifdef OPENSSL_IS_BORINGSSL
2534 	unsigned char *der = NULL;
2535 	int der_len;
2536 	const EC_KEY *eckey;
2537 	struct wpabuf *ret = NULL;
2538 	size_t len;
2539 	const EC_GROUP *group;
2540 	const EC_POINT *point;
2541 	BN_CTX *ctx;
2542 	EC_COMP_PUBKEY *pubkey = NULL;
2543 	int nid;
2544 
2545 	ctx = BN_CTX_new();
2546 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
2547 	if (!ctx || !eckey)
2548 		goto fail;
2549 
2550 	group = EC_KEY_get0_group(eckey);
2551 	point = EC_KEY_get0_public_key(eckey);
2552 	if (!group || !point)
2553 		goto fail;
2554 	nid = EC_GROUP_get_curve_name(group);
2555 
2556 	pubkey = EC_COMP_PUBKEY_new();
2557 	if (!pubkey ||
2558 	    X509_ALGOR_set0(pubkey->alg, OBJ_nid2obj(EVP_PKEY_EC),
2559 			    V_ASN1_OBJECT, (void *) OBJ_nid2obj(nid)) != 1)
2560 		goto fail;
2561 
2562 	len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED,
2563 				 NULL, 0, ctx);
2564 	if (len == 0)
2565 		goto fail;
2566 
2567 	der = OPENSSL_malloc(len);
2568 	if (!der)
2569 		goto fail;
2570 	len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED,
2571 				 der, len, ctx);
2572 
2573 	OPENSSL_free(pubkey->pub_key->data);
2574 	pubkey->pub_key->data = der;
2575 	der = NULL;
2576 	pubkey->pub_key->length = len;
2577 	/* No unused bits */
2578 	pubkey->pub_key->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
2579 	pubkey->pub_key->flags |= ASN1_STRING_FLAG_BITS_LEFT;
2580 
2581 	der_len = i2d_EC_COMP_PUBKEY(pubkey, &der);
2582 	if (der_len <= 0) {
2583 		wpa_printf(MSG_ERROR,
2584 			   "BoringSSL: Failed to build DER encoded public key");
2585 		goto fail;
2586 	}
2587 
2588 	ret = wpabuf_alloc_copy(der, der_len);
2589 fail:
2590 	EC_COMP_PUBKEY_free(pubkey);
2591 	OPENSSL_free(der);
2592 	BN_CTX_free(ctx);
2593 	return ret;
2594 #else /* OPENSSL_IS_BORINGSSL */
2595 	unsigned char *der = NULL;
2596 	int der_len;
2597 	struct wpabuf *buf;
2598 
2599 	/* For now, all users expect COMPRESSED form */
2600 	EC_KEY_set_conv_form(EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key),
2601 			     POINT_CONVERSION_COMPRESSED);
2602 
2603 	der_len = i2d_PUBKEY((EVP_PKEY *) key, &der);
2604 	if (der_len <= 0) {
2605 		wpa_printf(MSG_INFO, "OpenSSL: i2d_PUBKEY() failed: %s",
2606 			   ERR_error_string(ERR_get_error(), NULL));
2607 		return NULL;
2608 	}
2609 
2610 	buf = wpabuf_alloc_copy(der, der_len);
2611 	OPENSSL_free(der);
2612 	return buf;
2613 #endif /* OPENSSL_IS_BORINGSSL */
2614 }
2615 
2616 
2617 struct wpabuf * crypto_ec_key_get_ecprivate_key(struct crypto_ec_key *key,
2618 						bool include_pub)
2619 {
2620 	EC_KEY *eckey;
2621 	unsigned char *der = NULL;
2622 	int der_len;
2623 	struct wpabuf *buf;
2624 	unsigned int key_flags;
2625 
2626 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
2627 	if (!eckey)
2628 		return NULL;
2629 
2630 	key_flags = EC_KEY_get_enc_flags(eckey);
2631 	if (include_pub)
2632 		key_flags &= ~EC_PKEY_NO_PUBKEY;
2633 	else
2634 		key_flags |= EC_PKEY_NO_PUBKEY;
2635 	EC_KEY_set_enc_flags(eckey, key_flags);
2636 
2637 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_UNCOMPRESSED);
2638 
2639 	der_len = i2d_ECPrivateKey(eckey, &der);
2640 	if (der_len <= 0)
2641 		return NULL;
2642 	buf = wpabuf_alloc_copy(der, der_len);
2643 	OPENSSL_free(der);
2644 
2645 	return buf;
2646 }
2647 
2648 
2649 struct wpabuf * crypto_ec_key_get_pubkey_point(struct crypto_ec_key *key,
2650 					       int prefix)
2651 {
2652 	int len, res;
2653 	EC_KEY *eckey;
2654 	struct wpabuf *buf;
2655 	unsigned char *pos;
2656 
2657 	eckey = EVP_PKEY_get1_EC_KEY((EVP_PKEY *) key);
2658 	if (!eckey)
2659 		return NULL;
2660 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_UNCOMPRESSED);
2661 	len = i2o_ECPublicKey(eckey, NULL);
2662 	if (len <= 0) {
2663 		wpa_printf(MSG_ERROR,
2664 			   "OpenSSL: Failed to determine public key encoding length");
2665 		EC_KEY_free(eckey);
2666 		return NULL;
2667 	}
2668 
2669 	buf = wpabuf_alloc(len);
2670 	if (!buf) {
2671 		EC_KEY_free(eckey);
2672 		return NULL;
2673 	}
2674 
2675 	pos = wpabuf_put(buf, len);
2676 	res = i2o_ECPublicKey(eckey, &pos);
2677 	EC_KEY_free(eckey);
2678 	if (res != len) {
2679 		wpa_printf(MSG_ERROR,
2680 			   "OpenSSL: Failed to encode public key (res=%d/%d)",
2681 			   res, len);
2682 		wpabuf_free(buf);
2683 		return NULL;
2684 	}
2685 
2686 	if (!prefix) {
2687 		/* Remove 0x04 prefix if requested */
2688 		pos = wpabuf_mhead(buf);
2689 		os_memmove(pos, pos + 1, len - 1);
2690 		buf->used--;
2691 	}
2692 
2693 	return buf;
2694 }
2695 
2696 
2697 const struct crypto_ec_point *
2698 crypto_ec_key_get_public_key(struct crypto_ec_key *key)
2699 {
2700 	EC_KEY *eckey;
2701 
2702 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
2703 	if (!eckey)
2704 		return NULL;
2705 	return (const struct crypto_ec_point *) EC_KEY_get0_public_key(eckey);
2706 }
2707 
2708 
2709 const struct crypto_bignum *
2710 crypto_ec_key_get_private_key(struct crypto_ec_key *key)
2711 {
2712 	EC_KEY *eckey;
2713 
2714 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
2715 	if (!eckey)
2716 		return NULL;
2717 	return (const struct crypto_bignum *) EC_KEY_get0_private_key(eckey);
2718 }
2719 
2720 
2721 struct wpabuf * crypto_ec_key_sign(struct crypto_ec_key *key, const u8 *data,
2722 				   size_t len)
2723 {
2724 	EVP_PKEY_CTX *pkctx;
2725 	struct wpabuf *sig_der;
2726 	size_t sig_len;
2727 
2728 	sig_len = EVP_PKEY_size((EVP_PKEY *) key);
2729 	sig_der = wpabuf_alloc(sig_len);
2730 	if (!sig_der)
2731 		return NULL;
2732 
2733 	pkctx = EVP_PKEY_CTX_new((EVP_PKEY *) key, NULL);
2734 	if (!pkctx ||
2735 	    EVP_PKEY_sign_init(pkctx) <= 0 ||
2736 	    EVP_PKEY_sign(pkctx, wpabuf_put(sig_der, 0), &sig_len,
2737 			  data, len) <= 0) {
2738 		wpabuf_free(sig_der);
2739 		sig_der = NULL;
2740 	} else {
2741 		wpabuf_put(sig_der, sig_len);
2742 	}
2743 
2744 	EVP_PKEY_CTX_free(pkctx);
2745 	return sig_der;
2746 }
2747 
2748 
2749 struct wpabuf * crypto_ec_key_sign_r_s(struct crypto_ec_key *key,
2750 				       const u8 *data, size_t len)
2751 {
2752 	const EC_GROUP *group;
2753 	const EC_KEY *eckey;
2754 	BIGNUM *prime = NULL;
2755 	ECDSA_SIG *sig = NULL;
2756 	const BIGNUM *r, *s;
2757 	u8 *r_buf, *s_buf;
2758 	struct wpabuf *buf;
2759 	const unsigned char *p;
2760 	int prime_len;
2761 
2762 	buf = crypto_ec_key_sign(key, data, len);
2763 	if (!buf)
2764 		return NULL;
2765 
2766 	/* Extract (r,s) from Ecdsa-Sig-Value */
2767 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
2768 	if (!eckey)
2769 		goto fail;
2770 	group = EC_KEY_get0_group(eckey);
2771 	prime = BN_new();
2772 	if (!prime || !group ||
2773 	    !EC_GROUP_get_curve_GFp(group, prime, NULL, NULL, NULL))
2774 		goto fail;
2775 	prime_len = BN_num_bytes(prime);
2776 
2777 	p = wpabuf_head(buf);
2778 	sig = d2i_ECDSA_SIG(NULL, &p, wpabuf_len(buf));
2779 	if (!sig)
2780 		goto fail;
2781 	ECDSA_SIG_get0(sig, &r, &s);
2782 
2783 	/* Re-use wpabuf returned by crypto_ec_key_sign() */
2784 	buf->used = 0;
2785 	r_buf = wpabuf_put(buf, prime_len);
2786 	s_buf = wpabuf_put(buf, prime_len);
2787 	if (crypto_bignum_to_bin((const struct crypto_bignum *) r, r_buf,
2788 				 prime_len, prime_len) < 0 ||
2789 	    crypto_bignum_to_bin((const struct crypto_bignum *) s, s_buf,
2790 				 prime_len, prime_len) < 0)
2791 		goto fail;
2792 
2793 out:
2794 	BN_free(prime);
2795 	ECDSA_SIG_free(sig);
2796 	return buf;
2797 fail:
2798 	wpabuf_clear_free(buf);
2799 	buf = NULL;
2800 	goto out;
2801 }
2802 
2803 
2804 int crypto_ec_key_verify_signature(struct crypto_ec_key *key, const u8 *data,
2805 				   size_t len, const u8 *sig, size_t sig_len)
2806 {
2807 	EVP_PKEY_CTX *pkctx;
2808 	int ret;
2809 
2810 	pkctx = EVP_PKEY_CTX_new((EVP_PKEY *) key, NULL);
2811 	if (!pkctx || EVP_PKEY_verify_init(pkctx) <= 0) {
2812 		EVP_PKEY_CTX_free(pkctx);
2813 		return -1;
2814 	}
2815 
2816 	ret = EVP_PKEY_verify(pkctx, sig, sig_len, data, len);
2817 	EVP_PKEY_CTX_free(pkctx);
2818 	if (ret == 1)
2819 		return 1; /* signature ok */
2820 	if (ret == 0)
2821 		return 0; /* incorrect signature */
2822 	return -1;
2823 }
2824 
2825 
2826 int crypto_ec_key_verify_signature_r_s(struct crypto_ec_key *key,
2827 				       const u8 *data, size_t len,
2828 				       const u8 *r, size_t r_len,
2829 				       const u8 *s, size_t s_len)
2830 {
2831 	ECDSA_SIG *sig;
2832 	BIGNUM *r_bn, *s_bn;
2833 	unsigned char *der = NULL;
2834 	int der_len;
2835 	int ret = -1;
2836 
2837 	r_bn = BN_bin2bn(r, r_len, NULL);
2838 	s_bn = BN_bin2bn(s, s_len, NULL);
2839 	sig = ECDSA_SIG_new();
2840 	if (!r_bn || !s_bn || !sig || ECDSA_SIG_set0(sig, r_bn, s_bn) != 1)
2841 		goto fail;
2842 	r_bn = NULL;
2843 	s_bn = NULL;
2844 
2845 	der_len = i2d_ECDSA_SIG(sig, &der);
2846 	if (der_len <= 0) {
2847 		wpa_printf(MSG_DEBUG,
2848 			   "OpenSSL: Could not DER encode signature");
2849 		goto fail;
2850 	}
2851 
2852 	ret = crypto_ec_key_verify_signature(key, data, len, der, der_len);
2853 
2854 fail:
2855 	OPENSSL_free(der);
2856 	BN_free(r_bn);
2857 	BN_free(s_bn);
2858 	ECDSA_SIG_free(sig);
2859 	return ret;
2860 }
2861 
2862 
2863 int crypto_ec_key_group(struct crypto_ec_key *key)
2864 {
2865 	const EC_KEY *eckey;
2866 	const EC_GROUP *group;
2867 	int nid;
2868 
2869 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
2870 	if (!eckey)
2871 		return -1;
2872 	group = EC_KEY_get0_group(eckey);
2873 	if (!group)
2874 		return -1;
2875 	nid = EC_GROUP_get_curve_name(group);
2876 	switch (nid) {
2877 	case NID_X9_62_prime256v1:
2878 		return 19;
2879 	case NID_secp384r1:
2880 		return 20;
2881 	case NID_secp521r1:
2882 		return 21;
2883 #ifdef NID_brainpoolP256r1
2884 	case NID_brainpoolP256r1:
2885 		return 28;
2886 #endif /* NID_brainpoolP256r1 */
2887 #ifdef NID_brainpoolP384r1
2888 	case NID_brainpoolP384r1:
2889 		return 29;
2890 #endif /* NID_brainpoolP384r1 */
2891 #ifdef NID_brainpoolP512r1
2892 	case NID_brainpoolP512r1:
2893 		return 30;
2894 #endif /* NID_brainpoolP512r1 */
2895 	}
2896 	wpa_printf(MSG_ERROR, "OpenSSL: Unsupported curve (nid=%d) in EC key",
2897 		   nid);
2898 	return -1;
2899 }
2900 
2901 
2902 int crypto_ec_key_cmp(struct crypto_ec_key *key1, struct crypto_ec_key *key2)
2903 {
2904 	if (EVP_PKEY_cmp((EVP_PKEY *) key1, (EVP_PKEY *) key2) != 1)
2905 		return -1;
2906 	return 0;
2907 }
2908 
2909 
2910 void crypto_ec_key_debug_print(const struct crypto_ec_key *key,
2911 			       const char *title)
2912 {
2913 	BIO *out;
2914 	size_t rlen;
2915 	char *txt;
2916 	int res;
2917 
2918 	out = BIO_new(BIO_s_mem());
2919 	if (!out)
2920 		return;
2921 
2922 	EVP_PKEY_print_private(out, (EVP_PKEY *) key, 0, NULL);
2923 	rlen = BIO_ctrl_pending(out);
2924 	txt = os_malloc(rlen + 1);
2925 	if (txt) {
2926 		res = BIO_read(out, txt, rlen);
2927 		if (res > 0) {
2928 			txt[res] = '\0';
2929 			wpa_printf(MSG_DEBUG, "%s: %s", title, txt);
2930 		}
2931 		os_free(txt);
2932 	}
2933 	BIO_free(out);
2934 }
2935 
2936 
2937 struct wpabuf * crypto_pkcs7_get_certificates(const struct wpabuf *pkcs7)
2938 {
2939 #ifdef OPENSSL_IS_BORINGSSL
2940 	CBS pkcs7_cbs;
2941 #else /* OPENSSL_IS_BORINGSSL */
2942 	PKCS7 *p7 = NULL;
2943 	const unsigned char *p = wpabuf_head(pkcs7);
2944 #endif /* OPENSSL_IS_BORINGSSL */
2945 	STACK_OF(X509) *certs;
2946 	int i, num;
2947 	BIO *out = NULL;
2948 	size_t rlen;
2949 	struct wpabuf *pem = NULL;
2950 	int res;
2951 
2952 #ifdef OPENSSL_IS_BORINGSSL
2953 	certs = sk_X509_new_null();
2954 	if (!certs)
2955 		goto fail;
2956 	CBS_init(&pkcs7_cbs, wpabuf_head(pkcs7), wpabuf_len(pkcs7));
2957 	if (!PKCS7_get_certificates(certs, &pkcs7_cbs)) {
2958 		wpa_printf(MSG_INFO,
2959 			   "OpenSSL: Could not parse PKCS#7 object: %s",
2960 			   ERR_error_string(ERR_get_error(), NULL));
2961 		goto fail;
2962 	}
2963 #else /* OPENSSL_IS_BORINGSSL */
2964 	p7 = d2i_PKCS7(NULL, &p, wpabuf_len(pkcs7));
2965 	if (!p7) {
2966 		wpa_printf(MSG_INFO,
2967 			   "OpenSSL: Could not parse PKCS#7 object: %s",
2968 			   ERR_error_string(ERR_get_error(), NULL));
2969 		goto fail;
2970 	}
2971 
2972 	switch (OBJ_obj2nid(p7->type)) {
2973 	case NID_pkcs7_signed:
2974 		certs = p7->d.sign->cert;
2975 		break;
2976 	case NID_pkcs7_signedAndEnveloped:
2977 		certs = p7->d.signed_and_enveloped->cert;
2978 		break;
2979 	default:
2980 		certs = NULL;
2981 		break;
2982 	}
2983 #endif /* OPENSSL_IS_BORINGSSL */
2984 
2985 	if (!certs || ((num = sk_X509_num(certs)) == 0)) {
2986 		wpa_printf(MSG_INFO,
2987 			   "OpenSSL: No certificates found in PKCS#7 object");
2988 		goto fail;
2989 	}
2990 
2991 	out = BIO_new(BIO_s_mem());
2992 	if (!out)
2993 		goto fail;
2994 
2995 	for (i = 0; i < num; i++) {
2996 		X509 *cert = sk_X509_value(certs, i);
2997 
2998 		PEM_write_bio_X509(out, cert);
2999 	}
3000 
3001 	rlen = BIO_ctrl_pending(out);
3002 	pem = wpabuf_alloc(rlen);
3003 	if (!pem)
3004 		goto fail;
3005 	res = BIO_read(out, wpabuf_put(pem, 0), rlen);
3006 	if (res <= 0) {
3007 		wpabuf_free(pem);
3008 		pem = NULL;
3009 		goto fail;
3010 	}
3011 	wpabuf_put(pem, res);
3012 
3013 fail:
3014 #ifdef OPENSSL_IS_BORINGSSL
3015 	if (certs)
3016 		sk_X509_pop_free(certs, X509_free);
3017 #else /* OPENSSL_IS_BORINGSSL */
3018 	PKCS7_free(p7);
3019 #endif /* OPENSSL_IS_BORINGSSL */
3020 	if (out)
3021 		BIO_free_all(out);
3022 
3023 	return pem;
3024 }
3025 
3026 
3027 struct crypto_csr * crypto_csr_init()
3028 {
3029 	return (struct crypto_csr *)X509_REQ_new();
3030 }
3031 
3032 
3033 struct crypto_csr * crypto_csr_verify(const struct wpabuf *req)
3034 {
3035 	X509_REQ *csr;
3036 	EVP_PKEY *pkey = NULL;
3037 	const u8 *der = wpabuf_head(req);
3038 
3039 	csr = d2i_X509_REQ(NULL, &der, wpabuf_len(req));
3040 	if (!csr)
3041 		return NULL;
3042 
3043 	pkey = X509_REQ_get_pubkey((X509_REQ *)csr);
3044 	if (!pkey)
3045 		goto fail;
3046 
3047 	if (X509_REQ_verify((X509_REQ *)csr, pkey) != 1)
3048 		goto fail;
3049 
3050 	return (struct crypto_csr *)csr;
3051 fail:
3052 	X509_REQ_free(csr);
3053 	return NULL;
3054 }
3055 
3056 
3057 void crypto_csr_deinit(struct crypto_csr *csr)
3058 {
3059 	X509_REQ_free((X509_REQ *)csr);
3060 }
3061 
3062 
3063 int crypto_csr_set_ec_public_key(struct crypto_csr *csr, struct crypto_ec_key *key)
3064 {
3065 	if (!X509_REQ_set_pubkey((X509_REQ *)csr, (EVP_PKEY *)key))
3066 		return -1;
3067 
3068 	return 0;
3069 }
3070 
3071 
3072 int crypto_csr_set_name(struct crypto_csr *csr, enum crypto_csr_name type,
3073 			const char *name)
3074 {
3075 	X509_NAME *n;
3076 	int nid;
3077 
3078 	switch (type) {
3079 	case CSR_NAME_CN:
3080 		nid = NID_commonName;
3081 		break;
3082 	case CSR_NAME_SN:
3083 		nid = NID_surname;
3084 		break;
3085 	case CSR_NAME_C:
3086 		nid = NID_countryName;
3087 		break;
3088 	case CSR_NAME_O:
3089 		nid = NID_organizationName;
3090 		break;
3091 	case CSR_NAME_OU:
3092 		nid = NID_organizationalUnitName;
3093 		break;
3094 	default:
3095 		return -1;
3096 	}
3097 
3098 	n = X509_REQ_get_subject_name((X509_REQ *) csr);
3099 	if (!n)
3100 		return -1;
3101 
3102 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3103 	if (!X509_NAME_add_entry_by_NID(n, nid, MBSTRING_UTF8,
3104 					(unsigned char *) name,
3105 					os_strlen(name), -1, 0))
3106 		return -1;
3107 #else
3108 	if (!X509_NAME_add_entry_by_NID(n, nid, MBSTRING_UTF8,
3109 					(const unsigned char *) name,
3110 					os_strlen(name), -1, 0))
3111 		return -1;
3112 #endif
3113 
3114 	return 0;
3115 }
3116 
3117 
3118 int crypto_csr_set_attribute(struct crypto_csr *csr, enum crypto_csr_attr attr,
3119 			     int attr_type, const u8 *value, size_t len)
3120 {
3121 	int nid;
3122 
3123 	switch (attr) {
3124 	case CSR_ATTR_CHALLENGE_PASSWORD:
3125 		nid = NID_pkcs9_challengePassword;
3126 		break;
3127 	default:
3128 		return -1;
3129 	}
3130 
3131 	if (!X509_REQ_add1_attr_by_NID((X509_REQ *) csr, nid, attr_type, value,
3132 				       len))
3133 		return -1;
3134 
3135 	return 0;
3136 }
3137 
3138 
3139 const u8 * crypto_csr_get_attribute(struct crypto_csr *csr,
3140 				    enum crypto_csr_attr attr,
3141 				    size_t *len, int *type)
3142 {
3143 	X509_ATTRIBUTE *attrib;
3144 	ASN1_TYPE *attrib_type;
3145 	ASN1_STRING *data;
3146 	int loc;
3147 	int nid;
3148 
3149 	switch (attr) {
3150 	case CSR_ATTR_CHALLENGE_PASSWORD:
3151 		nid = NID_pkcs9_challengePassword;
3152 		break;
3153 	default:
3154 		return NULL;
3155 	}
3156 
3157 	loc = X509_REQ_get_attr_by_NID((X509_REQ *) csr, nid, -1);
3158 	if (loc < 0)
3159 		return NULL;
3160 
3161 	attrib = X509_REQ_get_attr((X509_REQ *) csr, loc);
3162 	if (!attrib)
3163 		return NULL;
3164 
3165 	attrib_type = X509_ATTRIBUTE_get0_type(attrib, 0);
3166 	if (!attrib_type)
3167 		return NULL;
3168 	*type = ASN1_TYPE_get(attrib_type);
3169 	data = X509_ATTRIBUTE_get0_data(attrib, 0, *type, NULL);
3170 	if (!data)
3171 		return NULL;
3172 	*len = ASN1_STRING_length(data);
3173 	return ASN1_STRING_get0_data(data);
3174 }
3175 
3176 
3177 struct wpabuf * crypto_csr_sign(struct crypto_csr *csr,
3178 				struct crypto_ec_key *key,
3179 				enum crypto_hash_alg algo)
3180 {
3181 	const EVP_MD *sign_md;
3182 	struct wpabuf *buf;
3183 	unsigned char *der = NULL;
3184 	int der_len;
3185 
3186 	switch (algo) {
3187 	case CRYPTO_HASH_ALG_SHA256:
3188 		sign_md = EVP_sha256();
3189 		break;
3190 	case CRYPTO_HASH_ALG_SHA384:
3191 		sign_md = EVP_sha384();
3192 		break;
3193 	case CRYPTO_HASH_ALG_SHA512:
3194 		sign_md = EVP_sha512();
3195 		break;
3196 	default:
3197 		return NULL;
3198 	}
3199 
3200 	if (!X509_REQ_sign((X509_REQ *) csr, (EVP_PKEY *) key, sign_md))
3201 		return NULL;
3202 
3203 	der_len = i2d_X509_REQ((X509_REQ *) csr, &der);
3204 	if (der_len < 0)
3205 		return NULL;
3206 
3207 	buf = wpabuf_alloc_copy(der, der_len);
3208 	OPENSSL_free(der);
3209 
3210 	return buf;
3211 }
3212 
3213 #endif /* CONFIG_ECC */
3214