xref: /freebsd/contrib/wpa/src/crypto/crypto_openssl.c (revision a90b9d0159070121c221b966469c3e36d912bf82)
1 /*
2  * Wrapper functions for OpenSSL libcrypto
3  * Copyright (c) 2004-2024, 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 #include <openssl/rsa.h>
20 #include <openssl/pem.h>
21 #ifdef CONFIG_ECC
22 #include <openssl/ec.h>
23 #include <openssl/x509.h>
24 #endif /* CONFIG_ECC */
25 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
26 #include <openssl/provider.h>
27 #include <openssl/core_names.h>
28 #include <openssl/param_build.h>
29 #include <openssl/encoder.h>
30 #include <openssl/decoder.h>
31 #else /* OpenSSL version >= 3.0 */
32 #include <openssl/cmac.h>
33 #endif /* OpenSSL version >= 3.0 */
34 #ifdef CONFIG_DPP3
35 #if OPENSSL_VERSION_NUMBER >= 0x30200000L
36 #include <openssl/hpke.h>
37 #endif
38 #endif /* CONFIG_DPP3 */
39 
40 #include "common.h"
41 #include "utils/const_time.h"
42 #include "wpabuf.h"
43 #include "dh_group5.h"
44 #include "sha1.h"
45 #include "sha256.h"
46 #include "sha384.h"
47 #include "sha512.h"
48 #include "md5.h"
49 #include "aes_wrap.h"
50 #include "crypto.h"
51 
52 #if OPENSSL_VERSION_NUMBER < 0x10100000L
53 /* Compatibility wrappers for older versions. */
54 
HMAC_CTX_new(void)55 static HMAC_CTX * HMAC_CTX_new(void)
56 {
57 	HMAC_CTX *ctx;
58 
59 	ctx = os_zalloc(sizeof(*ctx));
60 	if (ctx)
61 		HMAC_CTX_init(ctx);
62 	return ctx;
63 }
64 
65 
HMAC_CTX_free(HMAC_CTX * ctx)66 static void HMAC_CTX_free(HMAC_CTX *ctx)
67 {
68 	if (!ctx)
69 		return;
70 	HMAC_CTX_cleanup(ctx);
71 	bin_clear_free(ctx, sizeof(*ctx));
72 }
73 
74 
EVP_MD_CTX_new(void)75 static EVP_MD_CTX * EVP_MD_CTX_new(void)
76 {
77 	EVP_MD_CTX *ctx;
78 
79 	ctx = os_zalloc(sizeof(*ctx));
80 	if (ctx)
81 		EVP_MD_CTX_init(ctx);
82 	return ctx;
83 }
84 
85 
EVP_MD_CTX_free(EVP_MD_CTX * ctx)86 static void EVP_MD_CTX_free(EVP_MD_CTX *ctx)
87 {
88 	if (!ctx)
89 		return;
90 	EVP_MD_CTX_cleanup(ctx);
91 	bin_clear_free(ctx, sizeof(*ctx));
92 }
93 
94 
95 #ifdef CONFIG_ECC
96 
EVP_PKEY_get0_EC_KEY(EVP_PKEY * pkey)97 static EC_KEY * EVP_PKEY_get0_EC_KEY(EVP_PKEY *pkey)
98 {
99 	if (pkey->type != EVP_PKEY_EC)
100 		return NULL;
101 	return pkey->pkey.ec;
102 }
103 
104 
ECDSA_SIG_set0(ECDSA_SIG * sig,BIGNUM * r,BIGNUM * s)105 static int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s)
106 {
107 	sig->r = r;
108 	sig->s = s;
109 	return 1;
110 }
111 
112 
ECDSA_SIG_get0(const ECDSA_SIG * sig,const BIGNUM ** pr,const BIGNUM ** ps)113 static void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr,
114 			   const BIGNUM **ps)
115 {
116 	if (pr)
117 		*pr = sig->r;
118 	if (ps)
119 		*ps = sig->s;
120 }
121 
122 #endif /* CONFIG_ECC */
123 
ASN1_STRING_get0_data(const ASN1_STRING * x)124 static const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
125 {
126 	return ASN1_STRING_data((ASN1_STRING *) x);
127 }
128 
129 
X509_get0_notBefore(const X509 * x)130 static const ASN1_TIME * X509_get0_notBefore(const X509 *x)
131 {
132 	return X509_get_notBefore(x);
133 }
134 
135 
X509_get0_notAfter(const X509 * x)136 static const ASN1_TIME * X509_get0_notAfter(const X509 *x)
137 {
138 	return X509_get_notAfter(x);
139 }
140 
141 #endif /* OpenSSL version < 1.1.0 */
142 
143 
144 #if OPENSSL_VERSION_NUMBER < 0x10101000L || \
145 	(defined(LIBRESSL_VERSION_NUMBER) && \
146 	 LIBRESSL_VERSION_NUMBER < 0x30400000L)
147 
EC_POINT_get_affine_coordinates(const EC_GROUP * group,const EC_POINT * point,BIGNUM * x,BIGNUM * y,BN_CTX * ctx)148 static int EC_POINT_get_affine_coordinates(const EC_GROUP *group,
149 					   const EC_POINT *point, BIGNUM *x,
150 					   BIGNUM *y, BN_CTX *ctx)
151 {
152 	return EC_POINT_get_affine_coordinates_GFp(group, point, x, y, ctx);
153 }
154 
155 
EC_POINT_set_affine_coordinates(const EC_GROUP * group,EC_POINT * point,const BIGNUM * x,const BIGNUM * y,BN_CTX * ctx)156 static int EC_POINT_set_affine_coordinates(const EC_GROUP *group,
157 					   EC_POINT *point, const BIGNUM *x,
158 					   const BIGNUM *y, BN_CTX *ctx)
159 {
160 	return EC_POINT_set_affine_coordinates_GFp(group, point, x, y, ctx);
161 }
162 
163 #endif /* OpenSSL version < 1.1.1 */
164 
165 
166 #if OPENSSL_VERSION_NUMBER < 0x10101000L || \
167 	defined(OPENSSL_IS_BORINGSSL) || \
168 	(defined(LIBRESSL_VERSION_NUMBER) && \
169 	 LIBRESSL_VERSION_NUMBER < 0x30400000L)
170 
EC_POINT_set_compressed_coordinates(const EC_GROUP * group,EC_POINT * point,const BIGNUM * x,int y_bit,BN_CTX * ctx)171 static int EC_POINT_set_compressed_coordinates(const EC_GROUP *group,
172 					       EC_POINT *point, const BIGNUM *x,
173 					       int y_bit, BN_CTX *ctx)
174 {
175 	return EC_POINT_set_compressed_coordinates_GFp(group, point, x, y_bit,
176 						       ctx);
177 }
178 
179 
EC_GROUP_get_curve(const EC_GROUP * group,BIGNUM * p,BIGNUM * a,BIGNUM * b,BN_CTX * ctx)180 static int EC_GROUP_get_curve(const EC_GROUP *group, BIGNUM *p, BIGNUM *a,
181 			      BIGNUM *b, BN_CTX *ctx)
182 {
183 	return EC_GROUP_get_curve_GFp(group, p, a, b, ctx);
184 }
185 
186 #endif /* OpenSSL version < 1.1.1 */
187 
188 
189 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
190 static OSSL_PROVIDER *openssl_legacy_provider = NULL;
191 #endif /* OpenSSL version >= 3.0 */
192 
openssl_load_legacy_provider(void)193 void openssl_load_legacy_provider(void)
194 {
195 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
196 	if (openssl_legacy_provider)
197 		return;
198 
199 	openssl_legacy_provider = OSSL_PROVIDER_try_load(NULL, "legacy", 1);
200 #endif /* OpenSSL version >= 3.0 */
201 }
202 
203 
openssl_unload_legacy_provider(void)204 static void openssl_unload_legacy_provider(void)
205 {
206 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
207 	if (openssl_legacy_provider) {
208 		OSSL_PROVIDER_unload(openssl_legacy_provider);
209 		openssl_legacy_provider = NULL;
210 	}
211 #endif /* OpenSSL version >= 3.0 */
212 }
213 
214 
215 #if OPENSSL_VERSION_NUMBER < 0x30000000L
216 
get_group5_prime(void)217 static BIGNUM * get_group5_prime(void)
218 {
219 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
220 	return BN_get_rfc3526_prime_1536(NULL);
221 #elif !defined(OPENSSL_IS_BORINGSSL)
222 	return get_rfc3526_prime_1536(NULL);
223 #else
224 	static const unsigned char RFC3526_PRIME_1536[] = {
225 		0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xC9,0x0F,0xDA,0xA2,
226 		0x21,0x68,0xC2,0x34,0xC4,0xC6,0x62,0x8B,0x80,0xDC,0x1C,0xD1,
227 		0x29,0x02,0x4E,0x08,0x8A,0x67,0xCC,0x74,0x02,0x0B,0xBE,0xA6,
228 		0x3B,0x13,0x9B,0x22,0x51,0x4A,0x08,0x79,0x8E,0x34,0x04,0xDD,
229 		0xEF,0x95,0x19,0xB3,0xCD,0x3A,0x43,0x1B,0x30,0x2B,0x0A,0x6D,
230 		0xF2,0x5F,0x14,0x37,0x4F,0xE1,0x35,0x6D,0x6D,0x51,0xC2,0x45,
231 		0xE4,0x85,0xB5,0x76,0x62,0x5E,0x7E,0xC6,0xF4,0x4C,0x42,0xE9,
232 		0xA6,0x37,0xED,0x6B,0x0B,0xFF,0x5C,0xB6,0xF4,0x06,0xB7,0xED,
233 		0xEE,0x38,0x6B,0xFB,0x5A,0x89,0x9F,0xA5,0xAE,0x9F,0x24,0x11,
234 		0x7C,0x4B,0x1F,0xE6,0x49,0x28,0x66,0x51,0xEC,0xE4,0x5B,0x3D,
235 		0xC2,0x00,0x7C,0xB8,0xA1,0x63,0xBF,0x05,0x98,0xDA,0x48,0x36,
236 		0x1C,0x55,0xD3,0x9A,0x69,0x16,0x3F,0xA8,0xFD,0x24,0xCF,0x5F,
237 		0x83,0x65,0x5D,0x23,0xDC,0xA3,0xAD,0x96,0x1C,0x62,0xF3,0x56,
238 		0x20,0x85,0x52,0xBB,0x9E,0xD5,0x29,0x07,0x70,0x96,0x96,0x6D,
239 		0x67,0x0C,0x35,0x4E,0x4A,0xBC,0x98,0x04,0xF1,0x74,0x6C,0x08,
240 		0xCA,0x23,0x73,0x27,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
241 	};
242         return BN_bin2bn(RFC3526_PRIME_1536, sizeof(RFC3526_PRIME_1536), NULL);
243 #endif
244 }
245 
246 
get_group5_order(void)247 static BIGNUM * get_group5_order(void)
248 {
249 	static const unsigned char RFC3526_ORDER_1536[] = {
250 		0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xE4,0x87,0xED,0x51,
251 		0x10,0xB4,0x61,0x1A,0x62,0x63,0x31,0x45,0xC0,0x6E,0x0E,0x68,
252 		0x94,0x81,0x27,0x04,0x45,0x33,0xE6,0x3A,0x01,0x05,0xDF,0x53,
253 		0x1D,0x89,0xCD,0x91,0x28,0xA5,0x04,0x3C,0xC7,0x1A,0x02,0x6E,
254 		0xF7,0xCA,0x8C,0xD9,0xE6,0x9D,0x21,0x8D,0x98,0x15,0x85,0x36,
255 		0xF9,0x2F,0x8A,0x1B,0xA7,0xF0,0x9A,0xB6,0xB6,0xA8,0xE1,0x22,
256 		0xF2,0x42,0xDA,0xBB,0x31,0x2F,0x3F,0x63,0x7A,0x26,0x21,0x74,
257 		0xD3,0x1B,0xF6,0xB5,0x85,0xFF,0xAE,0x5B,0x7A,0x03,0x5B,0xF6,
258 		0xF7,0x1C,0x35,0xFD,0xAD,0x44,0xCF,0xD2,0xD7,0x4F,0x92,0x08,
259 		0xBE,0x25,0x8F,0xF3,0x24,0x94,0x33,0x28,0xF6,0x72,0x2D,0x9E,
260 		0xE1,0x00,0x3E,0x5C,0x50,0xB1,0xDF,0x82,0xCC,0x6D,0x24,0x1B,
261 		0x0E,0x2A,0xE9,0xCD,0x34,0x8B,0x1F,0xD4,0x7E,0x92,0x67,0xAF,
262 		0xC1,0xB2,0xAE,0x91,0xEE,0x51,0xD6,0xCB,0x0E,0x31,0x79,0xAB,
263 		0x10,0x42,0xA9,0x5D,0xCF,0x6A,0x94,0x83,0xB8,0x4B,0x4B,0x36,
264 		0xB3,0x86,0x1A,0xA7,0x25,0x5E,0x4C,0x02,0x78,0xBA,0x36,0x04,
265 		0x65,0x11,0xB9,0x93,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
266 	};
267 	return BN_bin2bn(RFC3526_ORDER_1536, sizeof(RFC3526_ORDER_1536), NULL);
268 }
269 
270 #endif /* OpenSSL version < 3.0 */
271 
272 
273 #ifdef OPENSSL_NO_SHA256
274 #define NO_SHA256_WRAPPER
275 #endif
276 #ifdef OPENSSL_NO_SHA512
277 #define NO_SHA384_WRAPPER
278 #endif
279 
openssl_digest_vector(const EVP_MD * type,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)280 static int openssl_digest_vector(const EVP_MD *type, size_t num_elem,
281 				 const u8 *addr[], const size_t *len, u8 *mac)
282 {
283 	EVP_MD_CTX *ctx;
284 	size_t i;
285 	unsigned int mac_len;
286 
287 	if (TEST_FAIL())
288 		return -1;
289 
290 	ctx = EVP_MD_CTX_new();
291 	if (!ctx)
292 		return -1;
293 	if (!EVP_DigestInit_ex(ctx, type, NULL)) {
294 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DigestInit_ex failed: %s",
295 			   ERR_error_string(ERR_get_error(), NULL));
296 		EVP_MD_CTX_free(ctx);
297 		return -1;
298 	}
299 	for (i = 0; i < num_elem; i++) {
300 		if (!EVP_DigestUpdate(ctx, addr[i], len[i])) {
301 			wpa_printf(MSG_ERROR, "OpenSSL: EVP_DigestUpdate "
302 				   "failed: %s",
303 				   ERR_error_string(ERR_get_error(), NULL));
304 			EVP_MD_CTX_free(ctx);
305 			return -1;
306 		}
307 	}
308 	if (!EVP_DigestFinal(ctx, mac, &mac_len)) {
309 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DigestFinal failed: %s",
310 			   ERR_error_string(ERR_get_error(), NULL));
311 		EVP_MD_CTX_free(ctx);
312 		return -1;
313 	}
314 	EVP_MD_CTX_free(ctx);
315 
316 	return 0;
317 }
318 
319 
320 #ifndef CONFIG_FIPS
321 
md4_vector(size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)322 int md4_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
323 {
324 	openssl_load_legacy_provider();
325 	return openssl_digest_vector(EVP_md4(), num_elem, addr, len, mac);
326 }
327 
328 
des_encrypt(const u8 * clear,const u8 * key,u8 * cypher)329 int des_encrypt(const u8 *clear, const u8 *key, u8 *cypher)
330 {
331 	u8 pkey[8], next, tmp;
332 	int i, plen, ret = -1;
333 	EVP_CIPHER_CTX *ctx;
334 
335 	openssl_load_legacy_provider();
336 
337 	/* Add parity bits to the key */
338 	next = 0;
339 	for (i = 0; i < 7; i++) {
340 		tmp = key[i];
341 		pkey[i] = (tmp >> i) | next | 1;
342 		next = tmp << (7 - i);
343 	}
344 	pkey[i] = next | 1;
345 
346 	ctx = EVP_CIPHER_CTX_new();
347 	if (ctx &&
348 	    EVP_EncryptInit_ex(ctx, EVP_des_ecb(), NULL, pkey, NULL) == 1 &&
349 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
350 	    EVP_EncryptUpdate(ctx, cypher, &plen, clear, 8) == 1 &&
351 	    EVP_EncryptFinal_ex(ctx, &cypher[plen], &plen) == 1)
352 		ret = 0;
353 	else
354 		wpa_printf(MSG_ERROR, "OpenSSL: DES encrypt failed");
355 
356 	if (ctx)
357 		EVP_CIPHER_CTX_free(ctx);
358 	return ret;
359 }
360 
361 
362 #ifndef CONFIG_NO_RC4
rc4_skip(const u8 * key,size_t keylen,size_t skip,u8 * data,size_t data_len)363 int rc4_skip(const u8 *key, size_t keylen, size_t skip,
364 	     u8 *data, size_t data_len)
365 {
366 #ifdef OPENSSL_NO_RC4
367 	return -1;
368 #else /* OPENSSL_NO_RC4 */
369 	EVP_CIPHER_CTX *ctx;
370 	int outl;
371 	int res = -1;
372 	unsigned char skip_buf[16];
373 
374 	openssl_load_legacy_provider();
375 
376 	ctx = EVP_CIPHER_CTX_new();
377 	if (!ctx ||
378 	    !EVP_CipherInit_ex(ctx, EVP_rc4(), NULL, NULL, NULL, 1) ||
379 	    !EVP_CIPHER_CTX_set_padding(ctx, 0) ||
380 	    !EVP_CIPHER_CTX_set_key_length(ctx, keylen) ||
381 	    !EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, 1))
382 		goto out;
383 
384 	while (skip >= sizeof(skip_buf)) {
385 		size_t len = skip;
386 		if (len > sizeof(skip_buf))
387 			len = sizeof(skip_buf);
388 		if (!EVP_CipherUpdate(ctx, skip_buf, &outl, skip_buf, len))
389 			goto out;
390 		skip -= len;
391 	}
392 
393 	if (EVP_CipherUpdate(ctx, data, &outl, data, data_len))
394 		res = 0;
395 
396 out:
397 	if (ctx)
398 		EVP_CIPHER_CTX_free(ctx);
399 	return res;
400 #endif /* OPENSSL_NO_RC4 */
401 }
402 #endif /* CONFIG_NO_RC4 */
403 
404 
md5_vector(size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)405 int md5_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
406 {
407 	return openssl_digest_vector(EVP_md5(), num_elem, addr, len, mac);
408 }
409 
410 #endif /* CONFIG_FIPS */
411 
412 
sha1_vector(size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)413 int sha1_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
414 {
415 	return openssl_digest_vector(EVP_sha1(), num_elem, addr, len, mac);
416 }
417 
418 
419 #ifndef NO_SHA256_WRAPPER
sha256_vector(size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)420 int sha256_vector(size_t num_elem, const u8 *addr[], const size_t *len,
421 		  u8 *mac)
422 {
423 	return openssl_digest_vector(EVP_sha256(), num_elem, addr, len, mac);
424 }
425 #endif /* NO_SHA256_WRAPPER */
426 
427 
428 #ifndef NO_SHA384_WRAPPER
sha384_vector(size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)429 int sha384_vector(size_t num_elem, const u8 *addr[], const size_t *len,
430 		  u8 *mac)
431 {
432 	return openssl_digest_vector(EVP_sha384(), num_elem, addr, len, mac);
433 }
434 #endif /* NO_SHA384_WRAPPER */
435 
436 
437 #ifndef NO_SHA512_WRAPPER
sha512_vector(size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)438 int sha512_vector(size_t num_elem, const u8 *addr[], const size_t *len,
439 		  u8 *mac)
440 {
441 	return openssl_digest_vector(EVP_sha512(), num_elem, addr, len, mac);
442 }
443 #endif /* NO_SHA512_WRAPPER */
444 
445 
aes_get_evp_cipher(size_t keylen)446 static const EVP_CIPHER * aes_get_evp_cipher(size_t keylen)
447 {
448 	switch (keylen) {
449 	case 16:
450 		return EVP_aes_128_ecb();
451 	case 24:
452 		return EVP_aes_192_ecb();
453 	case 32:
454 		return EVP_aes_256_ecb();
455 	default:
456 		return NULL;
457 	}
458 }
459 
460 
aes_encrypt_init(const u8 * key,size_t len)461 void * aes_encrypt_init(const u8 *key, size_t len)
462 {
463 	EVP_CIPHER_CTX *ctx;
464 	const EVP_CIPHER *type;
465 
466 	if (TEST_FAIL())
467 		return NULL;
468 
469 	type = aes_get_evp_cipher(len);
470 	if (!type) {
471 		wpa_printf(MSG_INFO, "%s: Unsupported len=%u",
472 			   __func__, (unsigned int) len);
473 		return NULL;
474 	}
475 
476 	ctx = EVP_CIPHER_CTX_new();
477 	if (ctx == NULL)
478 		return NULL;
479 	if (EVP_EncryptInit_ex(ctx, type, NULL, key, NULL) != 1 ||
480 	    EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) {
481 		EVP_CIPHER_CTX_free(ctx);
482 		return NULL;
483 	}
484 	return ctx;
485 }
486 
487 
aes_encrypt(void * ctx,const u8 * plain,u8 * crypt)488 int aes_encrypt(void *ctx, const u8 *plain, u8 *crypt)
489 {
490 	EVP_CIPHER_CTX *c = ctx;
491 	int clen = 16;
492 	if (EVP_EncryptUpdate(c, crypt, &clen, plain, 16) != 1) {
493 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_EncryptUpdate failed: %s",
494 			   ERR_error_string(ERR_get_error(), NULL));
495 		return -1;
496 	}
497 	return 0;
498 }
499 
500 
aes_encrypt_deinit(void * ctx)501 void aes_encrypt_deinit(void *ctx)
502 {
503 	EVP_CIPHER_CTX *c = ctx;
504 	u8 buf[16];
505 	int len = sizeof(buf);
506 	if (EVP_EncryptFinal_ex(c, buf, &len) != 1) {
507 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_EncryptFinal_ex failed: "
508 			   "%s", ERR_error_string(ERR_get_error(), NULL));
509 	}
510 	if (len != 0) {
511 		wpa_printf(MSG_ERROR, "OpenSSL: Unexpected padding length %d "
512 			   "in AES encrypt", len);
513 	}
514 	EVP_CIPHER_CTX_free(c);
515 }
516 
517 
aes_decrypt_init(const u8 * key,size_t len)518 void * aes_decrypt_init(const u8 *key, size_t len)
519 {
520 	EVP_CIPHER_CTX *ctx;
521 	const EVP_CIPHER *type;
522 
523 	if (TEST_FAIL())
524 		return NULL;
525 
526 	type = aes_get_evp_cipher(len);
527 	if (!type) {
528 		wpa_printf(MSG_INFO, "%s: Unsupported len=%u",
529 			   __func__, (unsigned int) len);
530 		return NULL;
531 	}
532 
533 	ctx = EVP_CIPHER_CTX_new();
534 	if (ctx == NULL)
535 		return NULL;
536 	if (EVP_DecryptInit_ex(ctx, type, NULL, key, NULL) != 1 ||
537 	    EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) {
538 		EVP_CIPHER_CTX_free(ctx);
539 		return NULL;
540 	}
541 	return ctx;
542 }
543 
544 
aes_decrypt(void * ctx,const u8 * crypt,u8 * plain)545 int aes_decrypt(void *ctx, const u8 *crypt, u8 *plain)
546 {
547 	EVP_CIPHER_CTX *c = ctx;
548 	int plen = 16;
549 	if (EVP_DecryptUpdate(c, plain, &plen, crypt, 16) != 1) {
550 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DecryptUpdate failed: %s",
551 			   ERR_error_string(ERR_get_error(), NULL));
552 		return -1;
553 	}
554 	return 0;
555 }
556 
557 
aes_decrypt_deinit(void * ctx)558 void aes_decrypt_deinit(void *ctx)
559 {
560 	EVP_CIPHER_CTX *c = ctx;
561 	u8 buf[16];
562 	int len = sizeof(buf);
563 	if (EVP_DecryptFinal_ex(c, buf, &len) != 1) {
564 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_DecryptFinal_ex failed: "
565 			   "%s", ERR_error_string(ERR_get_error(), NULL));
566 	}
567 	if (len != 0) {
568 		wpa_printf(MSG_ERROR, "OpenSSL: Unexpected padding length %d "
569 			   "in AES decrypt", len);
570 	}
571 	EVP_CIPHER_CTX_free(c);
572 }
573 
574 
575 #ifndef CONFIG_FIPS
576 #ifndef CONFIG_OPENSSL_INTERNAL_AES_WRAP
577 
578 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
aes_get_evp_wrap_cipher(size_t keylen)579 static const EVP_CIPHER * aes_get_evp_wrap_cipher(size_t keylen)
580 {
581 	switch (keylen) {
582 	case 16:
583 		return EVP_aes_128_wrap();
584 	case 24:
585 		return EVP_aes_192_wrap();
586 	case 32:
587 		return EVP_aes_256_wrap();
588 	default:
589 		return NULL;
590 	}
591 }
592 #endif /* OpenSSL version >= 3.0 */
593 
594 
aes_wrap(const u8 * kek,size_t kek_len,int n,const u8 * plain,u8 * cipher)595 int aes_wrap(const u8 *kek, size_t kek_len, int n, const u8 *plain, u8 *cipher)
596 {
597 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
598 	EVP_CIPHER_CTX *ctx;
599 	const EVP_CIPHER *type;
600 	int ret = -1, len;
601 	u8 buf[16];
602 
603 	if (TEST_FAIL())
604 		return -1;
605 
606 	type = aes_get_evp_wrap_cipher(kek_len);
607 	if (!type)
608 		return -1;
609 
610 	ctx = EVP_CIPHER_CTX_new();
611 	if (!ctx)
612 		return -1;
613 
614 	if (EVP_EncryptInit_ex(ctx, type, NULL, kek, NULL) == 1 &&
615 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
616 	    EVP_EncryptUpdate(ctx, cipher, &len, plain, n * 8) == 1 &&
617 	    len == (n + 1) * 8 &&
618 	    EVP_EncryptFinal_ex(ctx, buf, &len) == 1)
619 		ret = 0;
620 
621 	EVP_CIPHER_CTX_free(ctx);
622 	return ret;
623 #else /* OpenSSL version >= 3.0 */
624 	AES_KEY actx;
625 	int res;
626 
627 	if (TEST_FAIL())
628 		return -1;
629 	if (AES_set_encrypt_key(kek, kek_len << 3, &actx))
630 		return -1;
631 	res = AES_wrap_key(&actx, NULL, cipher, plain, n * 8);
632 	OPENSSL_cleanse(&actx, sizeof(actx));
633 	return res <= 0 ? -1 : 0;
634 #endif /* OpenSSL version >= 3.0 */
635 }
636 
637 
aes_unwrap(const u8 * kek,size_t kek_len,int n,const u8 * cipher,u8 * plain)638 int aes_unwrap(const u8 *kek, size_t kek_len, int n, const u8 *cipher,
639 	       u8 *plain)
640 {
641 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
642 	EVP_CIPHER_CTX *ctx;
643 	const EVP_CIPHER *type;
644 	int ret = -1, len;
645 	u8 buf[16];
646 
647 	if (TEST_FAIL())
648 		return -1;
649 
650 	type = aes_get_evp_wrap_cipher(kek_len);
651 	if (!type)
652 		return -1;
653 
654 	ctx = EVP_CIPHER_CTX_new();
655 	if (!ctx)
656 		return -1;
657 
658 	if (EVP_DecryptInit_ex(ctx, type, NULL, kek, NULL) == 1 &&
659 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
660 	    EVP_DecryptUpdate(ctx, plain, &len, cipher, (n + 1) * 8) == 1 &&
661 	    len == n * 8 &&
662 	    EVP_DecryptFinal_ex(ctx, buf, &len) == 1)
663 		ret = 0;
664 
665 	EVP_CIPHER_CTX_free(ctx);
666 	return ret;
667 #else /* OpenSSL version >= 3.0 */
668 	AES_KEY actx;
669 	int res;
670 
671 	if (TEST_FAIL())
672 		return -1;
673 	if (AES_set_decrypt_key(kek, kek_len << 3, &actx))
674 		return -1;
675 	res = AES_unwrap_key(&actx, NULL, plain, cipher, (n + 1) * 8);
676 	OPENSSL_cleanse(&actx, sizeof(actx));
677 	return res <= 0 ? -1 : 0;
678 #endif /* OpenSSL version >= 3.0 */
679 }
680 
681 #endif /* CONFIG_OPENSSL_INTERNAL_AES_WRAP */
682 #endif /* CONFIG_FIPS */
683 
684 
aes_128_cbc_encrypt(const u8 * key,const u8 * iv,u8 * data,size_t data_len)685 int aes_128_cbc_encrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
686 {
687 	EVP_CIPHER_CTX *ctx;
688 	int clen, len;
689 	u8 buf[16];
690 	int res = -1;
691 
692 	if (TEST_FAIL())
693 		return -1;
694 
695 	ctx = EVP_CIPHER_CTX_new();
696 	if (!ctx)
697 		return -1;
698 	clen = data_len;
699 	len = sizeof(buf);
700 	if (EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv) == 1 &&
701 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
702 	    EVP_EncryptUpdate(ctx, data, &clen, data, data_len) == 1 &&
703 	    clen == (int) data_len &&
704 	    EVP_EncryptFinal_ex(ctx, buf, &len) == 1 && len == 0)
705 		res = 0;
706 	EVP_CIPHER_CTX_free(ctx);
707 
708 	return res;
709 }
710 
711 
aes_128_cbc_decrypt(const u8 * key,const u8 * iv,u8 * data,size_t data_len)712 int aes_128_cbc_decrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
713 {
714 	EVP_CIPHER_CTX *ctx;
715 	int plen, len;
716 	u8 buf[16];
717 	int res = -1;
718 
719 	if (TEST_FAIL())
720 		return -1;
721 
722 	ctx = EVP_CIPHER_CTX_new();
723 	if (!ctx)
724 		return -1;
725 	plen = data_len;
726 	len = sizeof(buf);
727 	if (EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv) == 1 &&
728 	    EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
729 	    EVP_DecryptUpdate(ctx, data, &plen, data, data_len) == 1 &&
730 	    plen == (int) data_len &&
731 	    EVP_DecryptFinal_ex(ctx, buf, &len) == 1 && len == 0)
732 		res = 0;
733 	EVP_CIPHER_CTX_free(ctx);
734 
735 	return res;
736 
737 }
738 
739 
crypto_dh_init(u8 generator,const u8 * prime,size_t prime_len,u8 * privkey,u8 * pubkey)740 int crypto_dh_init(u8 generator, const u8 *prime, size_t prime_len, u8 *privkey,
741 		   u8 *pubkey)
742 {
743 	size_t pubkey_len, pad;
744 
745 	if (os_get_random(privkey, prime_len) < 0)
746 		return -1;
747 	if (os_memcmp(privkey, prime, prime_len) > 0) {
748 		/* Make sure private value is smaller than prime */
749 		privkey[0] = 0;
750 	}
751 
752 	pubkey_len = prime_len;
753 	if (crypto_mod_exp(&generator, 1, privkey, prime_len, prime, prime_len,
754 			   pubkey, &pubkey_len) < 0)
755 		return -1;
756 	if (pubkey_len < prime_len) {
757 		pad = prime_len - pubkey_len;
758 		os_memmove(pubkey + pad, pubkey, pubkey_len);
759 		os_memset(pubkey, 0, pad);
760 	}
761 
762 	return 0;
763 }
764 
765 
crypto_dh_derive_secret(u8 generator,const u8 * prime,size_t prime_len,const u8 * order,size_t order_len,const u8 * privkey,size_t privkey_len,const u8 * pubkey,size_t pubkey_len,u8 * secret,size_t * len)766 int crypto_dh_derive_secret(u8 generator, const u8 *prime, size_t prime_len,
767 			    const u8 *order, size_t order_len,
768 			    const u8 *privkey, size_t privkey_len,
769 			    const u8 *pubkey, size_t pubkey_len,
770 			    u8 *secret, size_t *len)
771 {
772 	BIGNUM *pub, *p;
773 	int res = -1;
774 
775 	pub = BN_bin2bn(pubkey, pubkey_len, NULL);
776 	p = BN_bin2bn(prime, prime_len, NULL);
777 	if (!pub || !p || BN_is_zero(pub) || BN_is_one(pub) ||
778 	    BN_cmp(pub, p) >= 0)
779 		goto fail;
780 
781 	if (order) {
782 		BN_CTX *ctx;
783 		BIGNUM *q, *tmp;
784 		int failed;
785 
786 		/* verify: pubkey^q == 1 mod p */
787 		q = BN_bin2bn(order, order_len, NULL);
788 		ctx = BN_CTX_new();
789 		tmp = BN_new();
790 		failed = !q || !ctx || !tmp ||
791 			!BN_mod_exp(tmp, pub, q, p, ctx) ||
792 			!BN_is_one(tmp);
793 		BN_clear_free(q);
794 		BN_clear_free(tmp);
795 		BN_CTX_free(ctx);
796 		if (failed)
797 			goto fail;
798 	}
799 
800 	res = crypto_mod_exp(pubkey, pubkey_len, privkey, privkey_len,
801 			     prime, prime_len, secret, len);
802 fail:
803 	BN_clear_free(pub);
804 	BN_clear_free(p);
805 	return res;
806 }
807 
808 
crypto_mod_exp(const u8 * base,size_t base_len,const u8 * power,size_t power_len,const u8 * modulus,size_t modulus_len,u8 * result,size_t * result_len)809 int crypto_mod_exp(const u8 *base, size_t base_len,
810 		   const u8 *power, size_t power_len,
811 		   const u8 *modulus, size_t modulus_len,
812 		   u8 *result, size_t *result_len)
813 {
814 	BIGNUM *bn_base, *bn_exp, *bn_modulus, *bn_result;
815 	int ret = -1;
816 	BN_CTX *ctx;
817 
818 	ctx = BN_CTX_new();
819 	if (ctx == NULL)
820 		return -1;
821 
822 	bn_base = BN_bin2bn(base, base_len, NULL);
823 	bn_exp = BN_bin2bn(power, power_len, NULL);
824 	bn_modulus = BN_bin2bn(modulus, modulus_len, NULL);
825 	bn_result = BN_new();
826 
827 	if (bn_base == NULL || bn_exp == NULL || bn_modulus == NULL ||
828 	    bn_result == NULL)
829 		goto error;
830 
831 	if (BN_mod_exp_mont_consttime(bn_result, bn_base, bn_exp, bn_modulus,
832 				      ctx, NULL) != 1)
833 		goto error;
834 
835 	*result_len = BN_bn2bin(bn_result, result);
836 	ret = 0;
837 
838 error:
839 	BN_clear_free(bn_base);
840 	BN_clear_free(bn_exp);
841 	BN_clear_free(bn_modulus);
842 	BN_clear_free(bn_result);
843 	BN_CTX_free(ctx);
844 	return ret;
845 }
846 
847 
848 struct crypto_cipher {
849 	EVP_CIPHER_CTX *enc;
850 	EVP_CIPHER_CTX *dec;
851 };
852 
853 
crypto_cipher_init(enum crypto_cipher_alg alg,const u8 * iv,const u8 * key,size_t key_len)854 struct crypto_cipher * crypto_cipher_init(enum crypto_cipher_alg alg,
855 					  const u8 *iv, const u8 *key,
856 					  size_t key_len)
857 {
858 	struct crypto_cipher *ctx;
859 	const EVP_CIPHER *cipher;
860 
861 	ctx = os_zalloc(sizeof(*ctx));
862 	if (ctx == NULL)
863 		return NULL;
864 
865 	switch (alg) {
866 #ifndef CONFIG_NO_RC4
867 #ifndef OPENSSL_NO_RC4
868 	case CRYPTO_CIPHER_ALG_RC4:
869 		cipher = EVP_rc4();
870 		break;
871 #endif /* OPENSSL_NO_RC4 */
872 #endif /* CONFIG_NO_RC4 */
873 #ifndef OPENSSL_NO_AES
874 	case CRYPTO_CIPHER_ALG_AES:
875 		switch (key_len) {
876 		case 16:
877 			cipher = EVP_aes_128_cbc();
878 			break;
879 #ifndef OPENSSL_IS_BORINGSSL
880 		case 24:
881 			cipher = EVP_aes_192_cbc();
882 			break;
883 #endif /* OPENSSL_IS_BORINGSSL */
884 		case 32:
885 			cipher = EVP_aes_256_cbc();
886 			break;
887 		default:
888 			os_free(ctx);
889 			return NULL;
890 		}
891 		break;
892 #endif /* OPENSSL_NO_AES */
893 #ifndef OPENSSL_NO_DES
894 	case CRYPTO_CIPHER_ALG_3DES:
895 		cipher = EVP_des_ede3_cbc();
896 		break;
897 	case CRYPTO_CIPHER_ALG_DES:
898 		cipher = EVP_des_cbc();
899 		break;
900 #endif /* OPENSSL_NO_DES */
901 #ifndef OPENSSL_NO_RC2
902 	case CRYPTO_CIPHER_ALG_RC2:
903 		cipher = EVP_rc2_ecb();
904 		break;
905 #endif /* OPENSSL_NO_RC2 */
906 	default:
907 		os_free(ctx);
908 		return NULL;
909 	}
910 
911 	if (!(ctx->enc = EVP_CIPHER_CTX_new()) ||
912 	    !EVP_EncryptInit_ex(ctx->enc, cipher, NULL, NULL, NULL) ||
913 	    !EVP_CIPHER_CTX_set_padding(ctx->enc, 0) ||
914 	    !EVP_CIPHER_CTX_set_key_length(ctx->enc, key_len) ||
915 	    !EVP_EncryptInit_ex(ctx->enc, NULL, NULL, key, iv)) {
916 		if (ctx->enc)
917 			EVP_CIPHER_CTX_free(ctx->enc);
918 		os_free(ctx);
919 		return NULL;
920 	}
921 
922 	if (!(ctx->dec = EVP_CIPHER_CTX_new()) ||
923 	    !EVP_DecryptInit_ex(ctx->dec, cipher, NULL, NULL, NULL) ||
924 	    !EVP_CIPHER_CTX_set_padding(ctx->dec, 0) ||
925 	    !EVP_CIPHER_CTX_set_key_length(ctx->dec, key_len) ||
926 	    !EVP_DecryptInit_ex(ctx->dec, NULL, NULL, key, iv)) {
927 		EVP_CIPHER_CTX_free(ctx->enc);
928 		if (ctx->dec)
929 			EVP_CIPHER_CTX_free(ctx->dec);
930 		os_free(ctx);
931 		return NULL;
932 	}
933 
934 	return ctx;
935 }
936 
937 
crypto_cipher_encrypt(struct crypto_cipher * ctx,const u8 * plain,u8 * crypt,size_t len)938 int crypto_cipher_encrypt(struct crypto_cipher *ctx, const u8 *plain,
939 			  u8 *crypt, size_t len)
940 {
941 	int outl;
942 	if (!EVP_EncryptUpdate(ctx->enc, crypt, &outl, plain, len))
943 		return -1;
944 	return 0;
945 }
946 
947 
crypto_cipher_decrypt(struct crypto_cipher * ctx,const u8 * crypt,u8 * plain,size_t len)948 int crypto_cipher_decrypt(struct crypto_cipher *ctx, const u8 *crypt,
949 			  u8 *plain, size_t len)
950 {
951 	int outl;
952 	outl = len;
953 	if (!EVP_DecryptUpdate(ctx->dec, plain, &outl, crypt, len))
954 		return -1;
955 	return 0;
956 }
957 
958 
crypto_cipher_deinit(struct crypto_cipher * ctx)959 void crypto_cipher_deinit(struct crypto_cipher *ctx)
960 {
961 	EVP_CIPHER_CTX_free(ctx->enc);
962 	EVP_CIPHER_CTX_free(ctx->dec);
963 	os_free(ctx);
964 }
965 
966 
dh5_init(struct wpabuf ** priv,struct wpabuf ** publ)967 void * dh5_init(struct wpabuf **priv, struct wpabuf **publ)
968 {
969 #if OPENSSL_VERSION_NUMBER < 0x10100000L
970 	DH *dh;
971 	struct wpabuf *pubkey = NULL, *privkey = NULL;
972 	size_t publen, privlen;
973 
974 	*priv = NULL;
975 	wpabuf_free(*publ);
976 	*publ = NULL;
977 
978 	dh = DH_new();
979 	if (dh == NULL)
980 		return NULL;
981 
982 	dh->g = BN_new();
983 	if (dh->g == NULL || BN_set_word(dh->g, 2) != 1)
984 		goto err;
985 
986 	dh->p = get_group5_prime();
987 	if (dh->p == NULL)
988 		goto err;
989 
990 	dh->q = get_group5_order();
991 	if (!dh->q)
992 		goto err;
993 
994 	if (DH_generate_key(dh) != 1)
995 		goto err;
996 
997 	publen = BN_num_bytes(dh->pub_key);
998 	pubkey = wpabuf_alloc(publen);
999 	if (pubkey == NULL)
1000 		goto err;
1001 	privlen = BN_num_bytes(dh->priv_key);
1002 	privkey = wpabuf_alloc(privlen);
1003 	if (privkey == NULL)
1004 		goto err;
1005 
1006 	BN_bn2bin(dh->pub_key, wpabuf_put(pubkey, publen));
1007 	BN_bn2bin(dh->priv_key, wpabuf_put(privkey, privlen));
1008 
1009 	*priv = privkey;
1010 	*publ = pubkey;
1011 	return dh;
1012 
1013 err:
1014 	wpabuf_clear_free(pubkey);
1015 	wpabuf_clear_free(privkey);
1016 	DH_free(dh);
1017 	return NULL;
1018 #elif OPENSSL_VERSION_NUMBER >= 0x30000000L
1019 	EVP_PKEY *pkey = NULL;
1020 	OSSL_PARAM params[2];
1021 	size_t pub_len = OSSL_PARAM_UNMODIFIED;
1022 	size_t priv_len;
1023 	struct wpabuf *pubkey = NULL, *privkey = NULL;
1024 	BIGNUM *priv_bn = NULL;
1025 	EVP_PKEY_CTX *gctx;
1026 
1027 	*priv = NULL;
1028 	wpabuf_free(*publ);
1029 	*publ = NULL;
1030 
1031 	params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
1032 						     "modp_1536", 0);
1033 	params[1] = OSSL_PARAM_construct_end();
1034 
1035 	gctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
1036 	if (!gctx ||
1037 	    EVP_PKEY_keygen_init(gctx) != 1 ||
1038 	    EVP_PKEY_CTX_set_params(gctx, params) != 1 ||
1039 	    EVP_PKEY_generate(gctx, &pkey) != 1 ||
1040 	    EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_PRIV_KEY,
1041 				  &priv_bn) != 1 ||
1042 	    EVP_PKEY_get_octet_string_param(pkey,
1043 					    OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1044 					    NULL, 0, &pub_len) < 0 ||
1045 	    pub_len == OSSL_PARAM_UNMODIFIED ||
1046 	    (priv_len = BN_num_bytes(priv_bn)) == 0 ||
1047 	    !(pubkey = wpabuf_alloc(pub_len)) ||
1048 	    !(privkey = wpabuf_alloc(priv_len)) ||
1049 	    EVP_PKEY_get_octet_string_param(pkey,
1050 					    OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1051 					    wpabuf_put(pubkey, pub_len),
1052 					    pub_len, NULL) != 1) {
1053 		wpa_printf(MSG_INFO, "OpenSSL: failed: %s",
1054 			   ERR_error_string(ERR_get_error(), NULL));
1055 		wpabuf_free(pubkey);
1056 		wpabuf_clear_free(privkey);
1057 		EVP_PKEY_free(pkey);
1058 		pkey = NULL;
1059 	} else {
1060 		BN_bn2bin(priv_bn, wpabuf_put(privkey, priv_len));
1061 
1062 		*priv = privkey;
1063 		*publ = pubkey;
1064 	}
1065 
1066 	BN_clear_free(priv_bn);
1067 	EVP_PKEY_CTX_free(gctx);
1068 	return pkey;
1069 #else
1070 	DH *dh;
1071 	struct wpabuf *pubkey = NULL, *privkey = NULL;
1072 	size_t publen, privlen;
1073 	BIGNUM *p, *g, *q;
1074 	const BIGNUM *priv_key = NULL, *pub_key = NULL;
1075 
1076 	*priv = NULL;
1077 	wpabuf_free(*publ);
1078 	*publ = NULL;
1079 
1080 	dh = DH_new();
1081 	if (dh == NULL)
1082 		return NULL;
1083 
1084 	g = BN_new();
1085 	p = get_group5_prime();
1086 	q = get_group5_order();
1087 	if (!g || BN_set_word(g, 2) != 1 || !p || !q ||
1088 	    DH_set0_pqg(dh, p, q, g) != 1)
1089 		goto err;
1090 	p = NULL;
1091 	q = NULL;
1092 	g = NULL;
1093 
1094 	if (DH_generate_key(dh) != 1)
1095 		goto err;
1096 
1097 	DH_get0_key(dh, &pub_key, &priv_key);
1098 	publen = BN_num_bytes(pub_key);
1099 	pubkey = wpabuf_alloc(publen);
1100 	if (!pubkey)
1101 		goto err;
1102 	privlen = BN_num_bytes(priv_key);
1103 	privkey = wpabuf_alloc(privlen);
1104 	if (!privkey)
1105 		goto err;
1106 
1107 	BN_bn2bin(pub_key, wpabuf_put(pubkey, publen));
1108 	BN_bn2bin(priv_key, wpabuf_put(privkey, privlen));
1109 
1110 	*priv = privkey;
1111 	*publ = pubkey;
1112 	return dh;
1113 
1114 err:
1115 	BN_free(p);
1116 	BN_free(q);
1117 	BN_free(g);
1118 	wpabuf_clear_free(pubkey);
1119 	wpabuf_clear_free(privkey);
1120 	DH_free(dh);
1121 	return NULL;
1122 #endif
1123 }
1124 
1125 
dh5_init_fixed(const struct wpabuf * priv,const struct wpabuf * publ)1126 void * dh5_init_fixed(const struct wpabuf *priv, const struct wpabuf *publ)
1127 {
1128 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1129 	DH *dh;
1130 
1131 	dh = DH_new();
1132 	if (dh == NULL)
1133 		return NULL;
1134 
1135 	dh->g = BN_new();
1136 	if (dh->g == NULL || BN_set_word(dh->g, 2) != 1)
1137 		goto err;
1138 
1139 	dh->p = get_group5_prime();
1140 	if (dh->p == NULL)
1141 		goto err;
1142 
1143 	dh->priv_key = BN_bin2bn(wpabuf_head(priv), wpabuf_len(priv), NULL);
1144 	if (dh->priv_key == NULL)
1145 		goto err;
1146 
1147 	dh->pub_key = BN_bin2bn(wpabuf_head(publ), wpabuf_len(publ), NULL);
1148 	if (dh->pub_key == NULL)
1149 		goto err;
1150 
1151 	if (DH_generate_key(dh) != 1)
1152 		goto err;
1153 
1154 	return dh;
1155 
1156 err:
1157 	DH_free(dh);
1158 	return NULL;
1159 #elif OPENSSL_VERSION_NUMBER >= 0x30000000L
1160 	EVP_PKEY *pkey = NULL;
1161 	OSSL_PARAM_BLD *bld;
1162 	OSSL_PARAM *params = NULL;
1163 	BIGNUM *priv_key, *pub_key;
1164 	EVP_PKEY_CTX *fctx;
1165 
1166 	fctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
1167 	priv_key = BN_bin2bn(wpabuf_head(priv), wpabuf_len(priv), NULL);
1168 	pub_key = BN_bin2bn(wpabuf_head(publ), wpabuf_len(publ), NULL);
1169 	bld = OSSL_PARAM_BLD_new();
1170 	if (!fctx || !priv_key || !pub_key || !bld ||
1171 	    OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME,
1172 					    "modp_1536", 0) != 1 ||
1173 	    OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY,
1174 				   priv_key) != 1 ||
1175 	    OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY,
1176 				   pub_key) != 1 ||
1177 	    !(params = OSSL_PARAM_BLD_to_param(bld)) ||
1178 	    EVP_PKEY_fromdata_init(fctx) != 1 ||
1179 	    EVP_PKEY_fromdata(fctx, &pkey, EVP_PKEY_KEYPAIR, params) != 1) {
1180 		wpa_printf(MSG_INFO, "OpenSSL: EVP_PKEY_fromdata failed: %s",
1181 			   ERR_error_string(ERR_get_error(), NULL));
1182 		EVP_PKEY_free(pkey);
1183 		pkey = NULL;
1184 	}
1185 
1186 	BN_clear_free(priv_key);
1187 	BN_free(pub_key);
1188 	EVP_PKEY_CTX_free(fctx);
1189 	OSSL_PARAM_BLD_free(bld);
1190 	OSSL_PARAM_free(params);
1191 	return pkey;
1192 #else
1193 	DH *dh;
1194 	BIGNUM *p = NULL, *g, *priv_key = NULL, *pub_key = NULL;
1195 
1196 	dh = DH_new();
1197 	if (dh == NULL)
1198 		return NULL;
1199 
1200 	g = BN_new();
1201 	p = get_group5_prime();
1202 	if (!g || BN_set_word(g, 2) != 1 || !p ||
1203 	    DH_set0_pqg(dh, p, NULL, g) != 1)
1204 		goto err;
1205 	p = NULL;
1206 	g = NULL;
1207 
1208 	priv_key = BN_bin2bn(wpabuf_head(priv), wpabuf_len(priv), NULL);
1209 	pub_key = BN_bin2bn(wpabuf_head(publ), wpabuf_len(publ), NULL);
1210 	if (!priv_key || !pub_key || DH_set0_key(dh, pub_key, priv_key) != 1)
1211 		goto err;
1212 	pub_key = NULL;
1213 	priv_key = NULL;
1214 
1215 	if (DH_generate_key(dh) != 1)
1216 		goto err;
1217 
1218 	return dh;
1219 
1220 err:
1221 	BN_free(p);
1222 	BN_free(g);
1223 	BN_free(pub_key);
1224 	BN_clear_free(priv_key);
1225 	DH_free(dh);
1226 	return NULL;
1227 #endif
1228 }
1229 
1230 
dh5_derive_shared(void * ctx,const struct wpabuf * peer_public,const struct wpabuf * own_private)1231 struct wpabuf * dh5_derive_shared(void *ctx, const struct wpabuf *peer_public,
1232 				  const struct wpabuf *own_private)
1233 {
1234 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1235 	EVP_PKEY *pkey = ctx;
1236 	EVP_PKEY *peer_pub;
1237 	size_t len;
1238 	struct wpabuf *res = NULL;
1239 	EVP_PKEY_CTX *dctx = NULL;
1240 
1241 	peer_pub = EVP_PKEY_new();
1242 	if (!pkey || !peer_pub ||
1243 	    EVP_PKEY_copy_parameters(peer_pub, pkey) != 1 ||
1244 	    EVP_PKEY_set1_encoded_public_key(peer_pub, wpabuf_head(peer_public),
1245 					     wpabuf_len(peer_public)) != 1 ||
1246 	    !(dctx = EVP_PKEY_CTX_new(pkey, NULL)) ||
1247 	    EVP_PKEY_derive_init(dctx) != 1 ||
1248 	    EVP_PKEY_derive_set_peer(dctx, peer_pub) != 1 ||
1249 	    EVP_PKEY_derive(dctx, NULL, &len) != 1 ||
1250 	    !(res = wpabuf_alloc(len)) ||
1251 	    EVP_PKEY_derive(dctx, wpabuf_mhead(res), &len) != 1) {
1252 		wpa_printf(MSG_INFO, "OpenSSL: EVP_PKEY_derive failed: %s",
1253 			   ERR_error_string(ERR_get_error(), NULL));
1254 		wpabuf_free(res);
1255 		res = NULL;
1256 	} else {
1257 		wpabuf_put(res, len);
1258 	}
1259 
1260 	EVP_PKEY_free(peer_pub);
1261 	EVP_PKEY_CTX_free(dctx);
1262 	return res;
1263 #else /* OpenSSL version >= 3.0 */
1264 	BIGNUM *pub_key;
1265 	struct wpabuf *res = NULL;
1266 	size_t rlen;
1267 	DH *dh = ctx;
1268 	int keylen;
1269 
1270 	if (ctx == NULL)
1271 		return NULL;
1272 
1273 	pub_key = BN_bin2bn(wpabuf_head(peer_public), wpabuf_len(peer_public),
1274 			    NULL);
1275 	if (pub_key == NULL)
1276 		return NULL;
1277 
1278 	rlen = DH_size(dh);
1279 	res = wpabuf_alloc(rlen);
1280 	if (res == NULL)
1281 		goto err;
1282 
1283 	keylen = DH_compute_key(wpabuf_mhead(res), pub_key, dh);
1284 	if (keylen < 0)
1285 		goto err;
1286 	wpabuf_put(res, keylen);
1287 	BN_clear_free(pub_key);
1288 
1289 	return res;
1290 
1291 err:
1292 	BN_clear_free(pub_key);
1293 	wpabuf_clear_free(res);
1294 	return NULL;
1295 #endif /* OpenSSL version >= 3.0 */
1296 }
1297 
1298 
dh5_free(void * ctx)1299 void dh5_free(void *ctx)
1300 {
1301 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1302 	EVP_PKEY *pkey = ctx;
1303 
1304 	EVP_PKEY_free(pkey);
1305 #else /* OpenSSL version >= 3.0 */
1306 	DH *dh;
1307 	if (ctx == NULL)
1308 		return;
1309 	dh = ctx;
1310 	DH_free(dh);
1311 #endif /* OpenSSL version >= 3.0 */
1312 }
1313 
1314 
1315 struct crypto_hash {
1316 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1317 	EVP_MAC_CTX *ctx;
1318 #else /* OpenSSL version >= 3.0 */
1319 	HMAC_CTX *ctx;
1320 #endif /* OpenSSL version >= 3.0 */
1321 	bool failed;
1322 };
1323 
1324 
crypto_hash_init(enum crypto_hash_alg alg,const u8 * key,size_t key_len)1325 struct crypto_hash * crypto_hash_init(enum crypto_hash_alg alg, const u8 *key,
1326 				      size_t key_len)
1327 {
1328 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1329 	struct crypto_hash *ctx;
1330 	EVP_MAC *mac;
1331 	OSSL_PARAM params[2];
1332 	char *a = NULL;
1333 
1334 	switch (alg) {
1335 #ifndef OPENSSL_NO_MD5
1336 	case CRYPTO_HASH_ALG_HMAC_MD5:
1337 		a = "MD5";
1338 		break;
1339 #endif /* OPENSSL_NO_MD5 */
1340 #ifndef OPENSSL_NO_SHA
1341 	case CRYPTO_HASH_ALG_HMAC_SHA1:
1342 		a = "SHA1";
1343 		break;
1344 #endif /* OPENSSL_NO_SHA */
1345 #ifndef OPENSSL_NO_SHA256
1346 #ifdef CONFIG_SHA256
1347 	case CRYPTO_HASH_ALG_HMAC_SHA256:
1348 		a = "SHA256";
1349 		break;
1350 #endif /* CONFIG_SHA256 */
1351 #endif /* OPENSSL_NO_SHA256 */
1352 	default:
1353 		return NULL;
1354 	}
1355 
1356 	mac = EVP_MAC_fetch(NULL, "HMAC", NULL);
1357 	if (!mac)
1358 		return NULL;
1359 
1360 	params[0] = OSSL_PARAM_construct_utf8_string("digest", a, 0);
1361 	params[1] = OSSL_PARAM_construct_end();
1362 
1363 	ctx = os_zalloc(sizeof(*ctx));
1364 	if (!ctx)
1365 		goto fail;
1366 	ctx->ctx = EVP_MAC_CTX_new(mac);
1367 	if (!ctx->ctx) {
1368 		os_free(ctx);
1369 		ctx = NULL;
1370 		goto fail;
1371 	}
1372 
1373 	if (EVP_MAC_init(ctx->ctx, key, key_len, params) != 1) {
1374 		EVP_MAC_CTX_free(ctx->ctx);
1375 		bin_clear_free(ctx, sizeof(*ctx));
1376 		ctx = NULL;
1377 		goto fail;
1378 	}
1379 
1380 fail:
1381 	EVP_MAC_free(mac);
1382 	return ctx;
1383 #else /* OpenSSL version >= 3.0 */
1384 	struct crypto_hash *ctx;
1385 	const EVP_MD *md;
1386 
1387 	switch (alg) {
1388 #ifndef OPENSSL_NO_MD5
1389 	case CRYPTO_HASH_ALG_HMAC_MD5:
1390 		md = EVP_md5();
1391 		break;
1392 #endif /* OPENSSL_NO_MD5 */
1393 #ifndef OPENSSL_NO_SHA
1394 	case CRYPTO_HASH_ALG_HMAC_SHA1:
1395 		md = EVP_sha1();
1396 		break;
1397 #endif /* OPENSSL_NO_SHA */
1398 #ifndef OPENSSL_NO_SHA256
1399 #ifdef CONFIG_SHA256
1400 	case CRYPTO_HASH_ALG_HMAC_SHA256:
1401 		md = EVP_sha256();
1402 		break;
1403 #endif /* CONFIG_SHA256 */
1404 #endif /* OPENSSL_NO_SHA256 */
1405 	default:
1406 		return NULL;
1407 	}
1408 
1409 	ctx = os_zalloc(sizeof(*ctx));
1410 	if (ctx == NULL)
1411 		return NULL;
1412 	ctx->ctx = HMAC_CTX_new();
1413 	if (!ctx->ctx) {
1414 		os_free(ctx);
1415 		return NULL;
1416 	}
1417 
1418 	if (HMAC_Init_ex(ctx->ctx, key, key_len, md, NULL) != 1) {
1419 		HMAC_CTX_free(ctx->ctx);
1420 		bin_clear_free(ctx, sizeof(*ctx));
1421 		return NULL;
1422 	}
1423 
1424 	return ctx;
1425 #endif /* OpenSSL version >= 3.0 */
1426 }
1427 
1428 
crypto_hash_update(struct crypto_hash * ctx,const u8 * data,size_t len)1429 void crypto_hash_update(struct crypto_hash *ctx, const u8 *data, size_t len)
1430 {
1431 	if (ctx == NULL)
1432 		return;
1433 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1434 	if (!EVP_MAC_update(ctx->ctx, data, len))
1435 		ctx->failed = true;
1436 #else /* OpenSSL version >= 3.0 */
1437 	if (!HMAC_Update(ctx->ctx, data, len))
1438 		ctx->failed = true;
1439 #endif /* OpenSSL version >= 3.0 */
1440 }
1441 
1442 
crypto_hash_finish(struct crypto_hash * ctx,u8 * mac,size_t * len)1443 int crypto_hash_finish(struct crypto_hash *ctx, u8 *mac, size_t *len)
1444 {
1445 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1446 	size_t mdlen;
1447 	int res;
1448 	bool failed;
1449 
1450 	if (!ctx)
1451 		return -2;
1452 
1453 	if (!mac || !len) {
1454 		EVP_MAC_CTX_free(ctx->ctx);
1455 		bin_clear_free(ctx, sizeof(*ctx));
1456 		return 0;
1457 	}
1458 
1459 	res = EVP_MAC_final(ctx->ctx, NULL, &mdlen, 0);
1460 	if (res != 1) {
1461 		EVP_MAC_CTX_free(ctx->ctx);
1462 		bin_clear_free(ctx, sizeof(*ctx));
1463 		return -1;
1464 	}
1465 	res = EVP_MAC_final(ctx->ctx, mac, &mdlen, mdlen);
1466 	EVP_MAC_CTX_free(ctx->ctx);
1467 	failed = ctx->failed;
1468 	bin_clear_free(ctx, sizeof(*ctx));
1469 
1470 	if (TEST_FAIL())
1471 		return -1;
1472 
1473 	if (failed)
1474 		return -2;
1475 
1476 	if (res == 1) {
1477 		*len = mdlen;
1478 		return 0;
1479 	}
1480 
1481 	return -1;
1482 #else /* OpenSSL version >= 3.0 */
1483 	unsigned int mdlen;
1484 	int res;
1485 	bool failed;
1486 
1487 	if (ctx == NULL)
1488 		return -2;
1489 
1490 	if (mac == NULL || len == NULL) {
1491 		HMAC_CTX_free(ctx->ctx);
1492 		bin_clear_free(ctx, sizeof(*ctx));
1493 		return 0;
1494 	}
1495 
1496 	mdlen = *len;
1497 	res = HMAC_Final(ctx->ctx, mac, &mdlen);
1498 	HMAC_CTX_free(ctx->ctx);
1499 	failed = ctx->failed;
1500 	bin_clear_free(ctx, sizeof(*ctx));
1501 
1502 	if (TEST_FAIL())
1503 		return -1;
1504 
1505 	if (failed)
1506 		return -2;
1507 
1508 	if (res == 1) {
1509 		*len = mdlen;
1510 		return 0;
1511 	}
1512 
1513 	return -1;
1514 #endif /* OpenSSL version >= 3.0 */
1515 }
1516 
1517 
1518 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1519 
openssl_hmac_vector(char * digest,const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac,unsigned int mdlen)1520 static int openssl_hmac_vector(char *digest, const u8 *key,
1521 			       size_t key_len, size_t num_elem,
1522 			       const u8 *addr[], const size_t *len, u8 *mac,
1523 			       unsigned int mdlen)
1524 {
1525 	EVP_MAC *hmac;
1526 	OSSL_PARAM params[2];
1527 	EVP_MAC_CTX *ctx;
1528 	size_t i, mlen;
1529 	int res;
1530 
1531 	if (TEST_FAIL())
1532 		return -1;
1533 
1534 	hmac = EVP_MAC_fetch(NULL, "HMAC", NULL);
1535 	if (!hmac)
1536 		return -1;
1537 
1538 	params[0] = OSSL_PARAM_construct_utf8_string("digest", digest, 0);
1539 	params[1] = OSSL_PARAM_construct_end();
1540 
1541 	ctx = EVP_MAC_CTX_new(hmac);
1542 	EVP_MAC_free(hmac);
1543 	if (!ctx)
1544 		return -1;
1545 
1546 	if (EVP_MAC_init(ctx, key, key_len, params) != 1)
1547 		goto fail;
1548 
1549 	for (i = 0; i < num_elem; i++) {
1550 		if (EVP_MAC_update(ctx, addr[i], len[i]) != 1)
1551 			goto fail;
1552 	}
1553 
1554 	res = EVP_MAC_final(ctx, mac, &mlen, mdlen);
1555 	EVP_MAC_CTX_free(ctx);
1556 
1557 	return res == 1 ? 0 : -1;
1558 fail:
1559 	EVP_MAC_CTX_free(ctx);
1560 	return -1;
1561 }
1562 
1563 
1564 #ifndef CONFIG_FIPS
1565 
hmac_md5_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1566 int hmac_md5_vector(const u8 *key, size_t key_len, size_t num_elem,
1567 		    const u8 *addr[], const size_t *len, u8 *mac)
1568 {
1569 	return openssl_hmac_vector("MD5", key ,key_len, num_elem, addr, len,
1570 				   mac, 16);
1571 }
1572 
1573 
hmac_md5(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1574 int hmac_md5(const u8 *key, size_t key_len, const u8 *data, size_t data_len,
1575 	     u8 *mac)
1576 {
1577 	return hmac_md5_vector(key, key_len, 1, &data, &data_len, mac);
1578 }
1579 
1580 #endif /* CONFIG_FIPS */
1581 
1582 
hmac_sha1_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1583 int hmac_sha1_vector(const u8 *key, size_t key_len, size_t num_elem,
1584 		     const u8 *addr[], const size_t *len, u8 *mac)
1585 {
1586 	return openssl_hmac_vector("SHA1", key, key_len, num_elem, addr,
1587 				   len, mac, 20);
1588 }
1589 
1590 
hmac_sha1(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1591 int hmac_sha1(const u8 *key, size_t key_len, const u8 *data, size_t data_len,
1592 	       u8 *mac)
1593 {
1594 	return hmac_sha1_vector(key, key_len, 1, &data, &data_len, mac);
1595 }
1596 
1597 
1598 #ifdef CONFIG_SHA256
1599 
hmac_sha256_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1600 int hmac_sha256_vector(const u8 *key, size_t key_len, size_t num_elem,
1601 		       const u8 *addr[], const size_t *len, u8 *mac)
1602 {
1603 	return openssl_hmac_vector("SHA256", key, key_len, num_elem, addr,
1604 				   len, mac, 32);
1605 }
1606 
1607 
hmac_sha256(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1608 int hmac_sha256(const u8 *key, size_t key_len, const u8 *data,
1609 		size_t data_len, u8 *mac)
1610 {
1611 	return hmac_sha256_vector(key, key_len, 1, &data, &data_len, mac);
1612 }
1613 
1614 #endif /* CONFIG_SHA256 */
1615 
1616 
1617 #ifdef CONFIG_SHA384
1618 
hmac_sha384_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1619 int hmac_sha384_vector(const u8 *key, size_t key_len, size_t num_elem,
1620 		       const u8 *addr[], const size_t *len, u8 *mac)
1621 {
1622 	return openssl_hmac_vector("SHA384", key, key_len, num_elem, addr,
1623 				   len, mac, 48);
1624 }
1625 
1626 
hmac_sha384(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1627 int hmac_sha384(const u8 *key, size_t key_len, const u8 *data,
1628 		size_t data_len, u8 *mac)
1629 {
1630 	return hmac_sha384_vector(key, key_len, 1, &data, &data_len, mac);
1631 }
1632 
1633 #endif /* CONFIG_SHA384 */
1634 
1635 
1636 #ifdef CONFIG_SHA512
1637 
hmac_sha512_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1638 int hmac_sha512_vector(const u8 *key, size_t key_len, size_t num_elem,
1639 		       const u8 *addr[], const size_t *len, u8 *mac)
1640 {
1641 	return openssl_hmac_vector("SHA512", key, key_len, num_elem, addr,
1642 				   len, mac, 64);
1643 }
1644 
1645 
hmac_sha512(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1646 int hmac_sha512(const u8 *key, size_t key_len, const u8 *data,
1647 		size_t data_len, u8 *mac)
1648 {
1649 	return hmac_sha512_vector(key, key_len, 1, &data, &data_len, mac);
1650 }
1651 
1652 #endif /* CONFIG_SHA512 */
1653 
1654 #else /* OpenSSL version >= 3.0 */
1655 
openssl_hmac_vector(const EVP_MD * type,const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac,unsigned int mdlen)1656 static int openssl_hmac_vector(const EVP_MD *type, const u8 *key,
1657 			       size_t key_len, size_t num_elem,
1658 			       const u8 *addr[], const size_t *len, u8 *mac,
1659 			       unsigned int mdlen)
1660 {
1661 	HMAC_CTX *ctx;
1662 	size_t i;
1663 	int res;
1664 
1665 	if (TEST_FAIL())
1666 		return -1;
1667 
1668 	ctx = HMAC_CTX_new();
1669 	if (!ctx)
1670 		return -1;
1671 	res = HMAC_Init_ex(ctx, key, key_len, type, NULL);
1672 	if (res != 1)
1673 		goto done;
1674 
1675 	for (i = 0; i < num_elem; i++)
1676 		HMAC_Update(ctx, addr[i], len[i]);
1677 
1678 	res = HMAC_Final(ctx, mac, &mdlen);
1679 done:
1680 	HMAC_CTX_free(ctx);
1681 
1682 	return res == 1 ? 0 : -1;
1683 }
1684 
1685 
1686 #ifndef CONFIG_FIPS
1687 
hmac_md5_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1688 int hmac_md5_vector(const u8 *key, size_t key_len, size_t num_elem,
1689 		    const u8 *addr[], const size_t *len, u8 *mac)
1690 {
1691 	return openssl_hmac_vector(EVP_md5(), key ,key_len, num_elem, addr, len,
1692 				   mac, 16);
1693 }
1694 
1695 
hmac_md5(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1696 int hmac_md5(const u8 *key, size_t key_len, const u8 *data, size_t data_len,
1697 	     u8 *mac)
1698 {
1699 	return hmac_md5_vector(key, key_len, 1, &data, &data_len, mac);
1700 }
1701 
1702 #endif /* CONFIG_FIPS */
1703 
1704 
hmac_sha1_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1705 int hmac_sha1_vector(const u8 *key, size_t key_len, size_t num_elem,
1706 		     const u8 *addr[], const size_t *len, u8 *mac)
1707 {
1708 	return openssl_hmac_vector(EVP_sha1(), key, key_len, num_elem, addr,
1709 				   len, mac, 20);
1710 }
1711 
1712 
hmac_sha1(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1713 int hmac_sha1(const u8 *key, size_t key_len, const u8 *data, size_t data_len,
1714 	       u8 *mac)
1715 {
1716 	return hmac_sha1_vector(key, key_len, 1, &data, &data_len, mac);
1717 }
1718 
1719 
1720 #ifdef CONFIG_SHA256
1721 
hmac_sha256_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1722 int hmac_sha256_vector(const u8 *key, size_t key_len, size_t num_elem,
1723 		       const u8 *addr[], const size_t *len, u8 *mac)
1724 {
1725 	return openssl_hmac_vector(EVP_sha256(), key, key_len, num_elem, addr,
1726 				   len, mac, 32);
1727 }
1728 
1729 
hmac_sha256(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1730 int hmac_sha256(const u8 *key, size_t key_len, const u8 *data,
1731 		size_t data_len, u8 *mac)
1732 {
1733 	return hmac_sha256_vector(key, key_len, 1, &data, &data_len, mac);
1734 }
1735 
1736 #endif /* CONFIG_SHA256 */
1737 
1738 
1739 #ifdef CONFIG_SHA384
1740 
hmac_sha384_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1741 int hmac_sha384_vector(const u8 *key, size_t key_len, size_t num_elem,
1742 		       const u8 *addr[], const size_t *len, u8 *mac)
1743 {
1744 	return openssl_hmac_vector(EVP_sha384(), key, key_len, num_elem, addr,
1745 				   len, mac, 48);
1746 }
1747 
1748 
hmac_sha384(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1749 int hmac_sha384(const u8 *key, size_t key_len, const u8 *data,
1750 		size_t data_len, u8 *mac)
1751 {
1752 	return hmac_sha384_vector(key, key_len, 1, &data, &data_len, mac);
1753 }
1754 
1755 #endif /* CONFIG_SHA384 */
1756 
1757 
1758 #ifdef CONFIG_SHA512
1759 
hmac_sha512_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1760 int hmac_sha512_vector(const u8 *key, size_t key_len, size_t num_elem,
1761 		       const u8 *addr[], const size_t *len, u8 *mac)
1762 {
1763 	return openssl_hmac_vector(EVP_sha512(), key, key_len, num_elem, addr,
1764 				   len, mac, 64);
1765 }
1766 
1767 
hmac_sha512(const u8 * key,size_t key_len,const u8 * data,size_t data_len,u8 * mac)1768 int hmac_sha512(const u8 *key, size_t key_len, const u8 *data,
1769 		size_t data_len, u8 *mac)
1770 {
1771 	return hmac_sha512_vector(key, key_len, 1, &data, &data_len, mac);
1772 }
1773 
1774 #endif /* CONFIG_SHA512 */
1775 
1776 #endif /* OpenSSL version >= 3.0 */
1777 
1778 
pbkdf2_sha1(const char * passphrase,const u8 * ssid,size_t ssid_len,int iterations,u8 * buf,size_t buflen)1779 int pbkdf2_sha1(const char *passphrase, const u8 *ssid, size_t ssid_len,
1780 		int iterations, u8 *buf, size_t buflen)
1781 {
1782 	if (PKCS5_PBKDF2_HMAC_SHA1(passphrase, os_strlen(passphrase), ssid,
1783 				   ssid_len, iterations, buflen, buf) != 1)
1784 		return -1;
1785 	return 0;
1786 }
1787 
1788 
crypto_get_random(void * buf,size_t len)1789 int crypto_get_random(void *buf, size_t len)
1790 {
1791 	if (RAND_bytes(buf, len) != 1)
1792 		return -1;
1793 	return 0;
1794 }
1795 
1796 
omac1_aes_vector(const u8 * key,size_t key_len,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1797 int omac1_aes_vector(const u8 *key, size_t key_len, size_t num_elem,
1798 		     const u8 *addr[], const size_t *len, u8 *mac)
1799 {
1800 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1801 	EVP_MAC_CTX *ctx = NULL;
1802 	EVP_MAC *emac;
1803 	int ret = -1;
1804 	size_t outlen, i;
1805 	OSSL_PARAM params[2];
1806 	char *cipher = NULL;
1807 
1808 	if (TEST_FAIL())
1809 		return -1;
1810 
1811 	emac = EVP_MAC_fetch(NULL, "CMAC", NULL);
1812 
1813 	if (key_len == 32)
1814 		cipher = "aes-256-cbc";
1815 	else if (key_len == 24)
1816 		cipher = "aes-192-cbc";
1817 	else if (key_len == 16)
1818 		cipher = "aes-128-cbc";
1819 
1820 	params[0] = OSSL_PARAM_construct_utf8_string("cipher", cipher, 0);
1821 	params[1] = OSSL_PARAM_construct_end();
1822 
1823 	if (!emac || !cipher ||
1824 	    !(ctx = EVP_MAC_CTX_new(emac)) ||
1825 	    EVP_MAC_init(ctx, key, key_len, params) != 1)
1826 		goto fail;
1827 
1828 	for (i = 0; i < num_elem; i++) {
1829 		if (!EVP_MAC_update(ctx, addr[i], len[i]))
1830 			goto fail;
1831 	}
1832 	if (EVP_MAC_final(ctx, mac, &outlen, 16) != 1 || outlen != 16)
1833 		goto fail;
1834 
1835 	ret = 0;
1836 fail:
1837 	EVP_MAC_CTX_free(ctx);
1838 	EVP_MAC_free(emac);
1839 	return ret;
1840 #else /* OpenSSL version >= 3.0 */
1841 	CMAC_CTX *ctx;
1842 	int ret = -1;
1843 	size_t outlen, i;
1844 
1845 	if (TEST_FAIL())
1846 		return -1;
1847 
1848 	ctx = CMAC_CTX_new();
1849 	if (ctx == NULL)
1850 		return -1;
1851 
1852 	if (key_len == 32) {
1853 		if (!CMAC_Init(ctx, key, 32, EVP_aes_256_cbc(), NULL))
1854 			goto fail;
1855 	} else if (key_len == 24) {
1856 		if (!CMAC_Init(ctx, key, 24, EVP_aes_192_cbc(), NULL))
1857 			goto fail;
1858 	} else if (key_len == 16) {
1859 		if (!CMAC_Init(ctx, key, 16, EVP_aes_128_cbc(), NULL))
1860 			goto fail;
1861 	} else {
1862 		goto fail;
1863 	}
1864 	for (i = 0; i < num_elem; i++) {
1865 		if (!CMAC_Update(ctx, addr[i], len[i]))
1866 			goto fail;
1867 	}
1868 	if (!CMAC_Final(ctx, mac, &outlen) || outlen != 16)
1869 		goto fail;
1870 
1871 	ret = 0;
1872 fail:
1873 	CMAC_CTX_free(ctx);
1874 	return ret;
1875 #endif /* OpenSSL version >= 3.0 */
1876 }
1877 
1878 
omac1_aes_128_vector(const u8 * key,size_t num_elem,const u8 * addr[],const size_t * len,u8 * mac)1879 int omac1_aes_128_vector(const u8 *key, size_t num_elem,
1880 			 const u8 *addr[], const size_t *len, u8 *mac)
1881 {
1882 	return omac1_aes_vector(key, 16, num_elem, addr, len, mac);
1883 }
1884 
1885 
omac1_aes_128(const u8 * key,const u8 * data,size_t data_len,u8 * mac)1886 int omac1_aes_128(const u8 *key, const u8 *data, size_t data_len, u8 *mac)
1887 {
1888 	return omac1_aes_128_vector(key, 1, &data, &data_len, mac);
1889 }
1890 
1891 
omac1_aes_256(const u8 * key,const u8 * data,size_t data_len,u8 * mac)1892 int omac1_aes_256(const u8 *key, const u8 *data, size_t data_len, u8 *mac)
1893 {
1894 	return omac1_aes_vector(key, 32, 1, &data, &data_len, mac);
1895 }
1896 
1897 
crypto_bignum_init(void)1898 struct crypto_bignum * crypto_bignum_init(void)
1899 {
1900 	if (TEST_FAIL())
1901 		return NULL;
1902 	return (struct crypto_bignum *) BN_new();
1903 }
1904 
1905 
crypto_bignum_init_set(const u8 * buf,size_t len)1906 struct crypto_bignum * crypto_bignum_init_set(const u8 *buf, size_t len)
1907 {
1908 	BIGNUM *bn;
1909 
1910 	if (TEST_FAIL())
1911 		return NULL;
1912 
1913 	bn = BN_bin2bn(buf, len, NULL);
1914 	return (struct crypto_bignum *) bn;
1915 }
1916 
1917 
crypto_bignum_init_uint(unsigned int val)1918 struct crypto_bignum * crypto_bignum_init_uint(unsigned int val)
1919 {
1920 	BIGNUM *bn;
1921 
1922 	if (TEST_FAIL())
1923 		return NULL;
1924 
1925 	bn = BN_new();
1926 	if (!bn)
1927 		return NULL;
1928 	if (BN_set_word(bn, val) != 1) {
1929 		BN_free(bn);
1930 		return NULL;
1931 	}
1932 	return (struct crypto_bignum *) bn;
1933 }
1934 
1935 
crypto_bignum_deinit(struct crypto_bignum * n,int clear)1936 void crypto_bignum_deinit(struct crypto_bignum *n, int clear)
1937 {
1938 	if (clear)
1939 		BN_clear_free((BIGNUM *) n);
1940 	else
1941 		BN_free((BIGNUM *) n);
1942 }
1943 
1944 
crypto_bignum_to_bin(const struct crypto_bignum * a,u8 * buf,size_t buflen,size_t padlen)1945 int crypto_bignum_to_bin(const struct crypto_bignum *a,
1946 			 u8 *buf, size_t buflen, size_t padlen)
1947 {
1948 	int num_bytes, offset;
1949 
1950 	if (TEST_FAIL())
1951 		return -1;
1952 
1953 	if (padlen > buflen)
1954 		return -1;
1955 
1956 	if (padlen) {
1957 #ifdef OPENSSL_IS_BORINGSSL
1958 		if (BN_bn2bin_padded(buf, padlen, (const BIGNUM *) a) == 0)
1959 			return -1;
1960 		return padlen;
1961 #else /* OPENSSL_IS_BORINGSSL */
1962 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
1963 		return BN_bn2binpad((const BIGNUM *) a, buf, padlen);
1964 #endif
1965 #endif
1966 	}
1967 
1968 	num_bytes = BN_num_bytes((const BIGNUM *) a);
1969 	if ((size_t) num_bytes > buflen)
1970 		return -1;
1971 	if (padlen > (size_t) num_bytes)
1972 		offset = padlen - num_bytes;
1973 	else
1974 		offset = 0;
1975 
1976 	os_memset(buf, 0, offset);
1977 	BN_bn2bin((const BIGNUM *) a, buf + offset);
1978 
1979 	return num_bytes + offset;
1980 }
1981 
1982 
crypto_bignum_rand(struct crypto_bignum * r,const struct crypto_bignum * m)1983 int crypto_bignum_rand(struct crypto_bignum *r, const struct crypto_bignum *m)
1984 {
1985 	if (TEST_FAIL())
1986 		return -1;
1987 	return BN_rand_range((BIGNUM *) r, (const BIGNUM *) m) == 1 ? 0 : -1;
1988 }
1989 
1990 
crypto_bignum_add(const struct crypto_bignum * a,const struct crypto_bignum * b,struct crypto_bignum * c)1991 int crypto_bignum_add(const struct crypto_bignum *a,
1992 		      const struct crypto_bignum *b,
1993 		      struct crypto_bignum *c)
1994 {
1995 	return BN_add((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b) ?
1996 		0 : -1;
1997 }
1998 
1999 
crypto_bignum_mod(const struct crypto_bignum * a,const struct crypto_bignum * b,struct crypto_bignum * c)2000 int crypto_bignum_mod(const struct crypto_bignum *a,
2001 		      const struct crypto_bignum *b,
2002 		      struct crypto_bignum *c)
2003 {
2004 	int res;
2005 	BN_CTX *bnctx;
2006 
2007 	bnctx = BN_CTX_new();
2008 	if (bnctx == NULL)
2009 		return -1;
2010 	res = BN_mod((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b,
2011 		     bnctx);
2012 	BN_CTX_free(bnctx);
2013 
2014 	return res ? 0 : -1;
2015 }
2016 
2017 
crypto_bignum_exptmod(const struct crypto_bignum * a,const struct crypto_bignum * b,const struct crypto_bignum * c,struct crypto_bignum * d)2018 int crypto_bignum_exptmod(const struct crypto_bignum *a,
2019 			  const struct crypto_bignum *b,
2020 			  const struct crypto_bignum *c,
2021 			  struct crypto_bignum *d)
2022 {
2023 	int res;
2024 	BN_CTX *bnctx;
2025 
2026 	if (TEST_FAIL())
2027 		return -1;
2028 
2029 	bnctx = BN_CTX_new();
2030 	if (bnctx == NULL)
2031 		return -1;
2032 	res = BN_mod_exp_mont_consttime((BIGNUM *) d, (const BIGNUM *) a,
2033 					(const BIGNUM *) b, (const BIGNUM *) c,
2034 					bnctx, NULL);
2035 	BN_CTX_free(bnctx);
2036 
2037 	return res ? 0 : -1;
2038 }
2039 
2040 
crypto_bignum_inverse(const struct crypto_bignum * a,const struct crypto_bignum * b,struct crypto_bignum * c)2041 int crypto_bignum_inverse(const struct crypto_bignum *a,
2042 			  const struct crypto_bignum *b,
2043 			  struct crypto_bignum *c)
2044 {
2045 	BIGNUM *res;
2046 	BN_CTX *bnctx;
2047 
2048 	if (TEST_FAIL())
2049 		return -1;
2050 	bnctx = BN_CTX_new();
2051 	if (bnctx == NULL)
2052 		return -1;
2053 #ifdef OPENSSL_IS_BORINGSSL
2054 	/* TODO: use BN_mod_inverse_blinded() ? */
2055 #else /* OPENSSL_IS_BORINGSSL */
2056 	BN_set_flags((BIGNUM *) a, BN_FLG_CONSTTIME);
2057 #endif /* OPENSSL_IS_BORINGSSL */
2058 	res = BN_mod_inverse((BIGNUM *) c, (const BIGNUM *) a,
2059 			     (const BIGNUM *) b, bnctx);
2060 	BN_CTX_free(bnctx);
2061 
2062 	return res ? 0 : -1;
2063 }
2064 
2065 
crypto_bignum_sub(const struct crypto_bignum * a,const struct crypto_bignum * b,struct crypto_bignum * c)2066 int crypto_bignum_sub(const struct crypto_bignum *a,
2067 		      const struct crypto_bignum *b,
2068 		      struct crypto_bignum *c)
2069 {
2070 	if (TEST_FAIL())
2071 		return -1;
2072 	return BN_sub((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b) ?
2073 		0 : -1;
2074 }
2075 
2076 
crypto_bignum_div(const struct crypto_bignum * a,const struct crypto_bignum * b,struct crypto_bignum * c)2077 int crypto_bignum_div(const struct crypto_bignum *a,
2078 		      const struct crypto_bignum *b,
2079 		      struct crypto_bignum *c)
2080 {
2081 	int res;
2082 
2083 	BN_CTX *bnctx;
2084 
2085 	if (TEST_FAIL())
2086 		return -1;
2087 
2088 	bnctx = BN_CTX_new();
2089 	if (bnctx == NULL)
2090 		return -1;
2091 #ifndef OPENSSL_IS_BORINGSSL
2092 	BN_set_flags((BIGNUM *) a, BN_FLG_CONSTTIME);
2093 #endif /* OPENSSL_IS_BORINGSSL */
2094 	res = BN_div((BIGNUM *) c, NULL, (const BIGNUM *) a,
2095 		     (const BIGNUM *) b, bnctx);
2096 	BN_CTX_free(bnctx);
2097 
2098 	return res ? 0 : -1;
2099 }
2100 
2101 
crypto_bignum_addmod(const struct crypto_bignum * a,const struct crypto_bignum * b,const struct crypto_bignum * c,struct crypto_bignum * d)2102 int crypto_bignum_addmod(const struct crypto_bignum *a,
2103 			 const struct crypto_bignum *b,
2104 			 const struct crypto_bignum *c,
2105 			 struct crypto_bignum *d)
2106 {
2107 	int res;
2108 	BN_CTX *bnctx;
2109 
2110 	if (TEST_FAIL())
2111 		return -1;
2112 
2113 	bnctx = BN_CTX_new();
2114 	if (!bnctx)
2115 		return -1;
2116 	res = BN_mod_add((BIGNUM *) d, (const BIGNUM *) a, (const BIGNUM *) b,
2117 			 (const BIGNUM *) c, bnctx);
2118 	BN_CTX_free(bnctx);
2119 
2120 	return res ? 0 : -1;
2121 }
2122 
2123 
crypto_bignum_mulmod(const struct crypto_bignum * a,const struct crypto_bignum * b,const struct crypto_bignum * c,struct crypto_bignum * d)2124 int crypto_bignum_mulmod(const struct crypto_bignum *a,
2125 			 const struct crypto_bignum *b,
2126 			 const struct crypto_bignum *c,
2127 			 struct crypto_bignum *d)
2128 {
2129 	int res;
2130 
2131 	BN_CTX *bnctx;
2132 
2133 	if (TEST_FAIL())
2134 		return -1;
2135 
2136 	bnctx = BN_CTX_new();
2137 	if (bnctx == NULL)
2138 		return -1;
2139 	res = BN_mod_mul((BIGNUM *) d, (const BIGNUM *) a, (const BIGNUM *) b,
2140 			 (const BIGNUM *) c, bnctx);
2141 	BN_CTX_free(bnctx);
2142 
2143 	return res ? 0 : -1;
2144 }
2145 
2146 
crypto_bignum_sqrmod(const struct crypto_bignum * a,const struct crypto_bignum * b,struct crypto_bignum * c)2147 int crypto_bignum_sqrmod(const struct crypto_bignum *a,
2148 			 const struct crypto_bignum *b,
2149 			 struct crypto_bignum *c)
2150 {
2151 	int res;
2152 	BN_CTX *bnctx;
2153 
2154 	if (TEST_FAIL())
2155 		return -1;
2156 
2157 	bnctx = BN_CTX_new();
2158 	if (!bnctx)
2159 		return -1;
2160 	res = BN_mod_sqr((BIGNUM *) c, (const BIGNUM *) a, (const BIGNUM *) b,
2161 			 bnctx);
2162 	BN_CTX_free(bnctx);
2163 
2164 	return res ? 0 : -1;
2165 }
2166 
2167 
crypto_bignum_rshift(const struct crypto_bignum * a,int n,struct crypto_bignum * r)2168 int crypto_bignum_rshift(const struct crypto_bignum *a, int n,
2169 			 struct crypto_bignum *r)
2170 {
2171 	return BN_rshift((BIGNUM *) r, (const BIGNUM *) a, n) == 1 ? 0 : -1;
2172 }
2173 
2174 
crypto_bignum_cmp(const struct crypto_bignum * a,const struct crypto_bignum * b)2175 int crypto_bignum_cmp(const struct crypto_bignum *a,
2176 		      const struct crypto_bignum *b)
2177 {
2178 	return BN_cmp((const BIGNUM *) a, (const BIGNUM *) b);
2179 }
2180 
2181 
crypto_bignum_is_zero(const struct crypto_bignum * a)2182 int crypto_bignum_is_zero(const struct crypto_bignum *a)
2183 {
2184 	return BN_is_zero((const BIGNUM *) a);
2185 }
2186 
2187 
crypto_bignum_is_one(const struct crypto_bignum * a)2188 int crypto_bignum_is_one(const struct crypto_bignum *a)
2189 {
2190 	return BN_is_one((const BIGNUM *) a);
2191 }
2192 
2193 
crypto_bignum_is_odd(const struct crypto_bignum * a)2194 int crypto_bignum_is_odd(const struct crypto_bignum *a)
2195 {
2196 	return BN_is_odd((const BIGNUM *) a);
2197 }
2198 
2199 
crypto_bignum_legendre(const struct crypto_bignum * a,const struct crypto_bignum * p)2200 int crypto_bignum_legendre(const struct crypto_bignum *a,
2201 			   const struct crypto_bignum *p)
2202 {
2203 	BN_CTX *bnctx;
2204 	BIGNUM *exp = NULL, *tmp = NULL;
2205 	int res = -2;
2206 	unsigned int mask;
2207 
2208 	if (TEST_FAIL())
2209 		return -2;
2210 
2211 	bnctx = BN_CTX_new();
2212 	if (bnctx == NULL)
2213 		return -2;
2214 
2215 	exp = BN_new();
2216 	tmp = BN_new();
2217 	if (!exp || !tmp ||
2218 	    /* exp = (p-1) / 2 */
2219 	    !BN_sub(exp, (const BIGNUM *) p, BN_value_one()) ||
2220 	    !BN_rshift1(exp, exp) ||
2221 	    !BN_mod_exp_mont_consttime(tmp, (const BIGNUM *) a, exp,
2222 				       (const BIGNUM *) p, bnctx, NULL))
2223 		goto fail;
2224 
2225 	/* Return 1 if tmp == 1, 0 if tmp == 0, or -1 otherwise. Need to use
2226 	 * constant time selection to avoid branches here. */
2227 	res = -1;
2228 	mask = const_time_eq(BN_is_word(tmp, 1), 1);
2229 	res = const_time_select_int(mask, 1, res);
2230 	mask = const_time_eq(BN_is_zero(tmp), 1);
2231 	res = const_time_select_int(mask, 0, res);
2232 
2233 fail:
2234 	BN_clear_free(tmp);
2235 	BN_clear_free(exp);
2236 	BN_CTX_free(bnctx);
2237 	return res;
2238 }
2239 
2240 
2241 #ifdef CONFIG_ECC
2242 
2243 struct crypto_ec {
2244 	EC_GROUP *group;
2245 	int nid;
2246 	int iana_group;
2247 	BN_CTX *bnctx;
2248 	BIGNUM *prime;
2249 	BIGNUM *order;
2250 	BIGNUM *a;
2251 	BIGNUM *b;
2252 };
2253 
2254 
crypto_ec_group_2_nid(int group)2255 static int crypto_ec_group_2_nid(int group)
2256 {
2257 	/* Map from IANA registry for IKE D-H groups to OpenSSL NID */
2258 	switch (group) {
2259 	case 19:
2260 		return NID_X9_62_prime256v1;
2261 	case 20:
2262 		return NID_secp384r1;
2263 	case 21:
2264 		return NID_secp521r1;
2265 	case 25:
2266 		return NID_X9_62_prime192v1;
2267 	case 26:
2268 		return NID_secp224r1;
2269 #ifdef NID_brainpoolP224r1
2270 	case 27:
2271 		return NID_brainpoolP224r1;
2272 #endif /* NID_brainpoolP224r1 */
2273 #ifdef NID_brainpoolP256r1
2274 	case 28:
2275 		return NID_brainpoolP256r1;
2276 #endif /* NID_brainpoolP256r1 */
2277 #ifdef NID_brainpoolP384r1
2278 	case 29:
2279 		return NID_brainpoolP384r1;
2280 #endif /* NID_brainpoolP384r1 */
2281 #ifdef NID_brainpoolP512r1
2282 	case 30:
2283 		return NID_brainpoolP512r1;
2284 #endif /* NID_brainpoolP512r1 */
2285 	default:
2286 		return -1;
2287 	}
2288 }
2289 
2290 
2291 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
crypto_ec_group_2_name(int group)2292 static const char * crypto_ec_group_2_name(int group)
2293 {
2294 	/* Map from IANA registry for IKE D-H groups to OpenSSL group name */
2295 	switch (group) {
2296 	case 19:
2297 		return "prime256v1";
2298 	case 20:
2299 		return "secp384r1";
2300 	case 21:
2301 		return "secp521r1";
2302 	case 25:
2303 		return "prime192v1";
2304 	case 26:
2305 		return "secp224r1";
2306 #ifdef NID_brainpoolP224r1
2307 	case 27:
2308 		return "brainpoolP224r1";
2309 #endif /* NID_brainpoolP224r1 */
2310 #ifdef NID_brainpoolP256r1
2311 	case 28:
2312 		return "brainpoolP256r1";
2313 #endif /* NID_brainpoolP256r1 */
2314 #ifdef NID_brainpoolP384r1
2315 	case 29:
2316 		return "brainpoolP384r1";
2317 #endif /* NID_brainpoolP384r1 */
2318 #ifdef NID_brainpoolP512r1
2319 	case 30:
2320 		return "brainpoolP512r1";
2321 #endif /* NID_brainpoolP512r1 */
2322 	default:
2323 		return NULL;
2324 	}
2325 }
2326 #endif /* OpenSSL version >= 3.0 */
2327 
2328 
crypto_ec_init(int group)2329 struct crypto_ec * crypto_ec_init(int group)
2330 {
2331 	struct crypto_ec *e;
2332 	int nid;
2333 
2334 	nid = crypto_ec_group_2_nid(group);
2335 	if (nid < 0)
2336 		return NULL;
2337 
2338 	e = os_zalloc(sizeof(*e));
2339 	if (e == NULL)
2340 		return NULL;
2341 
2342 	e->nid = nid;
2343 	e->iana_group = group;
2344 	e->bnctx = BN_CTX_new();
2345 	e->group = EC_GROUP_new_by_curve_name(nid);
2346 	e->prime = BN_new();
2347 	e->order = BN_new();
2348 	e->a = BN_new();
2349 	e->b = BN_new();
2350 	if (e->group == NULL || e->bnctx == NULL || e->prime == NULL ||
2351 	    e->order == NULL || e->a == NULL || e->b == NULL ||
2352 	    !EC_GROUP_get_curve(e->group, e->prime, e->a, e->b, e->bnctx) ||
2353 	    !EC_GROUP_get_order(e->group, e->order, e->bnctx)) {
2354 		crypto_ec_deinit(e);
2355 		e = NULL;
2356 	}
2357 
2358 	return e;
2359 }
2360 
2361 
crypto_ec_deinit(struct crypto_ec * e)2362 void crypto_ec_deinit(struct crypto_ec *e)
2363 {
2364 	if (e == NULL)
2365 		return;
2366 	BN_clear_free(e->b);
2367 	BN_clear_free(e->a);
2368 	BN_clear_free(e->order);
2369 	BN_clear_free(e->prime);
2370 	EC_GROUP_free(e->group);
2371 	BN_CTX_free(e->bnctx);
2372 	os_free(e);
2373 }
2374 
2375 
crypto_ec_point_init(struct crypto_ec * e)2376 struct crypto_ec_point * crypto_ec_point_init(struct crypto_ec *e)
2377 {
2378 	if (TEST_FAIL())
2379 		return NULL;
2380 	if (e == NULL)
2381 		return NULL;
2382 	return (struct crypto_ec_point *) EC_POINT_new(e->group);
2383 }
2384 
2385 
crypto_ec_prime_len(struct crypto_ec * e)2386 size_t crypto_ec_prime_len(struct crypto_ec *e)
2387 {
2388 	return BN_num_bytes(e->prime);
2389 }
2390 
2391 
crypto_ec_prime_len_bits(struct crypto_ec * e)2392 size_t crypto_ec_prime_len_bits(struct crypto_ec *e)
2393 {
2394 	return BN_num_bits(e->prime);
2395 }
2396 
2397 
crypto_ec_order_len(struct crypto_ec * e)2398 size_t crypto_ec_order_len(struct crypto_ec *e)
2399 {
2400 	return BN_num_bytes(e->order);
2401 }
2402 
2403 
crypto_ec_get_prime(struct crypto_ec * e)2404 const struct crypto_bignum * crypto_ec_get_prime(struct crypto_ec *e)
2405 {
2406 	return (const struct crypto_bignum *) e->prime;
2407 }
2408 
2409 
crypto_ec_get_order(struct crypto_ec * e)2410 const struct crypto_bignum * crypto_ec_get_order(struct crypto_ec *e)
2411 {
2412 	return (const struct crypto_bignum *) e->order;
2413 }
2414 
2415 
crypto_ec_get_a(struct crypto_ec * e)2416 const struct crypto_bignum * crypto_ec_get_a(struct crypto_ec *e)
2417 {
2418 	return (const struct crypto_bignum *) e->a;
2419 }
2420 
2421 
crypto_ec_get_b(struct crypto_ec * e)2422 const struct crypto_bignum * crypto_ec_get_b(struct crypto_ec *e)
2423 {
2424 	return (const struct crypto_bignum *) e->b;
2425 }
2426 
2427 
crypto_ec_get_generator(struct crypto_ec * e)2428 const struct crypto_ec_point * crypto_ec_get_generator(struct crypto_ec *e)
2429 {
2430 	return (const struct crypto_ec_point *)
2431 		EC_GROUP_get0_generator(e->group);
2432 }
2433 
2434 
crypto_ec_point_deinit(struct crypto_ec_point * p,int clear)2435 void crypto_ec_point_deinit(struct crypto_ec_point *p, int clear)
2436 {
2437 	if (clear)
2438 		EC_POINT_clear_free((EC_POINT *) p);
2439 	else
2440 		EC_POINT_free((EC_POINT *) p);
2441 }
2442 
2443 
crypto_ec_point_x(struct crypto_ec * e,const struct crypto_ec_point * p,struct crypto_bignum * x)2444 int crypto_ec_point_x(struct crypto_ec *e, const struct crypto_ec_point *p,
2445 		      struct crypto_bignum *x)
2446 {
2447 	return EC_POINT_get_affine_coordinates(e->group,
2448 					       (const EC_POINT *) p,
2449 					       (BIGNUM *) x, NULL,
2450 					       e->bnctx) == 1 ? 0 : -1;
2451 }
2452 
2453 
crypto_ec_point_to_bin(struct crypto_ec * e,const struct crypto_ec_point * point,u8 * x,u8 * y)2454 int crypto_ec_point_to_bin(struct crypto_ec *e,
2455 			   const struct crypto_ec_point *point, u8 *x, u8 *y)
2456 {
2457 	BIGNUM *x_bn, *y_bn;
2458 	int ret = -1;
2459 	int len = BN_num_bytes(e->prime);
2460 
2461 	if (TEST_FAIL())
2462 		return -1;
2463 
2464 	x_bn = BN_new();
2465 	y_bn = BN_new();
2466 
2467 	if (x_bn && y_bn &&
2468 	    EC_POINT_get_affine_coordinates(e->group, (EC_POINT *) point,
2469 					    x_bn, y_bn, e->bnctx)) {
2470 		if (x) {
2471 			ret = crypto_bignum_to_bin(
2472 				(struct crypto_bignum *) x_bn, x, len, len);
2473 		}
2474 		if (ret >= 0 && y) {
2475 			ret = crypto_bignum_to_bin(
2476 				(struct crypto_bignum *) y_bn, y, len, len);
2477 		}
2478 
2479 		if (ret > 0)
2480 			ret = 0;
2481 	}
2482 
2483 	BN_clear_free(x_bn);
2484 	BN_clear_free(y_bn);
2485 	return ret;
2486 }
2487 
2488 
crypto_ec_point_from_bin(struct crypto_ec * e,const u8 * val)2489 struct crypto_ec_point * crypto_ec_point_from_bin(struct crypto_ec *e,
2490 						  const u8 *val)
2491 {
2492 	BIGNUM *x, *y;
2493 	EC_POINT *elem;
2494 	int len = BN_num_bytes(e->prime);
2495 
2496 	if (TEST_FAIL())
2497 		return NULL;
2498 
2499 	x = BN_bin2bn(val, len, NULL);
2500 	y = BN_bin2bn(val + len, len, NULL);
2501 	elem = EC_POINT_new(e->group);
2502 	if (x == NULL || y == NULL || elem == NULL) {
2503 		BN_clear_free(x);
2504 		BN_clear_free(y);
2505 		EC_POINT_clear_free(elem);
2506 		return NULL;
2507 	}
2508 
2509 	if (!EC_POINT_set_affine_coordinates(e->group, elem, x, y, e->bnctx)) {
2510 		EC_POINT_clear_free(elem);
2511 		elem = NULL;
2512 	}
2513 
2514 	BN_clear_free(x);
2515 	BN_clear_free(y);
2516 
2517 	return (struct crypto_ec_point *) elem;
2518 }
2519 
2520 
crypto_ec_point_add(struct crypto_ec * e,const struct crypto_ec_point * a,const struct crypto_ec_point * b,struct crypto_ec_point * c)2521 int crypto_ec_point_add(struct crypto_ec *e, const struct crypto_ec_point *a,
2522 			const struct crypto_ec_point *b,
2523 			struct crypto_ec_point *c)
2524 {
2525 	if (TEST_FAIL())
2526 		return -1;
2527 	return EC_POINT_add(e->group, (EC_POINT *) c, (const EC_POINT *) a,
2528 			    (const EC_POINT *) b, e->bnctx) ? 0 : -1;
2529 }
2530 
2531 
crypto_ec_point_mul(struct crypto_ec * e,const struct crypto_ec_point * p,const struct crypto_bignum * b,struct crypto_ec_point * res)2532 int crypto_ec_point_mul(struct crypto_ec *e, const struct crypto_ec_point *p,
2533 			const struct crypto_bignum *b,
2534 			struct crypto_ec_point *res)
2535 {
2536 	if (TEST_FAIL())
2537 		return -1;
2538 	return EC_POINT_mul(e->group, (EC_POINT *) res, NULL,
2539 			    (const EC_POINT *) p, (const BIGNUM *) b, e->bnctx)
2540 		? 0 : -1;
2541 }
2542 
2543 
crypto_ec_point_invert(struct crypto_ec * e,struct crypto_ec_point * p)2544 int crypto_ec_point_invert(struct crypto_ec *e, struct crypto_ec_point *p)
2545 {
2546 	if (TEST_FAIL())
2547 		return -1;
2548 	return EC_POINT_invert(e->group, (EC_POINT *) p, e->bnctx) ? 0 : -1;
2549 }
2550 
2551 
2552 struct crypto_bignum *
crypto_ec_point_compute_y_sqr(struct crypto_ec * e,const struct crypto_bignum * x)2553 crypto_ec_point_compute_y_sqr(struct crypto_ec *e,
2554 			      const struct crypto_bignum *x)
2555 {
2556 	BIGNUM *tmp;
2557 
2558 	if (TEST_FAIL())
2559 		return NULL;
2560 
2561 	tmp = BN_new();
2562 
2563 	/* y^2 = x^3 + ax + b = (x^2 + a)x + b */
2564 	if (tmp &&
2565 	    BN_mod_sqr(tmp, (const BIGNUM *) x, e->prime, e->bnctx) &&
2566 	    BN_mod_add_quick(tmp, e->a, tmp, e->prime) &&
2567 	    BN_mod_mul(tmp, tmp, (const BIGNUM *) x, e->prime, e->bnctx) &&
2568 	    BN_mod_add_quick(tmp, tmp, e->b, e->prime))
2569 		return (struct crypto_bignum *) tmp;
2570 
2571 	BN_clear_free(tmp);
2572 	return NULL;
2573 }
2574 
2575 
crypto_ec_point_is_at_infinity(struct crypto_ec * e,const struct crypto_ec_point * p)2576 int crypto_ec_point_is_at_infinity(struct crypto_ec *e,
2577 				   const struct crypto_ec_point *p)
2578 {
2579 	return EC_POINT_is_at_infinity(e->group, (const EC_POINT *) p);
2580 }
2581 
2582 
crypto_ec_point_is_on_curve(struct crypto_ec * e,const struct crypto_ec_point * p)2583 int crypto_ec_point_is_on_curve(struct crypto_ec *e,
2584 				const struct crypto_ec_point *p)
2585 {
2586 	return EC_POINT_is_on_curve(e->group, (const EC_POINT *) p,
2587 				    e->bnctx) == 1;
2588 }
2589 
2590 
crypto_ec_point_cmp(const struct crypto_ec * e,const struct crypto_ec_point * a,const struct crypto_ec_point * b)2591 int crypto_ec_point_cmp(const struct crypto_ec *e,
2592 			const struct crypto_ec_point *a,
2593 			const struct crypto_ec_point *b)
2594 {
2595 	return EC_POINT_cmp(e->group, (const EC_POINT *) a,
2596 			    (const EC_POINT *) b, e->bnctx);
2597 }
2598 
2599 
crypto_ec_point_debug_print(const struct crypto_ec * e,const struct crypto_ec_point * p,const char * title)2600 void crypto_ec_point_debug_print(const struct crypto_ec *e,
2601 				 const struct crypto_ec_point *p,
2602 				 const char *title)
2603 {
2604 	BIGNUM *x, *y;
2605 	char *x_str = NULL, *y_str = NULL;
2606 
2607 	x = BN_new();
2608 	y = BN_new();
2609 	if (!x || !y ||
2610 	    EC_POINT_get_affine_coordinates(e->group, (const EC_POINT *) p,
2611 					    x, y, e->bnctx) != 1)
2612 		goto fail;
2613 
2614 	x_str = BN_bn2hex(x);
2615 	y_str = BN_bn2hex(y);
2616 	if (!x_str || !y_str)
2617 		goto fail;
2618 
2619 	wpa_printf(MSG_DEBUG, "%s (%s,%s)", title, x_str, y_str);
2620 
2621 fail:
2622 	OPENSSL_free(x_str);
2623 	OPENSSL_free(y_str);
2624 	BN_free(x);
2625 	BN_free(y);
2626 }
2627 
2628 
2629 struct crypto_ecdh {
2630 	struct crypto_ec *ec;
2631 	EVP_PKEY *pkey;
2632 };
2633 
crypto_ecdh_init(int group)2634 struct crypto_ecdh * crypto_ecdh_init(int group)
2635 {
2636 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
2637 	struct crypto_ecdh *ecdh;
2638 	const char *name;
2639 
2640 	ecdh = os_zalloc(sizeof(*ecdh));
2641 	if (!ecdh)
2642 		goto fail;
2643 
2644 	ecdh->ec = crypto_ec_init(group);
2645 	if (!ecdh->ec)
2646 		goto fail;
2647 
2648 	name = OSSL_EC_curve_nid2name(ecdh->ec->nid);
2649 	if (!name)
2650 		goto fail;
2651 
2652 	ecdh->pkey = EVP_EC_gen(name);
2653 	if (!ecdh->pkey)
2654 		goto fail;
2655 
2656 done:
2657 	return ecdh;
2658 fail:
2659 	crypto_ecdh_deinit(ecdh);
2660 	ecdh = NULL;
2661 	goto done;
2662 #else /* OpenSSL version >= 3.0 */
2663 	struct crypto_ecdh *ecdh;
2664 	EVP_PKEY *params = NULL;
2665 	EC_KEY *ec_params = NULL;
2666 	EVP_PKEY_CTX *kctx = NULL;
2667 
2668 	ecdh = os_zalloc(sizeof(*ecdh));
2669 	if (!ecdh)
2670 		goto fail;
2671 
2672 	ecdh->ec = crypto_ec_init(group);
2673 	if (!ecdh->ec)
2674 		goto fail;
2675 
2676 	ec_params = EC_KEY_new_by_curve_name(ecdh->ec->nid);
2677 	if (!ec_params) {
2678 		wpa_printf(MSG_ERROR,
2679 			   "OpenSSL: Failed to generate EC_KEY parameters");
2680 		goto fail;
2681 	}
2682 	EC_KEY_set_asn1_flag(ec_params, OPENSSL_EC_NAMED_CURVE);
2683 	params = EVP_PKEY_new();
2684 	if (!params || EVP_PKEY_set1_EC_KEY(params, ec_params) != 1) {
2685 		wpa_printf(MSG_ERROR,
2686 			   "OpenSSL: Failed to generate EVP_PKEY parameters");
2687 		goto fail;
2688 	}
2689 
2690 	kctx = EVP_PKEY_CTX_new(params, NULL);
2691 	if (!kctx)
2692 		goto fail;
2693 
2694 	if (EVP_PKEY_keygen_init(kctx) != 1) {
2695 		wpa_printf(MSG_ERROR,
2696 			   "OpenSSL: EVP_PKEY_keygen_init failed: %s",
2697 			   ERR_error_string(ERR_get_error(), NULL));
2698 		goto fail;
2699 	}
2700 
2701 	if (EVP_PKEY_keygen(kctx, &ecdh->pkey) != 1) {
2702 		wpa_printf(MSG_ERROR, "OpenSSL: EVP_PKEY_keygen failed: %s",
2703 			   ERR_error_string(ERR_get_error(), NULL));
2704 		goto fail;
2705 	}
2706 
2707 done:
2708 	EC_KEY_free(ec_params);
2709 	EVP_PKEY_free(params);
2710 	EVP_PKEY_CTX_free(kctx);
2711 
2712 	return ecdh;
2713 fail:
2714 	crypto_ecdh_deinit(ecdh);
2715 	ecdh = NULL;
2716 	goto done;
2717 #endif /* OpenSSL version >= 3.0 */
2718 }
2719 
2720 
crypto_ecdh_init2(int group,struct crypto_ec_key * own_key)2721 struct crypto_ecdh * crypto_ecdh_init2(int group, struct crypto_ec_key *own_key)
2722 {
2723 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
2724 	struct crypto_ecdh *ecdh;
2725 
2726 	ecdh = os_zalloc(sizeof(*ecdh));
2727 	if (!ecdh)
2728 		goto fail;
2729 
2730 	ecdh->ec = crypto_ec_init(group);
2731 	if (!ecdh->ec)
2732 		goto fail;
2733 
2734 	ecdh->pkey = EVP_PKEY_dup((EVP_PKEY *) own_key);
2735 	if (!ecdh->pkey)
2736 		goto fail;
2737 
2738 	return ecdh;
2739 fail:
2740 	crypto_ecdh_deinit(ecdh);
2741 	return NULL;
2742 #else /* OpenSSL version >= 3.0 */
2743 	struct crypto_ecdh *ecdh;
2744 
2745 	ecdh = os_zalloc(sizeof(*ecdh));
2746 	if (!ecdh)
2747 		goto fail;
2748 
2749 	ecdh->ec = crypto_ec_init(group);
2750 	if (!ecdh->ec)
2751 		goto fail;
2752 
2753 	ecdh->pkey = EVP_PKEY_new();
2754 	if (!ecdh->pkey ||
2755 	    EVP_PKEY_assign_EC_KEY(ecdh->pkey,
2756 				   EVP_PKEY_get1_EC_KEY((EVP_PKEY *) own_key))
2757 	    != 1)
2758 		goto fail;
2759 
2760 	return ecdh;
2761 fail:
2762 	crypto_ecdh_deinit(ecdh);
2763 	return NULL;
2764 #endif /* OpenSSL version >= 3.0 */
2765 }
2766 
2767 
crypto_ecdh_get_pubkey(struct crypto_ecdh * ecdh,int inc_y)2768 struct wpabuf * crypto_ecdh_get_pubkey(struct crypto_ecdh *ecdh, int inc_y)
2769 {
2770 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
2771 	struct wpabuf *buf = NULL;
2772 	unsigned char *pub;
2773 	size_t len, exp_len;
2774 
2775 	len = EVP_PKEY_get1_encoded_public_key(ecdh->pkey, &pub);
2776 	if (len == 0)
2777 		return NULL;
2778 
2779 	/* Encoded using SECG SEC 1, Sec. 2.3.4 format */
2780 	exp_len = 1 + 2 * crypto_ec_prime_len(ecdh->ec);
2781 	if (len != exp_len) {
2782 		wpa_printf(MSG_ERROR,
2783 			   "OpenSSL:%s: Unexpected encoded public key length %zu (expected %zu)",
2784 			   __func__, len, exp_len);
2785 		goto fail;
2786 	}
2787 	buf = wpabuf_alloc_copy(pub + 1, inc_y ? len - 1 : len / 2);
2788 fail:
2789 	OPENSSL_free(pub);
2790 	return buf;
2791 #else /* OpenSSL version >= 3.0 */
2792 	struct wpabuf *buf = NULL;
2793 	EC_KEY *eckey;
2794 	const EC_POINT *pubkey;
2795 	BIGNUM *x, *y = NULL;
2796 	int len = BN_num_bytes(ecdh->ec->prime);
2797 	int res;
2798 
2799 	eckey = EVP_PKEY_get1_EC_KEY(ecdh->pkey);
2800 	if (!eckey)
2801 		return NULL;
2802 
2803 	pubkey = EC_KEY_get0_public_key(eckey);
2804 	if (!pubkey)
2805 		return NULL;
2806 
2807 	x = BN_new();
2808 	if (inc_y) {
2809 		y = BN_new();
2810 		if (!y)
2811 			goto fail;
2812 	}
2813 	buf = wpabuf_alloc(inc_y ? 2 * len : len);
2814 	if (!x || !buf)
2815 		goto fail;
2816 
2817 	if (EC_POINT_get_affine_coordinates(ecdh->ec->group, pubkey,
2818 					    x, y, ecdh->ec->bnctx) != 1) {
2819 		wpa_printf(MSG_ERROR,
2820 			   "OpenSSL: EC_POINT_get_affine_coordinates failed: %s",
2821 			   ERR_error_string(ERR_get_error(), NULL));
2822 		goto fail;
2823 	}
2824 
2825 	res = crypto_bignum_to_bin((struct crypto_bignum *) x,
2826 				   wpabuf_put(buf, len), len, len);
2827 	if (res < 0)
2828 		goto fail;
2829 
2830 	if (inc_y) {
2831 		res = crypto_bignum_to_bin((struct crypto_bignum *) y,
2832 					   wpabuf_put(buf, len), len, len);
2833 		if (res < 0)
2834 			goto fail;
2835 	}
2836 
2837 done:
2838 	BN_clear_free(x);
2839 	BN_clear_free(y);
2840 	EC_KEY_free(eckey);
2841 
2842 	return buf;
2843 fail:
2844 	wpabuf_free(buf);
2845 	buf = NULL;
2846 	goto done;
2847 #endif /* OpenSSL version >= 3.0 */
2848 }
2849 
2850 
crypto_ecdh_set_peerkey(struct crypto_ecdh * ecdh,int inc_y,const u8 * key,size_t len)2851 struct wpabuf * crypto_ecdh_set_peerkey(struct crypto_ecdh *ecdh, int inc_y,
2852 					const u8 *key, size_t len)
2853 {
2854 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
2855 	EVP_PKEY *peerkey = EVP_PKEY_new();
2856 	EVP_PKEY_CTX *ctx;
2857 	size_t res_len;
2858 	struct wpabuf *res = NULL;
2859 	u8 *peer;
2860 
2861 	/* Encode using SECG SEC 1, Sec. 2.3.4 format */
2862 	peer = os_malloc(1 + len);
2863 	if (!peer) {
2864 		EVP_PKEY_free(peerkey);
2865 		return NULL;
2866 	}
2867 	peer[0] = inc_y ? 0x04 : 0x02;
2868 	os_memcpy(peer + 1, key, len);
2869 
2870 	if (!peerkey ||
2871 	    EVP_PKEY_copy_parameters(peerkey, ecdh->pkey) != 1 ||
2872 	    EVP_PKEY_set1_encoded_public_key(peerkey, peer, 1 + len) != 1) {
2873 		wpa_printf(MSG_INFO, "OpenSSL: EVP_PKEY_set1_encoded_public_key failed: %s",
2874 			   ERR_error_string(ERR_get_error(), NULL));
2875 		EVP_PKEY_free(peerkey);
2876 		os_free(peer);
2877 		return NULL;
2878 	}
2879 	os_free(peer);
2880 
2881 	ctx = EVP_PKEY_CTX_new(ecdh->pkey, NULL);
2882 	if (!ctx ||
2883 	    EVP_PKEY_derive_init(ctx) != 1 ||
2884 	    EVP_PKEY_derive_set_peer(ctx, peerkey) != 1 ||
2885 	    EVP_PKEY_derive(ctx, NULL, &res_len) != 1 ||
2886 	    !(res = wpabuf_alloc(res_len)) ||
2887 	    EVP_PKEY_derive(ctx, wpabuf_mhead(res), &res_len) != 1) {
2888 		wpa_printf(MSG_INFO, "OpenSSL: EVP_PKEY_derive failed: %s",
2889 			   ERR_error_string(ERR_get_error(), NULL));
2890 		wpabuf_free(res);
2891 		res = NULL;
2892 	} else {
2893 		wpabuf_put(res, res_len);
2894 	}
2895 
2896 	EVP_PKEY_free(peerkey);
2897 	EVP_PKEY_CTX_free(ctx);
2898 	return res;
2899 #else /* OpenSSL version >= 3.0 */
2900 	BIGNUM *x, *y = NULL;
2901 	EVP_PKEY_CTX *ctx = NULL;
2902 	EVP_PKEY *peerkey = NULL;
2903 	struct wpabuf *secret = NULL;
2904 	size_t secret_len;
2905 	EC_POINT *pub;
2906 	EC_KEY *eckey = NULL;
2907 
2908 	x = BN_bin2bn(key, inc_y ? len / 2 : len, NULL);
2909 	pub = EC_POINT_new(ecdh->ec->group);
2910 	if (!x || !pub)
2911 		goto fail;
2912 
2913 	if (inc_y) {
2914 		y = BN_bin2bn(key + len / 2, len / 2, NULL);
2915 		if (!y)
2916 			goto fail;
2917 		if (!EC_POINT_set_affine_coordinates(ecdh->ec->group, pub,
2918 						     x, y, ecdh->ec->bnctx)) {
2919 			wpa_printf(MSG_ERROR,
2920 				   "OpenSSL: EC_POINT_set_affine_coordinates failed: %s",
2921 				   ERR_error_string(ERR_get_error(), NULL));
2922 			goto fail;
2923 		}
2924 	} else if (!EC_POINT_set_compressed_coordinates(ecdh->ec->group,
2925 							pub, x, 0,
2926 							ecdh->ec->bnctx)) {
2927 		wpa_printf(MSG_ERROR,
2928 			   "OpenSSL: EC_POINT_set_compressed_coordinates failed: %s",
2929 			   ERR_error_string(ERR_get_error(), NULL));
2930 		goto fail;
2931 	}
2932 
2933 	if (!EC_POINT_is_on_curve(ecdh->ec->group, pub, ecdh->ec->bnctx)) {
2934 		wpa_printf(MSG_ERROR,
2935 			   "OpenSSL: ECDH peer public key is not on curve");
2936 		goto fail;
2937 	}
2938 
2939 	eckey = EC_KEY_new_by_curve_name(ecdh->ec->nid);
2940 	if (!eckey || EC_KEY_set_public_key(eckey, pub) != 1) {
2941 		wpa_printf(MSG_ERROR,
2942 			   "OpenSSL: EC_KEY_set_public_key failed: %s",
2943 			   ERR_error_string(ERR_get_error(), NULL));
2944 		goto fail;
2945 	}
2946 
2947 	peerkey = EVP_PKEY_new();
2948 	if (!peerkey || EVP_PKEY_set1_EC_KEY(peerkey, eckey) != 1)
2949 		goto fail;
2950 
2951 	ctx = EVP_PKEY_CTX_new(ecdh->pkey, NULL);
2952 	if (!ctx || EVP_PKEY_derive_init(ctx) != 1 ||
2953 	    EVP_PKEY_derive_set_peer(ctx, peerkey) != 1 ||
2954 	    EVP_PKEY_derive(ctx, NULL, &secret_len) != 1) {
2955 		wpa_printf(MSG_ERROR,
2956 			   "OpenSSL: EVP_PKEY_derive(1) failed: %s",
2957 			   ERR_error_string(ERR_get_error(), NULL));
2958 		goto fail;
2959 	}
2960 
2961 	secret = wpabuf_alloc(secret_len);
2962 	if (!secret)
2963 		goto fail;
2964 	if (EVP_PKEY_derive(ctx, wpabuf_put(secret, 0), &secret_len) != 1) {
2965 		wpa_printf(MSG_ERROR,
2966 			   "OpenSSL: EVP_PKEY_derive(2) failed: %s",
2967 			   ERR_error_string(ERR_get_error(), NULL));
2968 		goto fail;
2969 	}
2970 	if (secret->size != secret_len)
2971 		wpa_printf(MSG_DEBUG,
2972 			   "OpenSSL: EVP_PKEY_derive(2) changed secret_len %d -> %d",
2973 			   (int) secret->size, (int) secret_len);
2974 	wpabuf_put(secret, secret_len);
2975 
2976 done:
2977 	BN_free(x);
2978 	BN_free(y);
2979 	EC_KEY_free(eckey);
2980 	EC_POINT_free(pub);
2981 	EVP_PKEY_CTX_free(ctx);
2982 	EVP_PKEY_free(peerkey);
2983 	return secret;
2984 fail:
2985 	wpabuf_free(secret);
2986 	secret = NULL;
2987 	goto done;
2988 #endif /* OpenSSL version >= 3.0 */
2989 }
2990 
2991 
crypto_ecdh_deinit(struct crypto_ecdh * ecdh)2992 void crypto_ecdh_deinit(struct crypto_ecdh *ecdh)
2993 {
2994 	if (ecdh) {
2995 		crypto_ec_deinit(ecdh->ec);
2996 		EVP_PKEY_free(ecdh->pkey);
2997 		os_free(ecdh);
2998 	}
2999 }
3000 
3001 
crypto_ecdh_prime_len(struct crypto_ecdh * ecdh)3002 size_t crypto_ecdh_prime_len(struct crypto_ecdh *ecdh)
3003 {
3004 	return crypto_ec_prime_len(ecdh->ec);
3005 }
3006 
3007 
crypto_ec_key_parse_priv(const u8 * der,size_t der_len)3008 struct crypto_ec_key * crypto_ec_key_parse_priv(const u8 *der, size_t der_len)
3009 {
3010 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3011 	EVP_PKEY *pkey = NULL;
3012 	OSSL_DECODER_CTX *ctx;
3013 
3014 	ctx = OSSL_DECODER_CTX_new_for_pkey(
3015 		&pkey, "DER", NULL, "EC",
3016 		OSSL_KEYMGMT_SELECT_KEYPAIR |
3017 		OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3018 		NULL, NULL);
3019 	if (!ctx ||
3020 	    OSSL_DECODER_from_data(ctx, &der, &der_len) != 1) {
3021 		wpa_printf(MSG_INFO,
3022 			   "OpenSSL: Decoding EC private key (DER) failed: %s",
3023 			   ERR_error_string(ERR_get_error(), NULL));
3024 		if (ctx)
3025 			OSSL_DECODER_CTX_free(ctx);
3026 		goto fail;
3027 	}
3028 
3029 	OSSL_DECODER_CTX_free(ctx);
3030 	return (struct crypto_ec_key *) pkey;
3031 fail:
3032 	crypto_ec_key_deinit((struct crypto_ec_key *) pkey);
3033 	return NULL;
3034 #else /* OpenSSL version >= 3.0 */
3035 	EVP_PKEY *pkey = NULL;
3036 	EC_KEY *eckey;
3037 
3038 	eckey = d2i_ECPrivateKey(NULL, &der, der_len);
3039 	if (!eckey) {
3040 		wpa_printf(MSG_INFO, "OpenSSL: d2i_ECPrivateKey() failed: %s",
3041 			   ERR_error_string(ERR_get_error(), NULL));
3042 		goto fail;
3043 	}
3044 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
3045 
3046 	pkey = EVP_PKEY_new();
3047 	if (!pkey || EVP_PKEY_assign_EC_KEY(pkey, eckey) != 1) {
3048 		EC_KEY_free(eckey);
3049 		goto fail;
3050 	}
3051 
3052 	return (struct crypto_ec_key *) pkey;
3053 fail:
3054 	crypto_ec_key_deinit((struct crypto_ec_key *) pkey);
3055 	return NULL;
3056 #endif /* OpenSSL version >= 3.0 */
3057 }
3058 
3059 
crypto_ec_key_set_priv(int group,const u8 * raw,size_t raw_len)3060 struct crypto_ec_key * crypto_ec_key_set_priv(int group,
3061 					      const u8 *raw, size_t raw_len)
3062 {
3063 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3064 	const char *group_name;
3065 	OSSL_PARAM params[4];
3066 	EVP_PKEY_CTX *ctx = NULL;
3067 	EVP_PKEY *pkey = NULL;
3068 	BIGNUM *priv;
3069 	EC_POINT *pub = NULL;
3070 	EC_GROUP *ec_group = NULL;
3071 	size_t len;
3072 	u8 *pub_bin = NULL;
3073 	u8 *priv_bin = NULL;
3074 	int priv_bin_len;
3075 
3076 	group_name = crypto_ec_group_2_name(group);
3077 	if (!group_name)
3078 		return NULL;
3079 
3080 	priv = BN_bin2bn(raw, raw_len, NULL);
3081 	if (!priv)
3082 		return NULL;
3083 	priv_bin = os_malloc(raw_len);
3084 	if (!priv_bin)
3085 		goto fail;
3086 	priv_bin_len = BN_bn2lebinpad(priv, priv_bin, raw_len);
3087 	if (priv_bin_len < 0)
3088 		goto fail;
3089 
3090 	ec_group = EC_GROUP_new_by_curve_name(crypto_ec_group_2_nid(group));
3091 	if (!ec_group)
3092 		goto fail;
3093 	pub = EC_POINT_new(ec_group);
3094 	if (!pub ||
3095 	    EC_POINT_mul(ec_group, pub, priv, NULL, NULL, NULL) != 1)
3096 		goto fail;
3097 	len = EC_POINT_point2oct(ec_group, pub, POINT_CONVERSION_UNCOMPRESSED,
3098 				 NULL, 0, NULL);
3099 	if (len == 0)
3100 		goto fail;
3101 	pub_bin = os_malloc(len);
3102 	if (!pub_bin)
3103 		goto fail;
3104 	len = EC_POINT_point2oct(ec_group, pub, POINT_CONVERSION_UNCOMPRESSED,
3105 				 pub_bin, len, NULL);
3106 	if (len == 0)
3107 		goto fail;
3108 
3109 	params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
3110 						     (char *) group_name, 0);
3111 	params[1] = OSSL_PARAM_construct_BN(OSSL_PKEY_PARAM_PRIV_KEY,
3112 					    priv_bin, priv_bin_len);
3113 	params[2] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
3114 						      pub_bin, len);
3115 	params[3] = OSSL_PARAM_construct_end();
3116 
3117 	ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL);
3118 	if (!ctx ||
3119 	    EVP_PKEY_fromdata_init(ctx) <= 0 ||
3120 	    EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0)
3121 		goto fail;
3122 
3123 out:
3124 	bin_clear_free(priv_bin, raw_len);
3125 	os_free(pub_bin);
3126 	BN_clear_free(priv);
3127 	EVP_PKEY_CTX_free(ctx);
3128 	EC_POINT_free(pub);
3129 	EC_GROUP_free(ec_group);
3130 	return (struct crypto_ec_key *) pkey;
3131 
3132 fail:
3133 	EVP_PKEY_free(pkey);
3134 	pkey = NULL;
3135 	goto out;
3136 #else /* OpenSSL version >= 3.0 */
3137 	EC_KEY *eckey = NULL;
3138 	EVP_PKEY *pkey = NULL;
3139 	BIGNUM *priv = NULL;
3140 	int nid;
3141 	const EC_GROUP *ec_group;
3142 	EC_POINT *pub = NULL;
3143 
3144 	nid = crypto_ec_group_2_nid(group);
3145 	if (nid < 0) {
3146 		wpa_printf(MSG_ERROR, "OpenSSL: Unsupported group %d", group);
3147 		return NULL;
3148 	}
3149 
3150 	eckey = EC_KEY_new_by_curve_name(nid);
3151 	priv = BN_bin2bn(raw, raw_len, NULL);
3152 	if (!eckey || !priv ||
3153 	    EC_KEY_set_private_key(eckey, priv) != 1) {
3154 		wpa_printf(MSG_ERROR,
3155 			   "OpenSSL: Failed to set EC_KEY: %s",
3156 			   ERR_error_string(ERR_get_error(), NULL));
3157 		goto fail;
3158 	}
3159 
3160 	ec_group = EC_KEY_get0_group(eckey);
3161 	if (!ec_group)
3162 		goto fail;
3163 	pub = EC_POINT_new(ec_group);
3164 	if (!pub ||
3165 	    EC_POINT_mul(ec_group, pub, priv, NULL, NULL, NULL) != 1 ||
3166 	    EC_KEY_set_public_key(eckey, pub) != 1) {
3167 		wpa_printf(MSG_ERROR,
3168 			   "OpenSSL: Failed to set EC_KEY(pub): %s",
3169 			   ERR_error_string(ERR_get_error(), NULL));
3170 		goto fail;
3171 	}
3172 
3173 	EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
3174 
3175 	pkey = EVP_PKEY_new();
3176 	if (!pkey || EVP_PKEY_assign_EC_KEY(pkey, eckey) != 1) {
3177 		wpa_printf(MSG_ERROR, "OpenSSL: Could not create EVP_PKEY");
3178 		goto fail;
3179 	}
3180 
3181 out:
3182 	BN_clear_free(priv);
3183 	EC_POINT_free(pub);
3184 	return (struct crypto_ec_key *) pkey;
3185 
3186 fail:
3187 	EC_KEY_free(eckey);
3188 	EVP_PKEY_free(pkey);
3189 	pkey = NULL;
3190 	goto out;
3191 #endif /* OpenSSL version >= 3.0 */
3192 }
3193 
3194 
crypto_ec_key_parse_pub(const u8 * der,size_t der_len)3195 struct crypto_ec_key * crypto_ec_key_parse_pub(const u8 *der, size_t der_len)
3196 {
3197 	EVP_PKEY *pkey;
3198 
3199 	pkey = d2i_PUBKEY(NULL, &der, der_len);
3200 	if (!pkey) {
3201 		wpa_printf(MSG_INFO, "OpenSSL: d2i_PUBKEY() failed: %s",
3202 			   ERR_error_string(ERR_get_error(), NULL));
3203 		goto fail;
3204 	}
3205 
3206 	/* Ensure this is an EC key */
3207 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3208 	if (!EVP_PKEY_is_a(pkey, "EC"))
3209 		goto fail;
3210 #else /* OpenSSL version >= 3.0 */
3211 	if (!EVP_PKEY_get0_EC_KEY(pkey))
3212 		goto fail;
3213 #endif /* OpenSSL version >= 3.0 */
3214 	return (struct crypto_ec_key *) pkey;
3215 fail:
3216 	crypto_ec_key_deinit((struct crypto_ec_key *) pkey);
3217 	return NULL;
3218 }
3219 
3220 
crypto_ec_key_set_pub(int group,const u8 * buf_x,const u8 * buf_y,size_t len)3221 struct crypto_ec_key * crypto_ec_key_set_pub(int group, const u8 *buf_x,
3222 					     const u8 *buf_y, size_t len)
3223 {
3224 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3225 	const char *group_name;
3226 	OSSL_PARAM params[3];
3227 	u8 *pub;
3228 	EVP_PKEY_CTX *ctx;
3229 	EVP_PKEY *pkey = NULL;
3230 
3231 	group_name = crypto_ec_group_2_name(group);
3232 	if (!group_name)
3233 		return NULL;
3234 
3235 	pub = os_malloc(1 + len * 2);
3236 	if (!pub)
3237 		return NULL;
3238 	pub[0] = 0x04; /* uncompressed */
3239 	os_memcpy(pub + 1, buf_x, len);
3240 	os_memcpy(pub + 1 + len, buf_y, len);
3241 
3242 	params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
3243 						     (char *) group_name, 0);
3244 	params[1] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
3245 						      pub, 1 + len * 2);
3246 	params[2] = OSSL_PARAM_construct_end();
3247 
3248 	ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL);
3249 	if (!ctx) {
3250 		os_free(pub);
3251 		return NULL;
3252 	}
3253 	if (EVP_PKEY_fromdata_init(ctx) <= 0 ||
3254 	    EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_PUBLIC_KEY, params) <= 0) {
3255 		os_free(pub);
3256 		EVP_PKEY_CTX_free(ctx);
3257 		return NULL;
3258 	}
3259 
3260 	os_free(pub);
3261 	EVP_PKEY_CTX_free(ctx);
3262 
3263 	return (struct crypto_ec_key *) pkey;
3264 #else /* OpenSSL version >= 3.0 */
3265 	EC_KEY *eckey = NULL;
3266 	EVP_PKEY *pkey = NULL;
3267 	EC_GROUP *ec_group = NULL;
3268 	BN_CTX *ctx;
3269 	EC_POINT *point = NULL;
3270 	BIGNUM *x = NULL, *y = NULL;
3271 	int nid;
3272 
3273 	if (!buf_x || !buf_y)
3274 		return NULL;
3275 
3276 	nid = crypto_ec_group_2_nid(group);
3277 	if (nid < 0) {
3278 		wpa_printf(MSG_ERROR, "OpenSSL: Unsupported group %d", group);
3279 		return NULL;
3280 	}
3281 
3282 	ctx = BN_CTX_new();
3283 	if (!ctx)
3284 		goto fail;
3285 
3286 	ec_group = EC_GROUP_new_by_curve_name(nid);
3287 	if (!ec_group)
3288 		goto fail;
3289 
3290 	x = BN_bin2bn(buf_x, len, NULL);
3291 	y = BN_bin2bn(buf_y, len, NULL);
3292 	point = EC_POINT_new(ec_group);
3293 	if (!x || !y || !point)
3294 		goto fail;
3295 
3296 	if (!EC_POINT_set_affine_coordinates(ec_group, point, x, y, ctx)) {
3297 		wpa_printf(MSG_ERROR,
3298 			   "OpenSSL: EC_POINT_set_affine_coordinates failed: %s",
3299 			   ERR_error_string(ERR_get_error(), NULL));
3300 		goto fail;
3301 	}
3302 
3303 	if (!EC_POINT_is_on_curve(ec_group, point, ctx) ||
3304 	    EC_POINT_is_at_infinity(ec_group, point)) {
3305 		wpa_printf(MSG_ERROR, "OpenSSL: Invalid point");
3306 		goto fail;
3307 	}
3308 
3309 	eckey = EC_KEY_new();
3310 	if (!eckey ||
3311 	    EC_KEY_set_group(eckey, ec_group) != 1 ||
3312 	    EC_KEY_set_public_key(eckey, point) != 1) {
3313 		wpa_printf(MSG_ERROR,
3314 			   "OpenSSL: Failed to set EC_KEY: %s",
3315 			   ERR_error_string(ERR_get_error(), NULL));
3316 		goto fail;
3317 	}
3318 	EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
3319 
3320 	pkey = EVP_PKEY_new();
3321 	if (!pkey || EVP_PKEY_assign_EC_KEY(pkey, eckey) != 1) {
3322 		wpa_printf(MSG_ERROR, "OpenSSL: Could not create EVP_PKEY");
3323 		goto fail;
3324 	}
3325 
3326 out:
3327 	EC_GROUP_free(ec_group);
3328 	BN_free(x);
3329 	BN_free(y);
3330 	EC_POINT_free(point);
3331 	BN_CTX_free(ctx);
3332 	return (struct crypto_ec_key *) pkey;
3333 
3334 fail:
3335 	EC_KEY_free(eckey);
3336 	EVP_PKEY_free(pkey);
3337 	pkey = NULL;
3338 	goto out;
3339 #endif /* OpenSSL version >= 3.0 */
3340 }
3341 
3342 
3343 struct crypto_ec_key *
crypto_ec_key_set_pub_point(struct crypto_ec * ec,const struct crypto_ec_point * pub)3344 crypto_ec_key_set_pub_point(struct crypto_ec *ec,
3345 			    const struct crypto_ec_point *pub)
3346 {
3347 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3348 	int len = BN_num_bytes(ec->prime);
3349 	struct crypto_ec_key *key;
3350 	u8 *buf;
3351 
3352 	buf = os_malloc(2 * len);
3353 	if (!buf)
3354 		return NULL;
3355 	if (crypto_ec_point_to_bin(ec, pub, buf, buf + len) < 0) {
3356 		os_free(buf);
3357 		return NULL;
3358 	}
3359 
3360 	key = crypto_ec_key_set_pub(ec->iana_group, buf, buf + len, len);
3361 	os_free(buf);
3362 
3363 	return key;
3364 #else /* OpenSSL version >= 3.0 */
3365 	EC_KEY *eckey;
3366 	EVP_PKEY *pkey = NULL;
3367 
3368 	eckey = EC_KEY_new();
3369 	if (!eckey ||
3370 	    EC_KEY_set_group(eckey, ec->group) != 1 ||
3371 	    EC_KEY_set_public_key(eckey, (const EC_POINT *) pub) != 1) {
3372 		wpa_printf(MSG_ERROR,
3373 			   "OpenSSL: Failed to set EC_KEY: %s",
3374 			   ERR_error_string(ERR_get_error(), NULL));
3375 		goto fail;
3376 	}
3377 	EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
3378 
3379 	pkey = EVP_PKEY_new();
3380 	if (!pkey || EVP_PKEY_assign_EC_KEY(pkey, eckey) != 1) {
3381 		wpa_printf(MSG_ERROR, "OpenSSL: Could not create EVP_PKEY");
3382 		goto fail;
3383 	}
3384 
3385 out:
3386 	return (struct crypto_ec_key *) pkey;
3387 
3388 fail:
3389 	EVP_PKEY_free(pkey);
3390 	EC_KEY_free(eckey);
3391 	pkey = NULL;
3392 	goto out;
3393 #endif /* OpenSSL version >= 3.0 */
3394 }
3395 
3396 
crypto_ec_key_gen(int group)3397 struct crypto_ec_key * crypto_ec_key_gen(int group)
3398 {
3399 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3400 	EVP_PKEY_CTX *ctx;
3401 	OSSL_PARAM params[2];
3402 	const char *group_name;
3403 	EVP_PKEY *pkey = NULL;
3404 
3405 	group_name = crypto_ec_group_2_name(group);
3406 	if (!group_name)
3407 		return NULL;
3408 
3409 	params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
3410 						     (char *) group_name, 0);
3411 	params[1] = OSSL_PARAM_construct_end();
3412 
3413 	ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL);
3414 	if (!ctx ||
3415 	    EVP_PKEY_keygen_init(ctx) != 1 ||
3416 	    EVP_PKEY_CTX_set_params(ctx, params) != 1 ||
3417 	    EVP_PKEY_generate(ctx, &pkey) != 1) {
3418 		wpa_printf(MSG_INFO,
3419 			   "OpenSSL: failed to generate EC keypair: %s",
3420 			   ERR_error_string(ERR_get_error(), NULL));
3421 		pkey = NULL;
3422 	}
3423 
3424 	EVP_PKEY_CTX_free(ctx);
3425 
3426 	return (struct crypto_ec_key *) pkey;
3427 #else /* OpenSSL version >= 3.0 */
3428 	EVP_PKEY_CTX *kctx = NULL;
3429 	EC_KEY *ec_params = NULL, *eckey;
3430 	EVP_PKEY *params = NULL, *key = NULL;
3431 	int nid;
3432 
3433 	nid = crypto_ec_group_2_nid(group);
3434 	if (nid < 0) {
3435 		wpa_printf(MSG_ERROR, "OpenSSL: Unsupported group %d", group);
3436 		return NULL;
3437 	}
3438 
3439 	ec_params = EC_KEY_new_by_curve_name(nid);
3440 	if (!ec_params) {
3441 		wpa_printf(MSG_ERROR,
3442 			   "OpenSSL: Failed to generate EC_KEY parameters");
3443 		goto fail;
3444 	}
3445 	EC_KEY_set_asn1_flag(ec_params, OPENSSL_EC_NAMED_CURVE);
3446 	params = EVP_PKEY_new();
3447 	if (!params || EVP_PKEY_set1_EC_KEY(params, ec_params) != 1) {
3448 		wpa_printf(MSG_ERROR,
3449 			   "OpenSSL: Failed to generate EVP_PKEY parameters");
3450 		goto fail;
3451 	}
3452 
3453 	kctx = EVP_PKEY_CTX_new(params, NULL);
3454 	if (!kctx ||
3455 	    EVP_PKEY_keygen_init(kctx) != 1 ||
3456 	    EVP_PKEY_keygen(kctx, &key) != 1) {
3457 		wpa_printf(MSG_ERROR, "OpenSSL: Failed to generate EC key");
3458 		key = NULL;
3459 		goto fail;
3460 	}
3461 
3462 	eckey = EVP_PKEY_get1_EC_KEY(key);
3463 	if (!eckey) {
3464 		key = NULL;
3465 		goto fail;
3466 	}
3467 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
3468 	EC_KEY_free(eckey);
3469 
3470 fail:
3471 	EC_KEY_free(ec_params);
3472 	EVP_PKEY_free(params);
3473 	EVP_PKEY_CTX_free(kctx);
3474 	return (struct crypto_ec_key *) key;
3475 #endif /* OpenSSL version >= 3.0 */
3476 }
3477 
3478 
crypto_ec_key_deinit(struct crypto_ec_key * key)3479 void crypto_ec_key_deinit(struct crypto_ec_key *key)
3480 {
3481 	EVP_PKEY_free((EVP_PKEY *) key);
3482 }
3483 
3484 
3485 #ifdef OPENSSL_IS_BORINGSSL
3486 
3487 /* BoringSSL version of i2d_PUBKEY() always outputs public EC key using
3488  * uncompressed form so define a custom function to export EC pubkey using
3489  * the compressed format that is explicitly required for some protocols. */
3490 
3491 #include <openssl/asn1.h>
3492 #include <openssl/asn1t.h>
3493 
3494 typedef struct {
3495 	/* AlgorithmIdentifier ecPublicKey with optional parameters present
3496 	 * as an OID identifying the curve */
3497 	X509_ALGOR *alg;
3498 	/* Compressed format public key per ANSI X9.63 */
3499 	ASN1_BIT_STRING *pub_key;
3500 } EC_COMP_PUBKEY;
3501 
3502 ASN1_SEQUENCE(EC_COMP_PUBKEY) = {
3503 	ASN1_SIMPLE(EC_COMP_PUBKEY, alg, X509_ALGOR),
3504 	ASN1_SIMPLE(EC_COMP_PUBKEY, pub_key, ASN1_BIT_STRING)
3505 } ASN1_SEQUENCE_END(EC_COMP_PUBKEY);
3506 
3507 IMPLEMENT_ASN1_FUNCTIONS(EC_COMP_PUBKEY);
3508 
3509 #endif /* OPENSSL_IS_BORINGSSL */
3510 
3511 
crypto_ec_key_get_subject_public_key(struct crypto_ec_key * key)3512 struct wpabuf * crypto_ec_key_get_subject_public_key(struct crypto_ec_key *key)
3513 {
3514 	EVP_PKEY *pkey = (EVP_PKEY *) key;
3515 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3516 	OSSL_ENCODER_CTX *ctx;
3517 	int selection;
3518 	unsigned char *pdata = NULL;
3519 	size_t pdata_len = 0;
3520 	EVP_PKEY *copy = NULL;
3521 	struct wpabuf *buf = NULL;
3522 
3523 	if (EVP_PKEY_get_ec_point_conv_form(pkey) !=
3524 	    POINT_CONVERSION_COMPRESSED) {
3525 		copy = EVP_PKEY_dup(pkey);
3526 		if (!copy)
3527 			return NULL;
3528 		if (EVP_PKEY_set_utf8_string_param(
3529 			    copy, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
3530 			    OSSL_PKEY_EC_POINT_CONVERSION_FORMAT_COMPRESSED) !=
3531 		    1) {
3532 			wpa_printf(MSG_INFO,
3533 				   "OpenSSL: Failed to set compressed format");
3534 			EVP_PKEY_free(copy);
3535 			return NULL;
3536 		}
3537 		pkey = copy;
3538 	}
3539 
3540 	selection = OSSL_KEYMGMT_SELECT_ALL_PARAMETERS |
3541 		OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
3542 
3543 	ctx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "DER",
3544 					    "SubjectPublicKeyInfo",
3545 					    NULL);
3546 	if (!ctx || OSSL_ENCODER_to_data(ctx, &pdata, &pdata_len) != 1) {
3547 		wpa_printf(MSG_INFO,
3548 			   "OpenSSL: Failed to encode SubjectPublicKeyInfo: %s",
3549 			   ERR_error_string(ERR_get_error(), NULL));
3550 		pdata = NULL;
3551 	}
3552 	OSSL_ENCODER_CTX_free(ctx);
3553 	if (pdata) {
3554 		buf = wpabuf_alloc_copy(pdata, pdata_len);
3555 		OPENSSL_free(pdata);
3556 	}
3557 
3558 	EVP_PKEY_free(copy);
3559 
3560 	return buf;
3561 #else /* OpenSSL version >= 3.0 */
3562 #ifdef OPENSSL_IS_BORINGSSL
3563 	unsigned char *der = NULL;
3564 	int der_len;
3565 	const EC_KEY *eckey;
3566 	struct wpabuf *ret = NULL;
3567 	size_t len;
3568 	const EC_GROUP *group;
3569 	const EC_POINT *point;
3570 	BN_CTX *ctx;
3571 	EC_COMP_PUBKEY *pubkey = NULL;
3572 	int nid;
3573 
3574 	ctx = BN_CTX_new();
3575 	eckey = EVP_PKEY_get0_EC_KEY(pkey);
3576 	if (!ctx || !eckey)
3577 		goto fail;
3578 
3579 	group = EC_KEY_get0_group(eckey);
3580 	point = EC_KEY_get0_public_key(eckey);
3581 	if (!group || !point)
3582 		goto fail;
3583 	nid = EC_GROUP_get_curve_name(group);
3584 
3585 	pubkey = EC_COMP_PUBKEY_new();
3586 	if (!pubkey ||
3587 	    X509_ALGOR_set0(pubkey->alg, OBJ_nid2obj(EVP_PKEY_EC),
3588 			    V_ASN1_OBJECT, (void *) OBJ_nid2obj(nid)) != 1)
3589 		goto fail;
3590 
3591 	len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED,
3592 				 NULL, 0, ctx);
3593 	if (len == 0)
3594 		goto fail;
3595 
3596 	der = OPENSSL_malloc(len);
3597 	if (!der)
3598 		goto fail;
3599 	len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED,
3600 				 der, len, ctx);
3601 
3602 	OPENSSL_free(pubkey->pub_key->data);
3603 	pubkey->pub_key->data = der;
3604 	der = NULL;
3605 	pubkey->pub_key->length = len;
3606 	/* No unused bits */
3607 	pubkey->pub_key->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
3608 	pubkey->pub_key->flags |= ASN1_STRING_FLAG_BITS_LEFT;
3609 
3610 	der_len = i2d_EC_COMP_PUBKEY(pubkey, &der);
3611 	if (der_len <= 0) {
3612 		wpa_printf(MSG_ERROR,
3613 			   "BoringSSL: Failed to build DER encoded public key");
3614 		goto fail;
3615 	}
3616 
3617 	ret = wpabuf_alloc_copy(der, der_len);
3618 fail:
3619 	EC_COMP_PUBKEY_free(pubkey);
3620 	OPENSSL_free(der);
3621 	BN_CTX_free(ctx);
3622 	return ret;
3623 #else /* OPENSSL_IS_BORINGSSL */
3624 	unsigned char *der = NULL;
3625 	int der_len;
3626 	struct wpabuf *buf;
3627 	EC_KEY *eckey;
3628 
3629 	eckey = EVP_PKEY_get1_EC_KEY(pkey);
3630 	if (!eckey)
3631 		return NULL;
3632 
3633 	/* For now, all users expect COMPRESSED form */
3634 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
3635 
3636 	der_len = i2d_PUBKEY((EVP_PKEY *) key, &der);
3637 	EC_KEY_free(eckey);
3638 	if (der_len <= 0) {
3639 		wpa_printf(MSG_INFO, "OpenSSL: i2d_PUBKEY() failed: %s",
3640 			   ERR_error_string(ERR_get_error(), NULL));
3641 		return NULL;
3642 	}
3643 
3644 	buf = wpabuf_alloc_copy(der, der_len);
3645 	OPENSSL_free(der);
3646 	return buf;
3647 #endif /* OPENSSL_IS_BORINGSSL */
3648 #endif /* OpenSSL version >= 3.0 */
3649 }
3650 
3651 
crypto_ec_key_get_ecprivate_key(struct crypto_ec_key * key,bool include_pub)3652 struct wpabuf * crypto_ec_key_get_ecprivate_key(struct crypto_ec_key *key,
3653 						bool include_pub)
3654 {
3655 	EVP_PKEY *pkey = (EVP_PKEY *) key;
3656 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3657 	OSSL_ENCODER_CTX *ctx;
3658 	int selection;
3659 	unsigned char *pdata = NULL;
3660 	size_t pdata_len = 0;
3661 	struct wpabuf *buf;
3662 	EVP_PKEY *copy = NULL;
3663 
3664 	selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS |
3665 		OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
3666 	if (include_pub) {
3667 		selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
3668 	} else {
3669 		/* Not including OSSL_KEYMGMT_SELECT_PUBLIC_KEY does not seem
3670 		 * to really be sufficient, so clone the key and explicitly
3671 		 * mark it not to include the public key. */
3672 		copy = EVP_PKEY_dup(pkey);
3673 		if (!copy)
3674 			return NULL;
3675 		EVP_PKEY_set_int_param(copy, OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC,
3676 				       0);
3677 		pkey = copy;
3678 	}
3679 
3680 	ctx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "DER",
3681 					    "type-specific", NULL);
3682 	if (!ctx || OSSL_ENCODER_to_data(ctx, &pdata, &pdata_len) != 1) {
3683 		OSSL_ENCODER_CTX_free(ctx);
3684 		EVP_PKEY_free(copy);
3685 		return NULL;
3686 	}
3687 	OSSL_ENCODER_CTX_free(ctx);
3688 	buf = wpabuf_alloc_copy(pdata, pdata_len);
3689 	OPENSSL_free(pdata);
3690 	EVP_PKEY_free(copy);
3691 	return buf;
3692 #else /* OpenSSL version >= 3.0 */
3693 	EC_KEY *eckey;
3694 	unsigned char *der = NULL;
3695 	int der_len;
3696 	struct wpabuf *buf;
3697 	unsigned int key_flags;
3698 
3699 	eckey = EVP_PKEY_get1_EC_KEY(pkey);
3700 	if (!eckey)
3701 		return NULL;
3702 
3703 	key_flags = EC_KEY_get_enc_flags(eckey);
3704 	if (include_pub)
3705 		key_flags &= ~EC_PKEY_NO_PUBKEY;
3706 	else
3707 		key_flags |= EC_PKEY_NO_PUBKEY;
3708 	EC_KEY_set_enc_flags(eckey, key_flags);
3709 
3710 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_UNCOMPRESSED);
3711 
3712 	der_len = i2d_ECPrivateKey(eckey, &der);
3713 	EC_KEY_free(eckey);
3714 	if (der_len <= 0)
3715 		return NULL;
3716 	buf = wpabuf_alloc_copy(der, der_len);
3717 	OPENSSL_free(der);
3718 
3719 	return buf;
3720 #endif /* OpenSSL version >= 3.0 */
3721 }
3722 
3723 
crypto_ec_key_get_pubkey_point(struct crypto_ec_key * key,int prefix)3724 struct wpabuf * crypto_ec_key_get_pubkey_point(struct crypto_ec_key *key,
3725 					       int prefix)
3726 {
3727 	EVP_PKEY *pkey = (EVP_PKEY *) key;
3728 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3729 	struct wpabuf *buf;
3730 	unsigned char *pos;
3731 	size_t pub_len = OSSL_PARAM_UNMODIFIED;
3732 
3733 	buf = NULL;
3734 	if (!EVP_PKEY_is_a(pkey, "EC") ||
3735 	    EVP_PKEY_get_octet_string_param(pkey,
3736 					    OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
3737 					    NULL, 0, &pub_len) < 0 ||
3738 	    pub_len == OSSL_PARAM_UNMODIFIED ||
3739 	    !(buf = wpabuf_alloc(pub_len)) ||
3740 	    EVP_PKEY_get_octet_string_param(pkey,
3741 					    OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
3742 					    wpabuf_put(buf, pub_len),
3743 					    pub_len, NULL) != 1 ||
3744 	    wpabuf_head_u8(buf)[0] != 0x04) {
3745 		wpa_printf(MSG_INFO,
3746 			   "OpenSSL: Failed to get encoded public key: %s",
3747 			   ERR_error_string(ERR_get_error(), NULL));
3748 		wpabuf_free(buf);
3749 		return NULL;
3750 	}
3751 
3752 	if (!prefix) {
3753 		/* Remove 0x04 prefix if requested */
3754 		pos = wpabuf_mhead(buf);
3755 		os_memmove(pos, pos + 1, pub_len - 1);
3756 		buf->used--;
3757 	}
3758 
3759 	return buf;
3760 #else /* OpenSSL version >= 3.0 */
3761 	int len, res;
3762 	EC_KEY *eckey;
3763 	struct wpabuf *buf;
3764 	unsigned char *pos;
3765 
3766 	eckey = EVP_PKEY_get1_EC_KEY(pkey);
3767 	if (!eckey)
3768 		return NULL;
3769 	EC_KEY_set_conv_form(eckey, POINT_CONVERSION_UNCOMPRESSED);
3770 	len = i2o_ECPublicKey(eckey, NULL);
3771 	if (len <= 0) {
3772 		wpa_printf(MSG_ERROR,
3773 			   "OpenSSL: Failed to determine public key encoding length");
3774 		EC_KEY_free(eckey);
3775 		return NULL;
3776 	}
3777 
3778 	buf = wpabuf_alloc(len);
3779 	if (!buf) {
3780 		EC_KEY_free(eckey);
3781 		return NULL;
3782 	}
3783 
3784 	pos = wpabuf_put(buf, len);
3785 	res = i2o_ECPublicKey(eckey, &pos);
3786 	EC_KEY_free(eckey);
3787 	if (res != len) {
3788 		wpa_printf(MSG_ERROR,
3789 			   "OpenSSL: Failed to encode public key (res=%d/%d)",
3790 			   res, len);
3791 		wpabuf_free(buf);
3792 		return NULL;
3793 	}
3794 
3795 	if (!prefix) {
3796 		/* Remove 0x04 prefix if requested */
3797 		pos = wpabuf_mhead(buf);
3798 		os_memmove(pos, pos + 1, len - 1);
3799 		buf->used--;
3800 	}
3801 
3802 	return buf;
3803 #endif /* OpenSSL version >= 3.0 */
3804 }
3805 
3806 
3807 struct crypto_ec_point *
crypto_ec_key_get_public_key(struct crypto_ec_key * key)3808 crypto_ec_key_get_public_key(struct crypto_ec_key *key)
3809 {
3810 	EVP_PKEY *pkey = (EVP_PKEY *) key;
3811 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3812 	char group[64];
3813 	unsigned char pub[256];
3814 	size_t len;
3815 	EC_POINT *point = NULL;
3816 	EC_GROUP *grp;
3817 	int res = 0;
3818 	OSSL_PARAM params[2];
3819 
3820 	if (!EVP_PKEY_is_a(pkey, "EC") ||
3821 	    EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME,
3822 					   group, sizeof(group), &len) != 1 ||
3823 	    EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY,
3824 					    pub, sizeof(pub), &len) != 1)
3825 		return NULL;
3826 
3827 	params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
3828 						     group, 0);
3829 	params[1] = OSSL_PARAM_construct_end();
3830 	grp = EC_GROUP_new_from_params(params, NULL, NULL);
3831 	if (!grp)
3832 		goto fail;
3833 	point = EC_POINT_new(grp);
3834 	if (!point)
3835 		goto fail;
3836 	res = EC_POINT_oct2point(grp, point, pub, len, NULL);
3837 
3838 fail:
3839 	if (res != 1) {
3840 		EC_POINT_free(point);
3841 		point = NULL;
3842 	}
3843 
3844 	EC_GROUP_free(grp);
3845 
3846 	return (struct crypto_ec_point *) point;
3847 #else /* OpenSSL version >= 3.0 */
3848 	const EC_KEY *eckey;
3849 	const EC_POINT *point;
3850 	const EC_GROUP *group;
3851 
3852 	eckey = EVP_PKEY_get0_EC_KEY(pkey);
3853 	if (!eckey)
3854 		return NULL;
3855 	group = EC_KEY_get0_group(eckey);
3856 	if (!group)
3857 		return NULL;
3858 	point = EC_KEY_get0_public_key(eckey);
3859 	if (!point)
3860 		return NULL;
3861 	return (struct crypto_ec_point *) EC_POINT_dup(point, group);
3862 #endif /* OpenSSL version >= 3.0 */
3863 }
3864 
3865 
3866 struct crypto_bignum *
crypto_ec_key_get_private_key(struct crypto_ec_key * key)3867 crypto_ec_key_get_private_key(struct crypto_ec_key *key)
3868 {
3869 	EVP_PKEY *pkey = (EVP_PKEY *) key;
3870 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3871 	BIGNUM *bn = NULL;
3872 
3873 	if (!EVP_PKEY_is_a(pkey, "EC") ||
3874 	    EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_PRIV_KEY, &bn) != 1)
3875 		return NULL;
3876 	return (struct crypto_bignum *) bn;
3877 #else /* OpenSSL version >= 3.0 */
3878 	const EC_KEY *eckey;
3879 	const BIGNUM *bn;
3880 
3881 	eckey = EVP_PKEY_get0_EC_KEY(pkey);
3882 	if (!eckey)
3883 		return NULL;
3884 	bn = EC_KEY_get0_private_key(eckey);
3885 	if (!bn)
3886 		return NULL;
3887 	return (struct crypto_bignum *) BN_dup(bn);
3888 #endif /* OpenSSL version >= 3.0 */
3889 }
3890 
3891 
crypto_ec_key_sign(struct crypto_ec_key * key,const u8 * data,size_t len)3892 struct wpabuf * crypto_ec_key_sign(struct crypto_ec_key *key, const u8 *data,
3893 				   size_t len)
3894 {
3895 	EVP_PKEY_CTX *pkctx;
3896 	struct wpabuf *sig_der;
3897 	size_t sig_len;
3898 
3899 	sig_len = EVP_PKEY_size((EVP_PKEY *) key);
3900 	sig_der = wpabuf_alloc(sig_len);
3901 	if (!sig_der)
3902 		return NULL;
3903 
3904 	pkctx = EVP_PKEY_CTX_new((EVP_PKEY *) key, NULL);
3905 	if (!pkctx ||
3906 	    EVP_PKEY_sign_init(pkctx) <= 0 ||
3907 	    EVP_PKEY_sign(pkctx, wpabuf_put(sig_der, 0), &sig_len,
3908 			  data, len) <= 0) {
3909 		wpabuf_free(sig_der);
3910 		sig_der = NULL;
3911 	} else {
3912 		wpabuf_put(sig_der, sig_len);
3913 	}
3914 
3915 	EVP_PKEY_CTX_free(pkctx);
3916 	return sig_der;
3917 }
3918 
3919 
openssl_evp_pkey_ec_prime_len(struct crypto_ec_key * key)3920 static int openssl_evp_pkey_ec_prime_len(struct crypto_ec_key *key)
3921 {
3922 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3923 	char gname[50];
3924 	int nid;
3925 	EC_GROUP *group;
3926 	BIGNUM *prime = NULL;
3927 	int prime_len = -1;
3928 
3929 	if (EVP_PKEY_get_group_name((EVP_PKEY *) key, gname, sizeof(gname),
3930 				    NULL) != 1)
3931 		return -1;
3932 	nid = OBJ_txt2nid(gname);
3933 	group = EC_GROUP_new_by_curve_name(nid);
3934 	prime = BN_new();
3935 	if (!group || !prime)
3936 		goto fail;
3937 	if (EC_GROUP_get_curve(group, prime, NULL, NULL, NULL) == 1)
3938 		prime_len = BN_num_bytes(prime);
3939 fail:
3940 	EC_GROUP_free(group);
3941 	BN_free(prime);
3942 	return prime_len;
3943 #else
3944 	const EC_GROUP *group;
3945 	const EC_KEY *eckey;
3946 	BIGNUM *prime = NULL;
3947 	int prime_len = -1;
3948 
3949 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
3950 	if (!eckey)
3951 		goto fail;
3952 	group = EC_KEY_get0_group(eckey);
3953 	prime = BN_new();
3954 	if (!prime || !group ||
3955 	    !EC_GROUP_get_curve(group, prime, NULL, NULL, NULL))
3956 		goto fail;
3957 	prime_len = BN_num_bytes(prime);
3958 fail:
3959 	BN_free(prime);
3960 	return prime_len;
3961 #endif
3962 }
3963 
3964 
crypto_ec_key_sign_r_s(struct crypto_ec_key * key,const u8 * data,size_t len)3965 struct wpabuf * crypto_ec_key_sign_r_s(struct crypto_ec_key *key,
3966 				       const u8 *data, size_t len)
3967 {
3968 	ECDSA_SIG *sig = NULL;
3969 	const BIGNUM *r, *s;
3970 	u8 *r_buf, *s_buf;
3971 	struct wpabuf *buf;
3972 	const unsigned char *p;
3973 	int prime_len;
3974 
3975 	prime_len = openssl_evp_pkey_ec_prime_len(key);
3976 	if (prime_len < 0)
3977 		return NULL;
3978 
3979 	buf = crypto_ec_key_sign(key, data, len);
3980 	if (!buf)
3981 		return NULL;
3982 
3983 	/* Extract (r,s) from Ecdsa-Sig-Value */
3984 
3985 	p = wpabuf_head(buf);
3986 	sig = d2i_ECDSA_SIG(NULL, &p, wpabuf_len(buf));
3987 	if (!sig)
3988 		goto fail;
3989 	ECDSA_SIG_get0(sig, &r, &s);
3990 
3991 	/* Re-use wpabuf returned by crypto_ec_key_sign() */
3992 	buf->used = 0;
3993 	r_buf = wpabuf_put(buf, prime_len);
3994 	s_buf = wpabuf_put(buf, prime_len);
3995 	if (crypto_bignum_to_bin((const struct crypto_bignum *) r, r_buf,
3996 				 prime_len, prime_len) < 0 ||
3997 	    crypto_bignum_to_bin((const struct crypto_bignum *) s, s_buf,
3998 				 prime_len, prime_len) < 0)
3999 		goto fail;
4000 
4001 out:
4002 	ECDSA_SIG_free(sig);
4003 	return buf;
4004 fail:
4005 	wpabuf_clear_free(buf);
4006 	buf = NULL;
4007 	goto out;
4008 }
4009 
4010 
crypto_ec_key_verify_signature(struct crypto_ec_key * key,const u8 * data,size_t len,const u8 * sig,size_t sig_len)4011 int crypto_ec_key_verify_signature(struct crypto_ec_key *key, const u8 *data,
4012 				   size_t len, const u8 *sig, size_t sig_len)
4013 {
4014 	EVP_PKEY_CTX *pkctx;
4015 	int ret;
4016 
4017 	pkctx = EVP_PKEY_CTX_new((EVP_PKEY *) key, NULL);
4018 	if (!pkctx || EVP_PKEY_verify_init(pkctx) <= 0) {
4019 		EVP_PKEY_CTX_free(pkctx);
4020 		return -1;
4021 	}
4022 
4023 	ret = EVP_PKEY_verify(pkctx, sig, sig_len, data, len);
4024 	EVP_PKEY_CTX_free(pkctx);
4025 	if (ret == 1)
4026 		return 1; /* signature ok */
4027 	if (ret == 0)
4028 		return 0; /* incorrect signature */
4029 	return -1;
4030 }
4031 
4032 
crypto_ec_key_verify_signature_r_s(struct crypto_ec_key * key,const u8 * data,size_t len,const u8 * r,size_t r_len,const u8 * s,size_t s_len)4033 int crypto_ec_key_verify_signature_r_s(struct crypto_ec_key *key,
4034 				       const u8 *data, size_t len,
4035 				       const u8 *r, size_t r_len,
4036 				       const u8 *s, size_t s_len)
4037 {
4038 	ECDSA_SIG *sig;
4039 	BIGNUM *r_bn, *s_bn;
4040 	unsigned char *der = NULL;
4041 	int der_len;
4042 	int ret = -1;
4043 
4044 	r_bn = BN_bin2bn(r, r_len, NULL);
4045 	s_bn = BN_bin2bn(s, s_len, NULL);
4046 	sig = ECDSA_SIG_new();
4047 	if (!r_bn || !s_bn || !sig || ECDSA_SIG_set0(sig, r_bn, s_bn) != 1)
4048 		goto fail;
4049 	r_bn = NULL;
4050 	s_bn = NULL;
4051 
4052 	der_len = i2d_ECDSA_SIG(sig, &der);
4053 	if (der_len <= 0) {
4054 		wpa_printf(MSG_DEBUG,
4055 			   "OpenSSL: Could not DER encode signature");
4056 		goto fail;
4057 	}
4058 
4059 	ret = crypto_ec_key_verify_signature(key, data, len, der, der_len);
4060 
4061 fail:
4062 	OPENSSL_free(der);
4063 	BN_free(r_bn);
4064 	BN_free(s_bn);
4065 	ECDSA_SIG_free(sig);
4066 	return ret;
4067 }
4068 
4069 
crypto_ec_key_group(struct crypto_ec_key * key)4070 int crypto_ec_key_group(struct crypto_ec_key *key)
4071 {
4072 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4073 	char gname[50];
4074 	int nid;
4075 
4076 	if (EVP_PKEY_get_group_name((EVP_PKEY *) key, gname, sizeof(gname),
4077 				    NULL) != 1)
4078 		return -1;
4079 	nid = OBJ_txt2nid(gname);
4080 #else
4081 	const EC_KEY *eckey;
4082 	const EC_GROUP *group;
4083 	int nid;
4084 
4085 	eckey = EVP_PKEY_get0_EC_KEY((EVP_PKEY *) key);
4086 	if (!eckey)
4087 		return -1;
4088 	group = EC_KEY_get0_group(eckey);
4089 	if (!group)
4090 		return -1;
4091 	nid = EC_GROUP_get_curve_name(group);
4092 #endif
4093 	switch (nid) {
4094 	case NID_X9_62_prime256v1:
4095 		return 19;
4096 	case NID_secp384r1:
4097 		return 20;
4098 	case NID_secp521r1:
4099 		return 21;
4100 #ifdef NID_brainpoolP256r1
4101 	case NID_brainpoolP256r1:
4102 		return 28;
4103 #endif /* NID_brainpoolP256r1 */
4104 #ifdef NID_brainpoolP384r1
4105 	case NID_brainpoolP384r1:
4106 		return 29;
4107 #endif /* NID_brainpoolP384r1 */
4108 #ifdef NID_brainpoolP512r1
4109 	case NID_brainpoolP512r1:
4110 		return 30;
4111 #endif /* NID_brainpoolP512r1 */
4112 	default:
4113 		wpa_printf(MSG_ERROR,
4114 			   "OpenSSL: Unsupported curve (nid=%d) in EC key",
4115 			   nid);
4116 		return -1;
4117 	}
4118 }
4119 
4120 
crypto_ec_key_cmp(struct crypto_ec_key * key1,struct crypto_ec_key * key2)4121 int crypto_ec_key_cmp(struct crypto_ec_key *key1, struct crypto_ec_key *key2)
4122 {
4123 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4124 	if (EVP_PKEY_eq((EVP_PKEY *) key1, (EVP_PKEY *) key2) != 1)
4125 		return -1;
4126 #else
4127 	if (EVP_PKEY_cmp((EVP_PKEY *) key1, (EVP_PKEY *) key2) != 1)
4128 		return -1;
4129 #endif
4130 	return 0;
4131 }
4132 
4133 
crypto_ec_key_debug_print(const struct crypto_ec_key * key,const char * title)4134 void crypto_ec_key_debug_print(const struct crypto_ec_key *key,
4135 			       const char *title)
4136 {
4137 	BIO *out;
4138 	size_t rlen;
4139 	char *txt;
4140 	int res;
4141 
4142 	out = BIO_new(BIO_s_mem());
4143 	if (!out)
4144 		return;
4145 
4146 	EVP_PKEY_print_private(out, (EVP_PKEY *) key, 0, NULL);
4147 	rlen = BIO_ctrl_pending(out);
4148 	txt = os_malloc(rlen + 1);
4149 	if (txt) {
4150 		res = BIO_read(out, txt, rlen);
4151 		if (res > 0) {
4152 			txt[res] = '\0';
4153 			wpa_printf(MSG_DEBUG, "%s: %s", title, txt);
4154 		}
4155 		os_free(txt);
4156 	}
4157 	BIO_free(out);
4158 }
4159 
4160 
crypto_pkcs7_get_certificates(const struct wpabuf * pkcs7)4161 struct wpabuf * crypto_pkcs7_get_certificates(const struct wpabuf *pkcs7)
4162 {
4163 #ifdef OPENSSL_IS_BORINGSSL
4164 	CBS pkcs7_cbs;
4165 #else /* OPENSSL_IS_BORINGSSL */
4166 	PKCS7 *p7 = NULL;
4167 	const unsigned char *p = wpabuf_head(pkcs7);
4168 #endif /* OPENSSL_IS_BORINGSSL */
4169 	STACK_OF(X509) *certs;
4170 	int i, num;
4171 	BIO *out = NULL;
4172 	size_t rlen;
4173 	struct wpabuf *pem = NULL;
4174 	int res;
4175 
4176 #ifdef OPENSSL_IS_BORINGSSL
4177 	certs = sk_X509_new_null();
4178 	if (!certs)
4179 		goto fail;
4180 	CBS_init(&pkcs7_cbs, wpabuf_head(pkcs7), wpabuf_len(pkcs7));
4181 	if (!PKCS7_get_certificates(certs, &pkcs7_cbs)) {
4182 		wpa_printf(MSG_INFO,
4183 			   "OpenSSL: Could not parse PKCS#7 object: %s",
4184 			   ERR_error_string(ERR_get_error(), NULL));
4185 		goto fail;
4186 	}
4187 #else /* OPENSSL_IS_BORINGSSL */
4188 	p7 = d2i_PKCS7(NULL, &p, wpabuf_len(pkcs7));
4189 	if (!p7) {
4190 		wpa_printf(MSG_INFO,
4191 			   "OpenSSL: Could not parse PKCS#7 object: %s",
4192 			   ERR_error_string(ERR_get_error(), NULL));
4193 		goto fail;
4194 	}
4195 
4196 	switch (OBJ_obj2nid(p7->type)) {
4197 	case NID_pkcs7_signed:
4198 		certs = p7->d.sign->cert;
4199 		break;
4200 	case NID_pkcs7_signedAndEnveloped:
4201 		certs = p7->d.signed_and_enveloped->cert;
4202 		break;
4203 	default:
4204 		certs = NULL;
4205 		break;
4206 	}
4207 #endif /* OPENSSL_IS_BORINGSSL */
4208 
4209 	if (!certs || ((num = sk_X509_num(certs)) == 0)) {
4210 		wpa_printf(MSG_INFO,
4211 			   "OpenSSL: No certificates found in PKCS#7 object");
4212 		goto fail;
4213 	}
4214 
4215 	out = BIO_new(BIO_s_mem());
4216 	if (!out)
4217 		goto fail;
4218 
4219 	for (i = 0; i < num; i++) {
4220 		X509 *cert = sk_X509_value(certs, i);
4221 
4222 		PEM_write_bio_X509(out, cert);
4223 	}
4224 
4225 	rlen = BIO_ctrl_pending(out);
4226 	pem = wpabuf_alloc(rlen);
4227 	if (!pem)
4228 		goto fail;
4229 	res = BIO_read(out, wpabuf_put(pem, 0), rlen);
4230 	if (res <= 0) {
4231 		wpabuf_free(pem);
4232 		pem = NULL;
4233 		goto fail;
4234 	}
4235 	wpabuf_put(pem, res);
4236 
4237 fail:
4238 #ifdef OPENSSL_IS_BORINGSSL
4239 	if (certs)
4240 		sk_X509_pop_free(certs, X509_free);
4241 #else /* OPENSSL_IS_BORINGSSL */
4242 	PKCS7_free(p7);
4243 #endif /* OPENSSL_IS_BORINGSSL */
4244 	if (out)
4245 		BIO_free_all(out);
4246 
4247 	return pem;
4248 }
4249 
4250 
crypto_csr_init()4251 struct crypto_csr * crypto_csr_init()
4252 {
4253 	return (struct crypto_csr *)X509_REQ_new();
4254 }
4255 
4256 
crypto_csr_verify(const struct wpabuf * req)4257 struct crypto_csr * crypto_csr_verify(const struct wpabuf *req)
4258 {
4259 	X509_REQ *csr;
4260 	EVP_PKEY *pkey = NULL;
4261 	const u8 *der = wpabuf_head(req);
4262 
4263 	csr = d2i_X509_REQ(NULL, &der, wpabuf_len(req));
4264 	if (!csr)
4265 		return NULL;
4266 
4267 	pkey = X509_REQ_get_pubkey((X509_REQ *)csr);
4268 	if (!pkey)
4269 		goto fail;
4270 
4271 	if (X509_REQ_verify((X509_REQ *)csr, pkey) != 1)
4272 		goto fail;
4273 
4274 	return (struct crypto_csr *)csr;
4275 fail:
4276 	X509_REQ_free(csr);
4277 	return NULL;
4278 }
4279 
4280 
crypto_csr_deinit(struct crypto_csr * csr)4281 void crypto_csr_deinit(struct crypto_csr *csr)
4282 {
4283 	X509_REQ_free((X509_REQ *)csr);
4284 }
4285 
4286 
crypto_csr_set_ec_public_key(struct crypto_csr * csr,struct crypto_ec_key * key)4287 int crypto_csr_set_ec_public_key(struct crypto_csr *csr, struct crypto_ec_key *key)
4288 {
4289 	if (!X509_REQ_set_pubkey((X509_REQ *)csr, (EVP_PKEY *)key))
4290 		return -1;
4291 
4292 	return 0;
4293 }
4294 
4295 
crypto_csr_set_name(struct crypto_csr * csr,enum crypto_csr_name type,const char * name)4296 int crypto_csr_set_name(struct crypto_csr *csr, enum crypto_csr_name type,
4297 			const char *name)
4298 {
4299 	X509_NAME *n;
4300 	int nid;
4301 
4302 	switch (type) {
4303 	case CSR_NAME_CN:
4304 		nid = NID_commonName;
4305 		break;
4306 	case CSR_NAME_SN:
4307 		nid = NID_surname;
4308 		break;
4309 	case CSR_NAME_C:
4310 		nid = NID_countryName;
4311 		break;
4312 	case CSR_NAME_O:
4313 		nid = NID_organizationName;
4314 		break;
4315 	case CSR_NAME_OU:
4316 		nid = NID_organizationalUnitName;
4317 		break;
4318 	default:
4319 		return -1;
4320 	}
4321 
4322 	n = X509_REQ_get_subject_name((X509_REQ *) csr);
4323 	if (!n)
4324 		return -1;
4325 
4326 #if OPENSSL_VERSION_NUMBER < 0x10100000L
4327 	if (!X509_NAME_add_entry_by_NID(n, nid, MBSTRING_UTF8,
4328 					(unsigned char *) name,
4329 					os_strlen(name), -1, 0))
4330 		return -1;
4331 #else
4332 	if (!X509_NAME_add_entry_by_NID(n, nid, MBSTRING_UTF8,
4333 					(const unsigned char *) name,
4334 					os_strlen(name), -1, 0))
4335 		return -1;
4336 #endif
4337 
4338 	return 0;
4339 }
4340 
4341 
crypto_csr_set_attribute(struct crypto_csr * csr,enum crypto_csr_attr attr,int attr_type,const u8 * value,size_t len)4342 int crypto_csr_set_attribute(struct crypto_csr *csr, enum crypto_csr_attr attr,
4343 			     int attr_type, const u8 *value, size_t len)
4344 {
4345 	int nid;
4346 
4347 	switch (attr) {
4348 	case CSR_ATTR_CHALLENGE_PASSWORD:
4349 		nid = NID_pkcs9_challengePassword;
4350 		break;
4351 	default:
4352 		return -1;
4353 	}
4354 
4355 	if (!X509_REQ_add1_attr_by_NID((X509_REQ *) csr, nid, attr_type, value,
4356 				       len))
4357 		return -1;
4358 
4359 	return 0;
4360 }
4361 
4362 
crypto_csr_get_attribute(struct crypto_csr * csr,enum crypto_csr_attr attr,size_t * len,int * type)4363 const u8 * crypto_csr_get_attribute(struct crypto_csr *csr,
4364 				    enum crypto_csr_attr attr,
4365 				    size_t *len, int *type)
4366 {
4367 	X509_ATTRIBUTE *attrib;
4368 	ASN1_TYPE *attrib_type;
4369 	ASN1_STRING *data;
4370 	int loc;
4371 	int nid;
4372 
4373 	switch (attr) {
4374 	case CSR_ATTR_CHALLENGE_PASSWORD:
4375 		nid = NID_pkcs9_challengePassword;
4376 		break;
4377 	default:
4378 		return NULL;
4379 	}
4380 
4381 	loc = X509_REQ_get_attr_by_NID((X509_REQ *) csr, nid, -1);
4382 	if (loc < 0)
4383 		return NULL;
4384 
4385 	attrib = X509_REQ_get_attr((X509_REQ *) csr, loc);
4386 	if (!attrib)
4387 		return NULL;
4388 
4389 	attrib_type = X509_ATTRIBUTE_get0_type(attrib, 0);
4390 	if (!attrib_type)
4391 		return NULL;
4392 	*type = ASN1_TYPE_get(attrib_type);
4393 	data = X509_ATTRIBUTE_get0_data(attrib, 0, *type, NULL);
4394 	if (!data)
4395 		return NULL;
4396 	*len = ASN1_STRING_length(data);
4397 	return ASN1_STRING_get0_data(data);
4398 }
4399 
4400 
crypto_csr_sign(struct crypto_csr * csr,struct crypto_ec_key * key,enum crypto_hash_alg algo)4401 struct wpabuf * crypto_csr_sign(struct crypto_csr *csr,
4402 				struct crypto_ec_key *key,
4403 				enum crypto_hash_alg algo)
4404 {
4405 	const EVP_MD *sign_md;
4406 	struct wpabuf *buf;
4407 	unsigned char *der = NULL;
4408 	int der_len;
4409 
4410 	switch (algo) {
4411 	case CRYPTO_HASH_ALG_SHA256:
4412 		sign_md = EVP_sha256();
4413 		break;
4414 	case CRYPTO_HASH_ALG_SHA384:
4415 		sign_md = EVP_sha384();
4416 		break;
4417 	case CRYPTO_HASH_ALG_SHA512:
4418 		sign_md = EVP_sha512();
4419 		break;
4420 	default:
4421 		return NULL;
4422 	}
4423 
4424 	if (!X509_REQ_sign((X509_REQ *) csr, (EVP_PKEY *) key, sign_md))
4425 		return NULL;
4426 
4427 	der_len = i2d_X509_REQ((X509_REQ *) csr, &der);
4428 	if (der_len < 0)
4429 		return NULL;
4430 
4431 	buf = wpabuf_alloc_copy(der, der_len);
4432 	OPENSSL_free(der);
4433 
4434 	return buf;
4435 }
4436 
4437 #endif /* CONFIG_ECC */
4438 
4439 
crypto_rsa_key_read_public(FILE * f)4440 static EVP_PKEY * crypto_rsa_key_read_public(FILE *f)
4441 {
4442 	EVP_PKEY *pkey;
4443 	X509 *x509;
4444 	const ASN1_TIME *not_before, *not_after;
4445 	int res_before, res_after;
4446 
4447 	pkey = PEM_read_PUBKEY(f, NULL, NULL, NULL);
4448 	if (pkey)
4449 		return pkey;
4450 
4451 	rewind(f);
4452 	x509 = PEM_read_X509(f, NULL, NULL, NULL);
4453 	if (!x509)
4454 		return NULL;
4455 
4456 	not_before = X509_get0_notBefore(x509);
4457 	not_after = X509_get0_notAfter(x509);
4458 	if (!not_before || !not_after)
4459 		goto fail;
4460 	res_before = X509_cmp_current_time(not_before);
4461 	res_after = X509_cmp_current_time(not_after);
4462 	if (!res_before || !res_after)
4463 		goto fail;
4464 	if (res_before > 0 || res_after < 0) {
4465 		wpa_printf(MSG_INFO,
4466 			   "OpenSSL: Certificate for RSA public key is not valid at this time (%d %d)",
4467 			   res_before, res_after);
4468 		goto fail;
4469 	}
4470 
4471 	pkey = X509_get_pubkey(x509);
4472 	X509_free(x509);
4473 
4474 	if (!pkey)
4475 		return NULL;
4476 	if (EVP_PKEY_base_id(pkey) != EVP_PKEY_RSA) {
4477 		wpa_printf(MSG_INFO, "OpenSSL: No RSA public key found");
4478 		EVP_PKEY_free(pkey);
4479 		return NULL;
4480 	}
4481 
4482 	return pkey;
4483 fail:
4484 	X509_free(x509);
4485 	return NULL;
4486 }
4487 
4488 
crypto_rsa_key_read(const char * file,bool private_key)4489 struct crypto_rsa_key * crypto_rsa_key_read(const char *file, bool private_key)
4490 {
4491 	FILE *f;
4492 	EVP_PKEY *pkey;
4493 
4494 	f = fopen(file, "r");
4495 	if (!f)
4496 		return NULL;
4497 	if (private_key)
4498 		pkey = PEM_read_PrivateKey(f, NULL, NULL, NULL);
4499 	else
4500 		pkey = crypto_rsa_key_read_public(f);
4501 	fclose(f);
4502 	return (struct crypto_rsa_key *) pkey;
4503 }
4504 
4505 
4506 #ifndef OPENSSL_NO_SHA256
4507 
crypto_rsa_oaep_sha256_encrypt(struct crypto_rsa_key * key,const struct wpabuf * in)4508 struct wpabuf * crypto_rsa_oaep_sha256_encrypt(struct crypto_rsa_key *key,
4509 					       const struct wpabuf *in)
4510 {
4511 #if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x30400000L
4512 	EVP_PKEY *pkey = (EVP_PKEY *) key;
4513 	EVP_PKEY_CTX *pkctx;
4514 	struct wpabuf *res = NULL;
4515 	size_t outlen;
4516 
4517 	pkctx = EVP_PKEY_CTX_new(pkey, NULL);
4518 	if (!pkctx)
4519 		goto fail;
4520 
4521 	if (EVP_PKEY_encrypt_init(pkctx) != 1 ||
4522 	    EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_OAEP_PADDING) <= 0 ||
4523 	    EVP_PKEY_CTX_set_rsa_oaep_md(pkctx, EVP_sha256()) <= 0 ||
4524 	    EVP_PKEY_encrypt(pkctx, NULL, &outlen, wpabuf_head(in),
4525 			     wpabuf_len(in)) != 1 ||
4526 	    !(res = wpabuf_alloc(outlen)) ||
4527 	    EVP_PKEY_encrypt(pkctx, wpabuf_put(res, 0), &outlen,
4528 			     wpabuf_head(in), wpabuf_len(in)) != 1) {
4529 		wpabuf_free(res);
4530 		res = NULL;
4531 		goto fail;
4532 	}
4533 	wpabuf_put(res, outlen);
4534 
4535 fail:
4536 	EVP_PKEY_CTX_free(pkctx);
4537 	return res;
4538 #else
4539 	wpa_printf(MSG_ERROR, "%s() not supported", __func__);
4540 	return NULL;
4541 #endif
4542 }
4543 
4544 
crypto_rsa_oaep_sha256_decrypt(struct crypto_rsa_key * key,const struct wpabuf * in)4545 struct wpabuf * crypto_rsa_oaep_sha256_decrypt(struct crypto_rsa_key *key,
4546 					       const struct wpabuf *in)
4547 {
4548 #if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x30400000L
4549 	EVP_PKEY *pkey = (EVP_PKEY *) key;
4550 	EVP_PKEY_CTX *pkctx;
4551 	struct wpabuf *res = NULL;
4552 	size_t outlen;
4553 
4554 	pkctx = EVP_PKEY_CTX_new(pkey, NULL);
4555 	if (!pkctx)
4556 		goto fail;
4557 
4558 	if (EVP_PKEY_decrypt_init(pkctx) != 1 ||
4559 	    EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_OAEP_PADDING) <= 0 ||
4560 	    EVP_PKEY_CTX_set_rsa_oaep_md(pkctx, EVP_sha256()) <= 0 ||
4561 	    EVP_PKEY_decrypt(pkctx, NULL, &outlen, wpabuf_head(in),
4562 			     wpabuf_len(in)) != 1 ||
4563 	    !(res = wpabuf_alloc(outlen)) ||
4564 	    EVP_PKEY_decrypt(pkctx, wpabuf_put(res, 0), &outlen,
4565 			     wpabuf_head(in), wpabuf_len(in)) != 1) {
4566 		wpabuf_free(res);
4567 		res = NULL;
4568 		goto fail;
4569 	}
4570 	wpabuf_put(res, outlen);
4571 
4572 fail:
4573 	EVP_PKEY_CTX_free(pkctx);
4574 	return res;
4575 #else
4576 	wpa_printf(MSG_ERROR, "%s() not supported", __func__);
4577 	return NULL;
4578 #endif
4579 }
4580 
4581 #endif /* OPENSSL_NO_SHA256 */
4582 
4583 
crypto_rsa_key_free(struct crypto_rsa_key * key)4584 void crypto_rsa_key_free(struct crypto_rsa_key *key)
4585 {
4586 	EVP_PKEY_free((EVP_PKEY *) key);
4587 }
4588 
4589 
4590 #ifdef CONFIG_DPP3
4591 
4592 #define HPKE_MAX_SHARED_SECRET_LEN 66
4593 #define HPKE_MAX_HASH_LEN 64
4594 #define HPKE_MAX_KEY_LEN 32
4595 #define HPKE_MAX_NONCE_LEN 12
4596 #define HPKE_MAX_PUB_LEN (1 + 2 * 66)
4597 
4598 struct hpke_context {
4599 	/* KEM */
4600 	enum hpke_kem_id kem_id;
4601 	int kem_nid;
4602 	int iana_group;
4603 	size_t n_pk;
4604 	size_t n_secret;
4605 	const EVP_MD *kem_h;
4606 	size_t kem_n_h;
4607 
4608 	/* KDF */
4609 	enum hpke_kdf_id kdf_id;
4610 	const EVP_MD *kdf_h;
4611 	size_t n_h;
4612 
4613 	/* AEAD */
4614 	enum hpke_aead_id aead_id;
4615 	const EVP_CIPHER *cipher;
4616 	size_t n_k;
4617 	size_t n_n;
4618 	size_t n_t;
4619 	u8 key[HPKE_MAX_KEY_LEN];
4620 	u8 base_nonce[HPKE_MAX_NONCE_LEN];
4621 };
4622 
4623 
hpke_free_context(struct hpke_context * ctx)4624 static void hpke_free_context(struct hpke_context *ctx)
4625 {
4626 	bin_clear_free(ctx, sizeof(*ctx));
4627 }
4628 
4629 
hpke_get_context(enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id,struct crypto_ec_key * key)4630 static struct hpke_context * hpke_get_context(enum hpke_kem_id kem_id,
4631 					      enum hpke_kdf_id kdf_id,
4632 					      enum hpke_aead_id aead_id,
4633 					      struct crypto_ec_key *key)
4634 {
4635 	struct hpke_context *ctx;
4636 	int group;
4637 
4638 	ctx = os_zalloc(sizeof(*ctx));
4639 	if (!ctx)
4640 		return NULL;
4641 
4642 	ctx->kem_id = kem_id;
4643 	switch (kem_id) {
4644 	case HPKE_DHKEM_P256_HKDF_SHA256:
4645 		ctx->kem_nid = NID_X9_62_prime256v1;
4646 		ctx->iana_group = 19;
4647 		ctx->n_pk = 65;
4648 		ctx->n_secret = 32;
4649 		ctx->kem_h = EVP_sha256();
4650 		ctx->kem_n_h = 32;
4651 		break;
4652 	case HPKE_DHKEM_P384_HKDF_SHA384:
4653 		ctx->kem_nid = NID_secp384r1;
4654 		ctx->iana_group = 20;
4655 		ctx->n_pk = 97;
4656 		ctx->n_secret = 48;
4657 		ctx->kem_h = EVP_sha384();
4658 		ctx->kem_n_h = 48;
4659 		break;
4660 	case HPKE_DHKEM_P521_HKDF_SHA512:
4661 		ctx->kem_nid = NID_secp521r1;
4662 		ctx->iana_group = 21;
4663 		ctx->n_pk = 133;
4664 		ctx->n_secret = 64;
4665 		ctx->kem_h = EVP_sha512();
4666 		ctx->kem_n_h = 64;
4667 		break;
4668 	default:
4669 		goto fail;
4670 	}
4671 
4672 	ctx->kdf_id = kdf_id;
4673 	switch (kdf_id) {
4674 	case HPKE_KDF_HKDF_SHA256:
4675 		ctx->kdf_h = EVP_sha256();
4676 		ctx->n_h = 32;
4677 		break;
4678 	case HPKE_KDF_HKDF_SHA384:
4679 		ctx->kdf_h = EVP_sha384();
4680 		ctx->n_h = 48;
4681 		break;
4682 	case HPKE_KDF_HKDF_SHA512:
4683 		ctx->kdf_h = EVP_sha512();
4684 		ctx->n_h = 64;
4685 		break;
4686 	default:
4687 		goto fail;
4688 	}
4689 
4690 	ctx->aead_id = aead_id;
4691 	switch (aead_id) {
4692 	case HPKE_AEAD_AES_128_GCM:
4693 		ctx->cipher = EVP_aes_128_gcm();
4694 		ctx->n_k = 16;
4695 		ctx->n_n = 12;
4696 		ctx->n_t = 16;
4697 		break;
4698 	case HPKE_AEAD_AES_256_GCM:
4699 		ctx->cipher = EVP_aes_256_gcm();
4700 		ctx->n_k = 32;
4701 		ctx->n_n = 12;
4702 		ctx->n_t = 16;
4703 		break;
4704 	default:
4705 		goto fail;
4706 	}
4707 
4708 	/* Convert BP-256/384/512 to P-256/384/521 for DPP */
4709 	group = crypto_ec_key_group(key);
4710 	if (group == 28 && ctx->iana_group == 19) {
4711 		ctx->iana_group = 28;
4712 	} else if (group == 29 && ctx->iana_group == 20) {
4713 		ctx->iana_group = 29;
4714 	} else if (group == 30 && ctx->iana_group == 21) {
4715 		ctx->iana_group = 30;
4716 		ctx->n_pk = 129;
4717 	}
4718 	if (group != ctx->iana_group) {
4719 		wpa_printf(MSG_INFO, "OpenSSL:%s:group mismatch (%d != %d)",
4720 			   __func__, group, ctx->iana_group);
4721 		goto fail;
4722 	}
4723 
4724 	return ctx;
4725 fail:
4726 	hpke_free_context(ctx);
4727 	return NULL;
4728 }
4729 
4730 
hpke_suite_id(struct hpke_context * ctx,bool kem,u8 * suite_id)4731 static size_t hpke_suite_id(struct hpke_context *ctx, bool kem, u8 *suite_id)
4732 {
4733 	size_t suite_id_len;
4734 
4735 	if (kem) {
4736 		os_memcpy(suite_id, "KEM", 3);
4737 		WPA_PUT_BE16(&suite_id[3], ctx->kem_id);
4738 		suite_id_len = 5;
4739 	} else {
4740 		os_memcpy(suite_id, "HPKE", 4);
4741 		WPA_PUT_BE16(&suite_id[4], ctx->kem_id);
4742 		WPA_PUT_BE16(&suite_id[6], ctx->kdf_id);
4743 		WPA_PUT_BE16(&suite_id[8], ctx->aead_id);
4744 		suite_id_len = 10;
4745 	}
4746 	return suite_id_len;
4747 }
4748 
4749 
hpke_labeled_extract(struct hpke_context * ctx,bool kem,const u8 * salt,size_t salt_len,const char * label,const u8 * ikm,size_t ikm_len,u8 * prk)4750 static int hpke_labeled_extract(struct hpke_context *ctx, bool kem,
4751 				const u8 *salt, size_t salt_len,
4752 				const char *label,
4753 				const u8 *ikm, size_t ikm_len, u8 *prk)
4754 {
4755 	u8 zero[HPKE_MAX_HASH_LEN];
4756 	u8 suite_id[10];
4757 	size_t suite_id_len;
4758 	unsigned int mdlen = kem ? ctx->kem_n_h : ctx->n_h;
4759 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4760 	EVP_MAC *hmac;
4761 	OSSL_PARAM params[2];
4762 	EVP_MAC_CTX *hctx;
4763 	size_t mlen;
4764 	int res;
4765 #else /* OpenSSL version >= 3.0 */
4766 	HMAC_CTX *hctx;
4767 	int res;
4768 #endif /* OpenSSL version >= 3.0 */
4769 
4770 	if (!salt || !salt_len) {
4771 		salt_len = mdlen;
4772 		os_memset(zero, 0, salt_len);
4773 		salt = zero;
4774 	}
4775 
4776 	suite_id_len = hpke_suite_id(ctx, kem, suite_id);
4777 
4778 	/* labeled_ikm = concat("HPKE-v1", suite_id, label, ikm)
4779 	 * return Extract(salt, labeled_ikm) */
4780 
4781 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4782 	hmac = EVP_MAC_fetch(NULL, "HMAC", NULL);
4783 	if (!hmac)
4784 		return -1;
4785 
4786 	params[0] = OSSL_PARAM_construct_utf8_string(
4787 		"digest",
4788 		(char *) EVP_MD_get0_name(kem ? ctx->kem_h : ctx->kdf_h), 0);
4789 	params[1] = OSSL_PARAM_construct_end();
4790 
4791 	hctx = EVP_MAC_CTX_new(hmac);
4792 	EVP_MAC_free(hmac);
4793 	if (!hctx)
4794 		return -1;
4795 
4796 	if (EVP_MAC_init(hctx, salt, salt_len, params) != 1)
4797 		goto fail;
4798 
4799 	if (EVP_MAC_update(hctx, (const unsigned char *) "HPKE-v1", 7) != 1 ||
4800 	    EVP_MAC_update(hctx, suite_id, suite_id_len) != 1 ||
4801 	    EVP_MAC_update(hctx, (const unsigned char *) label,
4802 			   os_strlen(label)) != 1 ||
4803 	    EVP_MAC_update(hctx, ikm, ikm_len) != 1)
4804 		goto fail;
4805 
4806 	res = EVP_MAC_final(hctx, prk, &mlen, mdlen);
4807 	EVP_MAC_CTX_free(hctx);
4808 
4809 	return res == 1 ? 0 : -1;
4810 fail:
4811 	EVP_MAC_CTX_free(hctx);
4812 	return -1;
4813 #else /* OpenSSL version >= 3.0 */
4814 	hctx = HMAC_CTX_new();
4815 	if (!hctx)
4816 		return -1;
4817 	res = HMAC_Init_ex(hctx, salt, salt_len, kem ? ctx->kem_h : ctx->kdf_h,
4818 			   NULL);
4819 	if (res != 1)
4820 		goto done;
4821 
4822 	HMAC_Update(hctx, (const unsigned char *) "HPKE-v1", 7);
4823 	HMAC_Update(hctx, suite_id, suite_id_len);
4824 	HMAC_Update(hctx, (const unsigned char *) label, os_strlen(label));
4825 	HMAC_Update(hctx, ikm, ikm_len);
4826 
4827 	res = HMAC_Final(hctx, prk, &mdlen);
4828 done:
4829 	HMAC_CTX_free(hctx);
4830 
4831 	return res == 1 ? 0 : -1;
4832 #endif /* OpenSSL version >= 3.0 */
4833 }
4834 
4835 
4836 static int
hpke_labeled_expand(struct hpke_context * ctx,bool kem,const u8 * prk,const char * label,const u8 * info,size_t info_len,u8 * out,size_t out_len)4837 hpke_labeled_expand(struct hpke_context *ctx, bool kem, const u8 *prk,
4838 		    const char *label, const u8 *info, size_t info_len,
4839 		    u8 *out, size_t out_len)
4840 {
4841 	u8 suite_id[10];
4842 	size_t suite_id_len;
4843 	u8 hash[HPKE_MAX_HASH_LEN];
4844 	u8 iter = 0;
4845 	size_t label_len = os_strlen(label);
4846 	u8 *pos;
4847 	size_t left = out_len, clen;
4848 	int res = -1;
4849 	u8 *labeled_info;
4850 	size_t labeled_info_len;
4851 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4852 	EVP_MAC *hmac;
4853 	OSSL_PARAM params[2];
4854 	EVP_MAC_CTX *hctx = NULL;
4855 	size_t mdlen;
4856 #else /* OpenSSL version >= 3.0 */
4857 	HMAC_CTX *hctx;
4858 	unsigned int mdlen;
4859 #endif /* OpenSSL version >= 3.0 */
4860 
4861 	/* labeled_info = concat(I2OSP(L, 2), "HPKE-v1", suite_id,
4862 	 *                       label, info)
4863 	 * return Expand(prk, labeled_info, L) */
4864 	suite_id_len = hpke_suite_id(ctx, kem, suite_id);
4865 	labeled_info_len = 2 + 7 + suite_id_len + label_len + info_len;
4866 	labeled_info = os_malloc(labeled_info_len);
4867 	if (!labeled_info)
4868 		return -1;
4869 	pos = labeled_info;
4870 	WPA_PUT_BE16(pos, out_len);
4871 	pos += 2;
4872 	os_memcpy(pos, "HPKE-v1", 7);
4873 	pos += 7;
4874 	os_memcpy(pos, suite_id, suite_id_len);
4875 	pos += suite_id_len;
4876 	os_memcpy(pos, label, label_len);
4877 	pos += label_len;
4878 	if (info && info_len)
4879 		os_memcpy(pos, info, info_len);
4880 
4881 	pos = out;
4882 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4883 	hmac = EVP_MAC_fetch(NULL, "HMAC", NULL);
4884 	if (!hmac)
4885 		goto fail;
4886 
4887 	params[0] = OSSL_PARAM_construct_utf8_string(
4888 		"digest",
4889 		(char *) EVP_MD_get0_name(kem ? ctx->kem_h : ctx->kdf_h), 0);
4890 	params[1] = OSSL_PARAM_construct_end();
4891 #else /* OpenSSL version >= 3.0 */
4892 	hctx = HMAC_CTX_new();
4893 	if (!hctx)
4894 		goto fail;
4895 #endif /* OpenSSL version >= 3.0 */
4896 
4897 	while (left > 0) {
4898 		mdlen = kem ? ctx->kem_n_h : ctx->n_h;
4899 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4900 		EVP_MAC_CTX_free(hctx);
4901 		hctx = EVP_MAC_CTX_new(hmac);
4902 		if (!hctx)
4903 			goto fail;
4904 
4905 		if (EVP_MAC_init(hctx, prk, mdlen, params) != 1)
4906 			goto fail;
4907 
4908 		if (iter > 0 && EVP_MAC_update(hctx, hash, mdlen) != 1)
4909 			goto fail;
4910 		if (iter == 255)
4911 			goto fail;
4912 		iter++;
4913 
4914 		if (EVP_MAC_update(hctx, labeled_info, labeled_info_len) != 1 ||
4915 		    EVP_MAC_update(hctx, &iter, sizeof(iter)) != 1)
4916 			goto fail;
4917 
4918 		if (EVP_MAC_final(hctx, hash, &mdlen, mdlen) != 1)
4919 			goto fail;
4920 #else /* OpenSSL version >= 3.0 */
4921 		if (HMAC_Init_ex(hctx, prk, mdlen,
4922 				 kem ? ctx->kem_h : ctx->kdf_h,
4923 				 NULL) != 1)
4924 			goto fail;
4925 
4926 		if (iter > 0)
4927 			HMAC_Update(hctx, hash, mdlen);
4928 		if (iter == 255)
4929 			goto fail;
4930 		iter++;
4931 		HMAC_Update(hctx, labeled_info, labeled_info_len);
4932 		HMAC_Update(hctx, &iter, sizeof(iter));
4933 
4934 		if (HMAC_Final(hctx, hash, &mdlen) != 1)
4935 			goto fail;
4936 		HMAC_CTX_reset(hctx);
4937 #endif /* OpenSSL version >= 3.0 */
4938 
4939 		clen = left > mdlen ? mdlen : left;
4940 		os_memcpy(pos, hash, clen);
4941 		pos += clen;
4942 		left -= clen;
4943 	}
4944 	res = 0;
4945 fail:
4946 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
4947 	EVP_MAC_free(hmac);
4948 	EVP_MAC_CTX_free(hctx);
4949 #else /* OpenSSL version >= 3.0 */
4950 	HMAC_CTX_free(hctx);
4951 #endif /* OpenSSL version >= 3.0 */
4952 	os_free(labeled_info);
4953 
4954 	return res;
4955 }
4956 
4957 
hpke_extract_and_expand(struct hpke_context * ctx,const u8 * dhss,size_t dhss_len,const u8 * enc,size_t enc_len,const u8 * pk_rm,size_t pk_rm_len,u8 * shared_secret)4958 static int hpke_extract_and_expand(struct hpke_context *ctx,
4959 				   const u8 *dhss, size_t dhss_len,
4960 				   const u8 *enc, size_t enc_len,
4961 				   const u8 *pk_rm, size_t pk_rm_len,
4962 				   u8 *shared_secret)
4963 {
4964 	u8 kem_context[2 * HPKE_MAX_PUB_LEN];
4965 	u8 eae_prk[HPKE_MAX_HASH_LEN];
4966 
4967 	/* eae_prk = LabeledExtract("", "eae_prk", dh) */
4968 	if (hpke_labeled_extract(ctx, true, NULL, 0, "eae_prk", dhss, dhss_len,
4969 				 eae_prk) < 0)
4970 		return -1;
4971 
4972 	if (enc_len > HPKE_MAX_PUB_LEN || pk_rm_len > HPKE_MAX_PUB_LEN)
4973 		return -1;
4974 	/* kem_context = concat(enc, pkRm) */
4975 	os_memcpy(kem_context, enc, enc_len);
4976 	os_memcpy(&kem_context[enc_len], pk_rm, pk_rm_len);
4977 
4978 	/* shared_secret = LabeledExpand(eae_prk, "shared_secret",
4979 	 *                               kem_context, Nsecret) */
4980 	if (hpke_labeled_expand(ctx, true, eae_prk, "shared_secret",
4981 				kem_context, enc_len + pk_rm_len,
4982 				shared_secret, ctx->n_secret) < 0)
4983 		return -1;
4984 
4985 	forced_memzero(eae_prk, sizeof(eae_prk));
4986 	return 0;
4987 }
4988 
4989 
hpke_key_schedule(struct hpke_context * ctx,const u8 * shared_secret,const u8 * info,size_t info_len)4990 static int hpke_key_schedule(struct hpke_context *ctx, const u8 *shared_secret,
4991 			     const u8 *info, size_t info_len)
4992 {
4993 	u8 key_schedule_context[1 + 2 * HPKE_MAX_HASH_LEN];
4994 	u8 secret[HPKE_MAX_HASH_LEN];
4995 	int res = -1;
4996 
4997 	/* key_schedule_context = concat(mode, psk_id_hash, info_hash) */
4998 	key_schedule_context[0] = HPKE_MODE_BASE;
4999 
5000 	/* psk_id_hash = LabeledExtract("", "psk_id_hash", psk_id) */
5001 	if (hpke_labeled_extract(ctx, false, NULL, 0, "psk_id_hash",
5002 				 NULL, 0, &key_schedule_context[1]) < 0)
5003 		goto fail;
5004 
5005 	/* info_hash = LabeledExtract("", "info_hash", info) */
5006 	if (hpke_labeled_extract(ctx, false, NULL, 0, "info_hash",
5007 				 info, info_len,
5008 				 &key_schedule_context[1 + ctx->n_h]) < 0)
5009 		goto fail;
5010 
5011 	/* secret = LabeledExtract(shared_secret, "secret", psk) */
5012 	if (hpke_labeled_extract(ctx, false, shared_secret, ctx->n_secret,
5013 				 "secret", NULL, 0, secret) < 0)
5014 		goto fail;
5015 
5016 	/* key = LabeledExpand(secret, "key", key_schedule_context, Nk) */
5017 	if (hpke_labeled_expand(ctx, false, secret, "key",
5018 				key_schedule_context, 1 + 2 * ctx->n_h,
5019 				ctx->key, ctx->n_k) < 0)
5020 		goto fail;
5021 
5022 	/* base_nonce = LabeledExpand(secret, "base_nonce",
5023 	 *                            key_schedule_context, Nn) */
5024 	if (hpke_labeled_expand(ctx, false, secret, "base_nonce",
5025 				key_schedule_context, 1 + 2 * ctx->n_h,
5026 				ctx->base_nonce, ctx->n_n) < 0)
5027 		goto fail;
5028 	res = 0;
5029 fail:
5030 	forced_memzero(key_schedule_context, sizeof(key_schedule_context));
5031 	forced_memzero(secret, sizeof(secret));
5032 	return res;
5033 }
5034 
5035 
hpke_encap(struct hpke_context * ctx,struct crypto_ec_key * pk_r,u8 * shared_secret,u8 * enc)5036 static int hpke_encap(struct hpke_context *ctx, struct crypto_ec_key *pk_r,
5037 		      u8 *shared_secret, u8 *enc)
5038 {
5039 	EVP_PKEY_CTX *pctx = NULL;
5040 	struct crypto_ec_key *sk_e;
5041 	int res = -1;
5042 	u8 *dhss = NULL;
5043 	size_t dhss_len = 0;
5044 	struct wpabuf *enc_buf = NULL, *pk_rm = NULL;
5045 
5046 	/* skE, pkE = GenerateKeyPair() */
5047 	sk_e = crypto_ec_key_gen(ctx->iana_group);
5048 	if (!sk_e) {
5049 		wpa_printf(MSG_INFO, "OpenSSL:%s:Could not generate key pair",
5050 			   __func__);
5051 		goto fail;
5052 	}
5053 
5054 	/* dh = DH(skE, pkR) */
5055 	dhss_len = sizeof(dhss);
5056 	pctx = EVP_PKEY_CTX_new((EVP_PKEY *) sk_e, NULL);
5057 	if (!pctx ||
5058 	    EVP_PKEY_derive_init(pctx) != 1 ||
5059 	    EVP_PKEY_derive_set_peer(pctx, (EVP_PKEY *) pk_r) != 1 ||
5060 	    EVP_PKEY_derive(pctx, NULL, &dhss_len) != 1 ||
5061 	    !(dhss = os_malloc(dhss_len)) ||
5062 	    EVP_PKEY_derive(pctx, dhss, &dhss_len) != 1 ||
5063 	    dhss_len > HPKE_MAX_SHARED_SECRET_LEN) {
5064 		wpa_printf(MSG_INFO,
5065 			   "OpenSSL: hpke_encap: EVP_PKEY_derive failed (dhss_len=%zu): %s",
5066 			   dhss_len, ERR_error_string(ERR_get_error(), NULL));
5067 		goto fail;
5068 	}
5069 
5070 	/* enc = SerializePublicKey(pkE) */
5071 	enc_buf = crypto_ec_key_get_pubkey_point(sk_e, 1);
5072 	if (!enc_buf)
5073 		goto fail;
5074 	os_memcpy(enc, wpabuf_head(enc_buf), wpabuf_len(enc_buf));
5075 
5076 	/* pkRm = SerializePublicKey(pkR) */
5077 	pk_rm = crypto_ec_key_get_pubkey_point(pk_r, 1);
5078 	if (!pk_rm)
5079 		goto fail;
5080 
5081 	/* kem_context = concat(enc, pkRm) */
5082 	/* shared_secret = ExtractAndExpand(dh, kem_context) */
5083 	/* return shared_secret, enc */
5084 	res = hpke_extract_and_expand(ctx, dhss, dhss_len, enc, ctx->n_pk,
5085 				      wpabuf_head(pk_rm),
5086 				      wpabuf_len(pk_rm), shared_secret);
5087 fail:
5088 	bin_clear_free(dhss, dhss_len);
5089 	crypto_ec_key_deinit(sk_e);
5090 	EVP_PKEY_CTX_free(pctx);
5091 	wpabuf_free(enc_buf);
5092 	wpabuf_free(pk_rm);
5093 	return res;
5094 }
5095 
5096 
5097 static struct wpabuf *
hpke_aead_seal(struct hpke_context * ctx,const u8 * aad,size_t aad_len,const u8 * pt,size_t pt_len)5098 hpke_aead_seal(struct hpke_context *ctx, const u8 *aad, size_t aad_len,
5099 	       const u8 *pt, size_t pt_len)
5100 {
5101 	EVP_CIPHER_CTX *cctx;
5102 	int len = 0;
5103 	struct wpabuf *ct = NULL;
5104 
5105 	/* No need to xor in sequence number since we support only the
5106 	 * single-shot API, i.e., base_nonce can be used as-is. */
5107 
5108 	cctx = EVP_CIPHER_CTX_new();
5109 	if (!cctx ||
5110 	    EVP_EncryptInit_ex(cctx, ctx->cipher, NULL, ctx->key,
5111 			       ctx->base_nonce) != 1) {
5112 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_DecryptInit_ex failed",
5113 			   __func__);
5114 		goto fail;
5115 	}
5116 	if (aad && aad_len &&
5117 	    EVP_EncryptUpdate(cctx, NULL, &len, aad, aad_len) != 1) {
5118 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_EncryptUpdate(AAD) failed",
5119 			   __func__);
5120 		goto fail;
5121 	}
5122 	ct = wpabuf_alloc(pt_len + AES_BLOCK_SIZE + ctx->n_t);
5123 	if (!ct)
5124 		goto fail;
5125 	if (EVP_EncryptUpdate(cctx, wpabuf_put(ct, 0), &len, pt, pt_len) != 1) {
5126 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_EncryptUpdate failed",
5127 			   __func__);
5128 		goto fail;
5129 	}
5130 	wpabuf_put(ct, len);
5131 
5132 	if (EVP_EncryptFinal(cctx, wpabuf_put(ct, 0), &len) != 1) {
5133 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_DecryptFinal failed",
5134 			   __func__);
5135 		wpabuf_free(ct);
5136 		ct = NULL;
5137 		goto fail;
5138 	}
5139 
5140 	if (EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_GET_TAG, ctx->n_t,
5141 				wpabuf_put(ct, ctx->n_t)) != 1) {
5142 		wpa_printf(MSG_INFO, "OpenSSL:%s:Could not get tag",
5143 			   __func__);
5144 		wpabuf_free(ct);
5145 		ct = NULL;
5146 		goto fail;
5147 	}
5148 fail:
5149 	EVP_CIPHER_CTX_free(cctx);
5150 	return ct;
5151 }
5152 
5153 
hpke_base_seal_int(enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id,struct crypto_ec_key * peer_pub,const u8 * info,size_t info_len,const u8 * aad,size_t aad_len,const u8 * pt,size_t pt_len)5154 static struct wpabuf * hpke_base_seal_int(enum hpke_kem_id kem_id,
5155 					  enum hpke_kdf_id kdf_id,
5156 					  enum hpke_aead_id aead_id,
5157 					  struct crypto_ec_key *peer_pub,
5158 					  const u8 *info, size_t info_len,
5159 					  const u8 *aad, size_t aad_len,
5160 					  const u8 *pt, size_t pt_len)
5161 {
5162 	struct hpke_context *ctx;
5163 	u8 shared_secret[HPKE_MAX_SHARED_SECRET_LEN];
5164 	u8 enc[1 + 2 * HPKE_MAX_PUB_LEN];
5165 	struct wpabuf *ct = NULL, *enc_ct = NULL;
5166 
5167 	ctx = hpke_get_context(kem_id, kdf_id, aead_id, peer_pub);
5168 	if (!ctx)
5169 		return NULL;
5170 
5171 	/* shared_secret, enc = Encap(pkR) */
5172 	if (hpke_encap(ctx, peer_pub, shared_secret, enc) < 0)
5173 		goto fail;
5174 
5175 	/* KeyScheduleS(mode_base, shared_secret, info,
5176 	 *              default_psk, default_psk_id) */
5177 	if (hpke_key_schedule(ctx, shared_secret, info, info_len) < 0)
5178 		goto fail;
5179 
5180 	/* ct = ctx.Seal(aad, pt) */
5181 	ct = hpke_aead_seal(ctx, aad, aad_len, pt, pt_len);
5182 	if (!ct)
5183 		goto fail;
5184 
5185 	/* return enc, ct */
5186 	enc_ct = wpabuf_alloc(ctx->n_pk + wpabuf_len(ct));
5187 	if (!enc_ct)
5188 		goto fail;
5189 	wpabuf_put_data(enc_ct, enc, ctx->n_pk);
5190 	wpabuf_put_buf(enc_ct, ct);
5191 
5192 fail:
5193 	forced_memzero(shared_secret, sizeof(shared_secret));
5194 	hpke_free_context(ctx);
5195 	wpabuf_free(ct);
5196 	return enc_ct;
5197 }
5198 
5199 
hpke_decap(struct hpke_context * ctx,const u8 * enc,size_t enc_ct_len,struct crypto_ec_key * sk_r,u8 * shared_secret)5200 static int hpke_decap(struct hpke_context *ctx, const u8 *enc,
5201 		      size_t enc_ct_len, struct crypto_ec_key *sk_r,
5202 		      u8 *shared_secret)
5203 {
5204 	EVP_PKEY_CTX *pctx = NULL;
5205 	struct wpabuf *pk_rm = NULL;
5206 	size_t len;
5207 	int res = -1;
5208 	struct crypto_ec_key *pk_e = NULL;
5209 	u8 *dhss = NULL;
5210 	size_t dhss_len = 0;
5211 
5212 	/* pkE = DeserializePublicKey(enc) */
5213 	if (enc_ct_len < ctx->n_pk)
5214 		return -1; /* not enough room for enc */
5215 	if (enc[0] != 0x04)
5216 		return -1; /* not in uncompressed form */
5217 	len = (ctx->n_pk - 1) / 2;
5218 	pk_e = crypto_ec_key_set_pub(ctx->iana_group, &enc[1],
5219 				     &enc[1 + len], len);
5220 	if (!pk_e)
5221 		return -1; /* invalid public key point */
5222 	/* dh = DH(skR, pkE) */
5223 	pctx = EVP_PKEY_CTX_new((EVP_PKEY *) sk_r, NULL);
5224 	if (!pctx ||
5225 	    EVP_PKEY_derive_init(pctx) != 1 ||
5226 	    EVP_PKEY_derive_set_peer(pctx, (EVP_PKEY *) pk_e) != 1 ||
5227 	    EVP_PKEY_derive(pctx, NULL, &dhss_len) != 1 ||
5228 	    !(dhss = os_malloc(dhss_len)) ||
5229 	    EVP_PKEY_derive(pctx, dhss, &dhss_len) != 1 ||
5230 	    dhss_len > HPKE_MAX_SHARED_SECRET_LEN) {
5231 		wpa_printf(MSG_INFO,
5232 			   "OpenSSL: hpke_decap: EVP_PKEY_derive failed (dhss_len=%zu): %s",
5233 			   dhss_len, ERR_error_string(ERR_get_error(), NULL));
5234 		goto fail;
5235 	}
5236 
5237 	/* pkRm = SerializePublicKey(pk(skR)) */
5238 	pk_rm = crypto_ec_key_get_pubkey_point(sk_r, 1);
5239 	if (!pk_rm)
5240 		goto fail;
5241 
5242 	/* kem_context = concat(enc, pkRm) */
5243 	/* shared_secret = ExtractAndExpand(dh, kem_context) */
5244 	res = hpke_extract_and_expand(ctx, dhss, dhss_len, enc, ctx->n_pk,
5245 				      wpabuf_head(pk_rm),
5246 				      wpabuf_len(pk_rm), shared_secret);
5247 fail:
5248 	bin_clear_free(dhss, dhss_len);
5249 	crypto_ec_key_deinit(pk_e);
5250 	EVP_PKEY_CTX_free(pctx);
5251 	wpabuf_free(pk_rm);
5252 	return res;
5253 }
5254 
5255 
5256 static struct wpabuf *
hpke_aead_open(struct hpke_context * ctx,const u8 * aad,size_t aad_len,const u8 * ct,size_t ct_len)5257 hpke_aead_open(struct hpke_context *ctx, const u8 *aad, size_t aad_len,
5258 	       const u8 *ct, size_t ct_len)
5259 {
5260 	EVP_CIPHER_CTX *cctx;
5261 	int len = 0;
5262 	const u8 *tag;
5263 	struct wpabuf *pt = NULL;
5264 
5265 	if (ct_len < ctx->n_t)
5266 		return NULL;
5267 	tag = ct + ct_len - ctx->n_t;
5268 	ct_len -= ctx->n_t;
5269 
5270 	/* No need to xor in sequence number since we support only the
5271 	 * single-shot API, i.e., base_nonce can be used as-is. */
5272 
5273 	cctx = EVP_CIPHER_CTX_new();
5274 	if (!cctx ||
5275 	    EVP_DecryptInit_ex(cctx, ctx->cipher, NULL, ctx->key,
5276 			       ctx->base_nonce) != 1) {
5277 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_DecryptInit_ex failed",
5278 			   __func__);
5279 		goto fail;
5280 	}
5281 	if (aad && aad_len &&
5282 	    EVP_DecryptUpdate(cctx, NULL, &len, aad, aad_len) != 1) {
5283 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_DecryptUpdate(AAD) failed",
5284 			   __func__);
5285 		goto fail;
5286 	}
5287 	pt = wpabuf_alloc(ct_len + AES_BLOCK_SIZE);
5288 	if (!pt)
5289 		goto fail;
5290 	if (EVP_DecryptUpdate(cctx, wpabuf_put(pt, 0), &len, ct, ct_len) != 1) {
5291 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_DecryptUpdate failed",
5292 			   __func__);
5293 		goto fail;
5294 	}
5295 	wpabuf_put(pt, len);
5296 
5297 	if (EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_SET_TAG, ctx->n_t,
5298 				(void *) tag) != 1) {
5299 		wpa_printf(MSG_INFO, "OpenSSL:%s:Could not set tag",
5300 			   __func__);
5301 		wpabuf_free(pt);
5302 		pt = NULL;
5303 		goto fail;
5304 	}
5305 
5306 	if (EVP_DecryptFinal(cctx, wpabuf_put(pt, 0), &len) != 1) {
5307 		wpa_printf(MSG_INFO, "OpenSSL:%s:EVP_DecryptFinal failed",
5308 			   __func__);
5309 		wpabuf_free(pt);
5310 		pt = NULL;
5311 	}
5312 fail:
5313 	EVP_CIPHER_CTX_free(cctx);
5314 	return pt;
5315 }
5316 
5317 
hpke_base_open_int(enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id,struct crypto_ec_key * own_priv,const u8 * info,size_t info_len,const u8 * aad,size_t aad_len,const u8 * enc_ct,size_t enc_ct_len)5318 static struct wpabuf * hpke_base_open_int(enum hpke_kem_id kem_id,
5319 					  enum hpke_kdf_id kdf_id,
5320 					  enum hpke_aead_id aead_id,
5321 					  struct crypto_ec_key *own_priv,
5322 					  const u8 *info, size_t info_len,
5323 					  const u8 *aad, size_t aad_len,
5324 					  const u8 *enc_ct, size_t enc_ct_len)
5325 {
5326 	struct hpke_context *ctx;
5327 	u8 shared_secret[HPKE_MAX_SHARED_SECRET_LEN];
5328 	struct wpabuf *pt = NULL;
5329 
5330 	ctx = hpke_get_context(kem_id, kdf_id, aead_id, own_priv);
5331 	if (!ctx)
5332 		return NULL;
5333 
5334 	/* shared_secret = Decap(enc, skR) */
5335 	if (hpke_decap(ctx, enc_ct, enc_ct_len, own_priv, shared_secret) < 0)
5336 		goto fail;
5337 
5338 	/* KeyScheduleR(mode_base, shared_secret, info,
5339 	 *              default_psk, default_psk_id) */
5340 	if (hpke_key_schedule(ctx, shared_secret, info, info_len) < 0)
5341 		goto fail;
5342 
5343 	/* return ctx.Open(aad, ct) */
5344 	pt = hpke_aead_open(ctx, aad, aad_len,
5345 			    &enc_ct[ctx->n_pk], enc_ct_len - ctx->n_pk);
5346 
5347 fail:
5348 	forced_memzero(shared_secret, sizeof(shared_secret));
5349 	hpke_free_context(ctx);
5350 	return pt;
5351 }
5352 
5353 
5354 #if OPENSSL_VERSION_NUMBER >= 0x30200000L
5355 
hpke_set_suite(OSSL_HPKE_SUITE * suite,enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id)5356 static bool hpke_set_suite(OSSL_HPKE_SUITE *suite,
5357 			   enum hpke_kem_id kem_id,
5358 			   enum hpke_kdf_id kdf_id,
5359 			   enum hpke_aead_id aead_id)
5360 {
5361 	os_memset(suite, 0, sizeof(*suite));
5362 
5363 	switch (kem_id) {
5364 	case HPKE_DHKEM_P256_HKDF_SHA256:
5365 		suite->kem_id = OSSL_HPKE_KEM_ID_P256;
5366 		break;
5367 	case HPKE_DHKEM_P384_HKDF_SHA384:
5368 		suite->kem_id = OSSL_HPKE_KEM_ID_P384;
5369 		break;
5370 	case HPKE_DHKEM_P521_HKDF_SHA512:
5371 		suite->kem_id = OSSL_HPKE_KEM_ID_P521;
5372 		break;
5373 	default:
5374 		return false;
5375 	}
5376 
5377 	switch (kdf_id) {
5378 	case HPKE_KDF_HKDF_SHA256:
5379 		suite->kdf_id = OSSL_HPKE_KDF_ID_HKDF_SHA256;
5380 		break;
5381 	case HPKE_KDF_HKDF_SHA384:
5382 		suite->kdf_id = OSSL_HPKE_KDF_ID_HKDF_SHA384;
5383 		break;
5384 	case HPKE_KDF_HKDF_SHA512:
5385 		suite->kdf_id = OSSL_HPKE_KDF_ID_HKDF_SHA512;
5386 		break;
5387 	default:
5388 		return false;
5389 	}
5390 
5391 	switch (aead_id) {
5392 	case HPKE_AEAD_AES_128_GCM:
5393 		suite->aead_id = OSSL_HPKE_AEAD_ID_AES_GCM_128;
5394 		break;
5395 	case HPKE_AEAD_AES_256_GCM:
5396 		suite->aead_id = OSSL_HPKE_AEAD_ID_AES_GCM_256;
5397 		break;
5398 	default:
5399 		return false;
5400 	}
5401 
5402 	if (!OSSL_HPKE_suite_check(*suite)) {
5403 		wpa_printf(MSG_INFO,
5404 			   "OpenSSL: HPKE suite kem_id=%d kdf_id=%d aead_id=%d not supported",
5405 			   kem_id, kdf_id, aead_id);
5406 		return false;
5407 	}
5408 
5409 	return true;
5410 }
5411 
5412 
hpke_base_seal(enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id,struct crypto_ec_key * peer_pub,const u8 * info,size_t info_len,const u8 * aad,size_t aad_len,const u8 * pt,size_t pt_len)5413 struct wpabuf * hpke_base_seal(enum hpke_kem_id kem_id,
5414 			       enum hpke_kdf_id kdf_id,
5415 			       enum hpke_aead_id aead_id,
5416 			       struct crypto_ec_key *peer_pub,
5417 			       const u8 *info, size_t info_len,
5418 			       const u8 *aad, size_t aad_len,
5419 			       const u8 *pt, size_t pt_len)
5420 {
5421 	OSSL_HPKE_SUITE suite;
5422 	OSSL_HPKE_CTX *ctx = NULL;
5423 	struct wpabuf *res = NULL, *buf, *pub = NULL;
5424 	size_t enc_len, ct_len;
5425 	int group;
5426 
5427 	group = crypto_ec_key_group(peer_pub);
5428 	if (group == 28 || group == 29 || group == 30) {
5429 		/* Use the internal routines for the special DPP use case with
5430 		 * brainpool curves, */
5431 		return hpke_base_seal_int(kem_id, kdf_id, aead_id, peer_pub,
5432 					  info, info_len, aad, aad_len,
5433 					  pt, pt_len);
5434 	}
5435 
5436 
5437 	if (!hpke_set_suite(&suite, kem_id, kdf_id, aead_id))
5438 		return NULL;
5439 
5440 	enc_len = OSSL_HPKE_get_public_encap_size(suite);
5441 	ct_len = OSSL_HPKE_get_ciphertext_size(suite, pt_len);
5442 	buf = wpabuf_alloc(enc_len + ct_len);
5443 	if (!buf)
5444 		goto out;
5445 
5446 	pub = crypto_ec_key_get_pubkey_point(peer_pub, 1);
5447 	if (!pub)
5448 		goto out;
5449 
5450 	ctx = OSSL_HPKE_CTX_new(OSSL_HPKE_MODE_BASE, suite,
5451 				OSSL_HPKE_ROLE_SENDER, NULL, NULL);
5452 	if (!ctx)
5453 		goto out;
5454 
5455 	if (OSSL_HPKE_encap(ctx, wpabuf_put(buf, 0), &enc_len,
5456 			    wpabuf_head(pub), wpabuf_len(pub),
5457 			    info, info_len) != 1) {
5458 		wpa_printf(MSG_DEBUG, "OpenSSL: OSSL_HPKE_encap failed: %s",
5459 			   ERR_error_string(ERR_get_error(), NULL));
5460 		goto out;
5461 	}
5462 	wpabuf_put(buf, enc_len);
5463 
5464 	if (OSSL_HPKE_seal(ctx, wpabuf_put(buf, 0), &ct_len, aad, aad_len,
5465 			   pt, pt_len) != 1) {
5466 		wpa_printf(MSG_DEBUG, "OpenSSL: OSSL_HPKE_seal failed: %s",
5467 			   ERR_error_string(ERR_get_error(), NULL));
5468 		goto out;
5469 	}
5470 	wpabuf_put(buf, ct_len);
5471 	res = buf;
5472 	buf = NULL;
5473 
5474 out:
5475 	OSSL_HPKE_CTX_free(ctx);
5476 	wpabuf_free(buf);
5477 	wpabuf_free(pub);
5478 	return res;
5479 }
5480 
5481 
hpke_base_open(enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id,struct crypto_ec_key * own_priv,const u8 * info,size_t info_len,const u8 * aad,size_t aad_len,const u8 * enc_ct,size_t enc_ct_len)5482 struct wpabuf * hpke_base_open(enum hpke_kem_id kem_id,
5483 			       enum hpke_kdf_id kdf_id,
5484 			       enum hpke_aead_id aead_id,
5485 			       struct crypto_ec_key *own_priv,
5486 			       const u8 *info, size_t info_len,
5487 			       const u8 *aad, size_t aad_len,
5488 			       const u8 *enc_ct, size_t enc_ct_len)
5489 {
5490 	OSSL_HPKE_SUITE suite;
5491 	OSSL_HPKE_CTX *ctx;
5492 	struct wpabuf *buf = NULL, *res = NULL;
5493 	size_t len, enc_len;
5494 	int group;
5495 
5496 	group = crypto_ec_key_group(own_priv);
5497 	if (group == 28 || group == 29 || group == 30) {
5498 		/* Use the internal routines for the special DPP use case with
5499 		 * brainpool curves, */
5500 		return hpke_base_open_int(kem_id, kdf_id, aead_id, own_priv,
5501 					  info, info_len, aad, aad_len,
5502 					  enc_ct, enc_ct_len);
5503 	}
5504 
5505 	if (!hpke_set_suite(&suite, kem_id, kdf_id, aead_id))
5506 		return NULL;
5507 
5508 	enc_len = OSSL_HPKE_get_public_encap_size(suite);
5509 	if (enc_ct_len < enc_len) {
5510 		wpa_printf(MSG_DEBUG, "OpenSSL: Too short HPKE enc_ct data");
5511 		return NULL;
5512 	}
5513 
5514 	ctx = OSSL_HPKE_CTX_new(OSSL_HPKE_MODE_BASE, suite,
5515 				OSSL_HPKE_ROLE_RECEIVER, NULL, NULL);
5516 	if (!ctx)
5517 		goto out;
5518 
5519 	if (OSSL_HPKE_decap(ctx, enc_ct, enc_len, (EVP_PKEY *) own_priv,
5520 			    info, info_len) != 1) {
5521 		wpa_printf(MSG_DEBUG, "OpenSSL: OSSL_HPKE_decap failed: %s",
5522 			   ERR_error_string(ERR_get_error(), NULL));
5523 		goto out;
5524 	}
5525 
5526 	len = enc_ct_len;
5527 	buf = wpabuf_alloc(len);
5528 	if (!buf)
5529 		goto out;
5530 
5531 	if (OSSL_HPKE_open(ctx, wpabuf_put(buf, 0), &len, aad, aad_len,
5532 			   enc_ct + enc_len, enc_ct_len - enc_len) != 1) {
5533 		wpa_printf(MSG_DEBUG, "OpenSSL: OSSL_HPKE_open failed: %s",
5534 			   ERR_error_string(ERR_get_error(), NULL));
5535 		goto out;
5536 	}
5537 
5538 	wpabuf_put(buf, len);
5539 	res = buf;
5540 	buf = NULL;
5541 
5542 out:
5543 	OSSL_HPKE_CTX_free(ctx);
5544 	wpabuf_free(buf);
5545 	return res;
5546 }
5547 
5548 #else /* OpenSSL < 3.2 */
5549 
hpke_base_seal(enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id,struct crypto_ec_key * peer_pub,const u8 * info,size_t info_len,const u8 * aad,size_t aad_len,const u8 * pt,size_t pt_len)5550 struct wpabuf * hpke_base_seal(enum hpke_kem_id kem_id,
5551 			       enum hpke_kdf_id kdf_id,
5552 			       enum hpke_aead_id aead_id,
5553 			       struct crypto_ec_key *peer_pub,
5554 			       const u8 *info, size_t info_len,
5555 			       const u8 *aad, size_t aad_len,
5556 			       const u8 *pt, size_t pt_len)
5557 {
5558 	return hpke_base_seal_int(kem_id, kdf_id, aead_id, peer_pub,
5559 				  info, info_len, aad, aad_len, pt, pt_len);
5560 }
5561 
5562 
hpke_base_open(enum hpke_kem_id kem_id,enum hpke_kdf_id kdf_id,enum hpke_aead_id aead_id,struct crypto_ec_key * own_priv,const u8 * info,size_t info_len,const u8 * aad,size_t aad_len,const u8 * enc_ct,size_t enc_ct_len)5563 struct wpabuf * hpke_base_open(enum hpke_kem_id kem_id,
5564 			       enum hpke_kdf_id kdf_id,
5565 			       enum hpke_aead_id aead_id,
5566 			       struct crypto_ec_key *own_priv,
5567 			       const u8 *info, size_t info_len,
5568 			       const u8 *aad, size_t aad_len,
5569 			       const u8 *enc_ct, size_t enc_ct_len)
5570 {
5571 	return hpke_base_open_int(kem_id, kdf_id, aead_id, own_priv,
5572 				  info, info_len, aad, aad_len,
5573 				  enc_ct, enc_ct_len);
5574 }
5575 
5576 #endif /* OpenSSL < 3.2 */
5577 
5578 #endif /* CONFIG_DPP3 */
5579 
5580 
crypto_unload(void)5581 void crypto_unload(void)
5582 {
5583 	openssl_unload_legacy_provider();
5584 }
5585