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