1 /*-
2 * Copyright (c) 2014 Michihiro NAKAJIMA
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25 
26 #include "archive_platform.h"
27 
28 #ifdef HAVE_STRING_H
29 #include <string.h>
30 #endif
31 #include "archive.h"
32 #include "archive_cryptor_private.h"
33 
34 /*
35  * On systems that do not support any recognized crypto libraries,
36  * this file will normally define no usable symbols.
37  *
38  * But some compilers and linkers choke on empty object files, so
39  * define a public symbol that will always exist.  This could
40  * be removed someday if this file gains another always-present
41  * symbol definition.
42  */
43 int __libarchive_cryptor_build_hack(void) {
44 	return 0;
45 }
46 
47 #ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto
48 
49 static int
50 pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
51     size_t salt_len, unsigned rounds, uint8_t *derived_key,
52     size_t derived_key_len)
53 {
54 	CCKeyDerivationPBKDF(kCCPBKDF2, (const char *)pw,
55 	    pw_len, salt, salt_len, kCCPRFHmacAlgSHA1, rounds,
56 	    derived_key, derived_key_len);
57 	return 0;
58 }
59 
60 #elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H)
61 #ifdef _MSC_VER
62 #pragma comment(lib, "Bcrypt.lib")
63 #endif
64 
65 static int
66 pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
67 	size_t salt_len, unsigned rounds, uint8_t *derived_key,
68 	size_t derived_key_len)
69 {
70 	NTSTATUS status;
71 	BCRYPT_ALG_HANDLE hAlg;
72 
73 	status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA1_ALGORITHM,
74 		MS_PRIMITIVE_PROVIDER, BCRYPT_ALG_HANDLE_HMAC_FLAG);
75 	if (!BCRYPT_SUCCESS(status))
76 		return -1;
77 
78 	status = BCryptDeriveKeyPBKDF2(hAlg,
79 		(PUCHAR)(uintptr_t)pw, (ULONG)pw_len,
80 		(PUCHAR)(uintptr_t)salt, (ULONG)salt_len, rounds,
81 		(PUCHAR)derived_key, (ULONG)derived_key_len, 0);
82 
83 	BCryptCloseAlgorithmProvider(hAlg, 0);
84 
85 	return (BCRYPT_SUCCESS(status)) ? 0: -1;
86 }
87 
88 #elif defined(HAVE_LIBMBEDCRYPTO) && defined(HAVE_MBEDTLS_PKCS5_H)
89 
90 static int
91 pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
92     size_t salt_len, unsigned rounds, uint8_t *derived_key,
93     size_t derived_key_len)
94 {
95 	mbedtls_md_context_t ctx;
96 	const mbedtls_md_info_t *info;
97 	int ret;
98 
99 	mbedtls_md_init(&ctx);
100 	info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
101 	if (info == NULL) {
102 		mbedtls_md_free(&ctx);
103 		return (-1);
104 	}
105 	ret = mbedtls_md_setup(&ctx, info, 1);
106 	if (ret != 0) {
107 		mbedtls_md_free(&ctx);
108 		return (-1);
109 	}
110 	ret = mbedtls_pkcs5_pbkdf2_hmac(&ctx, (const unsigned char *)pw,
111 	    pw_len, salt, salt_len, rounds, derived_key_len, derived_key);
112 
113 	mbedtls_md_free(&ctx);
114 	return (ret);
115 }
116 
117 #elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_PBKDF2_H)
118 
119 static int
120 pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
121     size_t salt_len, unsigned rounds, uint8_t *derived_key,
122     size_t derived_key_len) {
123 	pbkdf2_hmac_sha1((unsigned)pw_len, (const uint8_t *)pw, rounds,
124 	    salt_len, salt, derived_key_len, derived_key);
125 	return 0;
126 }
127 
128 #elif defined(HAVE_LIBCRYPTO) && defined(HAVE_PKCS5_PBKDF2_HMAC_SHA1)
129 
130 static int
131 pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
132     size_t salt_len, unsigned rounds, uint8_t *derived_key,
133     size_t derived_key_len) {
134 
135 	PKCS5_PBKDF2_HMAC_SHA1(pw, pw_len, salt, salt_len, rounds,
136 	    derived_key_len, derived_key);
137 	return 0;
138 }
139 
140 #else
141 
142 /* Stub */
143 static int
144 pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
145     size_t salt_len, unsigned rounds, uint8_t *derived_key,
146     size_t derived_key_len) {
147 	(void)pw; /* UNUSED */
148 	(void)pw_len; /* UNUSED */
149 	(void)salt; /* UNUSED */
150 	(void)salt_len; /* UNUSED */
151 	(void)rounds; /* UNUSED */
152 	(void)derived_key; /* UNUSED */
153 	(void)derived_key_len; /* UNUSED */
154 	return -1; /* UNSUPPORTED */
155 }
156 
157 #endif
158 
159 #ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto
160 # if MAC_OS_X_VERSION_MAX_ALLOWED < 1090
161 #  define kCCAlgorithmAES kCCAlgorithmAES128
162 # endif
163 
164 static int
165 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
166 {
167 	CCCryptorStatus r;
168 
169 	ctx->key_len = key_len;
170 	memcpy(ctx->key, key, key_len);
171 	memset(ctx->nonce, 0, sizeof(ctx->nonce));
172 	ctx->encr_pos = AES_BLOCK_SIZE;
173 	r = CCCryptorCreateWithMode(kCCEncrypt, kCCModeECB, kCCAlgorithmAES,
174 	    ccNoPadding, NULL, key, key_len, NULL, 0, 0, 0, &ctx->ctx);
175 	return (r == kCCSuccess)? 0: -1;
176 }
177 
178 static int
179 aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
180 {
181 	CCCryptorRef ref = ctx->ctx;
182 	CCCryptorStatus r;
183 
184 	r = CCCryptorReset(ref, NULL);
185 	if (r != kCCSuccess && r != kCCUnimplemented)
186 		return -1;
187 	r = CCCryptorUpdate(ref, ctx->nonce, AES_BLOCK_SIZE, ctx->encr_buf,
188 	    AES_BLOCK_SIZE, NULL);
189 	return (r == kCCSuccess)? 0: -1;
190 }
191 
192 static int
193 aes_ctr_release(archive_crypto_ctx *ctx)
194 {
195 	memset(ctx->key, 0, ctx->key_len);
196 	memset(ctx->nonce, 0, sizeof(ctx->nonce));
197 	return 0;
198 }
199 
200 #elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H)
201 
202 static int
203 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
204 {
205 	BCRYPT_ALG_HANDLE hAlg;
206 	BCRYPT_KEY_HANDLE hKey;
207 	DWORD keyObj_len, aes_key_len;
208 	PBYTE keyObj;
209 	ULONG result;
210 	NTSTATUS status;
211 	BCRYPT_KEY_LENGTHS_STRUCT key_lengths;
212 
213 	ctx->hAlg = NULL;
214 	ctx->hKey = NULL;
215 	ctx->keyObj = NULL;
216 	switch (key_len) {
217 	case 16: aes_key_len = 128; break;
218 	case 24: aes_key_len = 192; break;
219 	case 32: aes_key_len = 256; break;
220 	default: return -1;
221 	}
222 	status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_AES_ALGORITHM,
223 		MS_PRIMITIVE_PROVIDER, 0);
224 	if (!BCRYPT_SUCCESS(status))
225 		return -1;
226 	status = BCryptGetProperty(hAlg, BCRYPT_KEY_LENGTHS, (PUCHAR)&key_lengths,
227 		sizeof(key_lengths), &result, 0);
228 	if (!BCRYPT_SUCCESS(status)) {
229 		BCryptCloseAlgorithmProvider(hAlg, 0);
230 		return -1;
231 	}
232 	if (key_lengths.dwMinLength > aes_key_len
233 		|| key_lengths.dwMaxLength < aes_key_len) {
234 		BCryptCloseAlgorithmProvider(hAlg, 0);
235 		return -1;
236 	}
237 	status = BCryptGetProperty(hAlg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&keyObj_len,
238 		sizeof(keyObj_len), &result, 0);
239 	if (!BCRYPT_SUCCESS(status)) {
240 		BCryptCloseAlgorithmProvider(hAlg, 0);
241 		return -1;
242 	}
243 	keyObj = (PBYTE)HeapAlloc(GetProcessHeap(), 0, keyObj_len);
244 	if (keyObj == NULL) {
245 		BCryptCloseAlgorithmProvider(hAlg, 0);
246 		return -1;
247 	}
248 	status = BCryptSetProperty(hAlg, BCRYPT_CHAINING_MODE,
249 		(PUCHAR)BCRYPT_CHAIN_MODE_ECB, sizeof(BCRYPT_CHAIN_MODE_ECB), 0);
250 	if (!BCRYPT_SUCCESS(status)) {
251 		BCryptCloseAlgorithmProvider(hAlg, 0);
252 		HeapFree(GetProcessHeap(), 0, keyObj);
253 		return -1;
254 	}
255 	status = BCryptGenerateSymmetricKey(hAlg, &hKey,
256 		keyObj, keyObj_len,
257 		(PUCHAR)(uintptr_t)key, (ULONG)key_len, 0);
258 	if (!BCRYPT_SUCCESS(status)) {
259 		BCryptCloseAlgorithmProvider(hAlg, 0);
260 		HeapFree(GetProcessHeap(), 0, keyObj);
261 		return -1;
262 	}
263 
264 	ctx->hAlg = hAlg;
265 	ctx->hKey = hKey;
266 	ctx->keyObj = keyObj;
267 	ctx->keyObj_len = keyObj_len;
268 	ctx->encr_pos = AES_BLOCK_SIZE;
269 
270 	return 0;
271 }
272 
273 static int
274 aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
275 {
276 	NTSTATUS status;
277 	ULONG result;
278 
279 	status = BCryptEncrypt(ctx->hKey, (PUCHAR)ctx->nonce, AES_BLOCK_SIZE,
280 		NULL, NULL, 0, (PUCHAR)ctx->encr_buf, AES_BLOCK_SIZE,
281 		&result, 0);
282 	return BCRYPT_SUCCESS(status) ? 0 : -1;
283 }
284 
285 static int
286 aes_ctr_release(archive_crypto_ctx *ctx)
287 {
288 
289 	if (ctx->hAlg != NULL) {
290 		BCryptCloseAlgorithmProvider(ctx->hAlg, 0);
291 		ctx->hAlg = NULL;
292 		BCryptDestroyKey(ctx->hKey);
293 		ctx->hKey = NULL;
294 		HeapFree(GetProcessHeap(), 0, ctx->keyObj);
295 		ctx->keyObj = NULL;
296 	}
297 	memset(ctx, 0, sizeof(*ctx));
298 	return 0;
299 }
300 
301 #elif defined(HAVE_LIBMBEDCRYPTO) && defined(HAVE_MBEDTLS_AES_H)
302 
303 static int
304 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
305 {
306 	mbedtls_aes_init(&ctx->ctx);
307 	ctx->key_len = key_len;
308 	memcpy(ctx->key, key, key_len);
309 	memset(ctx->nonce, 0, sizeof(ctx->nonce));
310 	ctx->encr_pos = AES_BLOCK_SIZE;
311 	return 0;
312 }
313 
314 static int
315 aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
316 {
317 	if (mbedtls_aes_setkey_enc(&ctx->ctx, ctx->key,
318 	    ctx->key_len * 8) != 0)
319 		return (-1);
320 	if (mbedtls_aes_crypt_ecb(&ctx->ctx, MBEDTLS_AES_ENCRYPT, ctx->nonce,
321 	    ctx->encr_buf) != 0)
322 		return (-1);
323 	return 0;
324 }
325 
326 static int
327 aes_ctr_release(archive_crypto_ctx *ctx)
328 {
329 	mbedtls_aes_free(&ctx->ctx);
330 	memset(ctx, 0, sizeof(*ctx));
331 	return 0;
332 }
333 
334 #elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_AES_H)
335 
336 static int
337 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
338 {
339 	ctx->key_len = key_len;
340 	memcpy(ctx->key, key, key_len);
341 	memset(ctx->nonce, 0, sizeof(ctx->nonce));
342 	ctx->encr_pos = AES_BLOCK_SIZE;
343 	memset(&ctx->ctx, 0, sizeof(ctx->ctx));
344 	return 0;
345 }
346 
347 static int
348 aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
349 {
350 	aes_set_encrypt_key(&ctx->ctx, ctx->key_len, ctx->key);
351 	aes_encrypt(&ctx->ctx, AES_BLOCK_SIZE, ctx->encr_buf, ctx->nonce);
352 	return 0;
353 }
354 
355 static int
356 aes_ctr_release(archive_crypto_ctx *ctx)
357 {
358 	memset(ctx, 0, sizeof(*ctx));
359 	return 0;
360 }
361 
362 #elif defined(HAVE_LIBCRYPTO)
363 
364 static int
365 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
366 {
367 	if ((ctx->ctx = EVP_CIPHER_CTX_new()) == NULL)
368 		return -1;
369 
370 	switch (key_len) {
371 	case 16: ctx->type = EVP_aes_128_ecb(); break;
372 	case 24: ctx->type = EVP_aes_192_ecb(); break;
373 	case 32: ctx->type = EVP_aes_256_ecb(); break;
374 	default: ctx->type = NULL; return -1;
375 	}
376 
377 	ctx->key_len = key_len;
378 	memcpy(ctx->key, key, key_len);
379 	memset(ctx->nonce, 0, sizeof(ctx->nonce));
380 	ctx->encr_pos = AES_BLOCK_SIZE;
381 #if OPENSSL_VERSION_NUMBER  >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
382 	if (!EVP_CIPHER_CTX_reset(ctx->ctx)) {
383 		EVP_CIPHER_CTX_free(ctx->ctx);
384 		ctx->ctx = NULL;
385 	}
386 #else
387 	EVP_CIPHER_CTX_init(ctx->ctx);
388 #endif
389 	return 0;
390 }
391 
392 static int
393 aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
394 {
395 	int outl = 0;
396 	int r;
397 
398 	r = EVP_EncryptInit_ex(ctx->ctx, ctx->type, NULL, ctx->key, NULL);
399 	if (r == 0)
400 		return -1;
401 	r = EVP_EncryptUpdate(ctx->ctx, ctx->encr_buf, &outl, ctx->nonce,
402 	    AES_BLOCK_SIZE);
403 	if (r == 0 || outl != AES_BLOCK_SIZE)
404 		return -1;
405 	return 0;
406 }
407 
408 static int
409 aes_ctr_release(archive_crypto_ctx *ctx)
410 {
411 	EVP_CIPHER_CTX_free(ctx->ctx);
412 	memset(ctx->key, 0, ctx->key_len);
413 	memset(ctx->nonce, 0, sizeof(ctx->nonce));
414 	return 0;
415 }
416 
417 #else
418 
419 #define ARCHIVE_CRYPTOR_STUB
420 /* Stub */
421 static int
422 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
423 {
424 	(void)ctx; /* UNUSED */
425 	(void)key; /* UNUSED */
426 	(void)key_len; /* UNUSED */
427 	return -1;
428 }
429 
430 static int
431 aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
432 {
433 	(void)ctx; /* UNUSED */
434 	return -1;
435 }
436 
437 static int
438 aes_ctr_release(archive_crypto_ctx *ctx)
439 {
440 	(void)ctx; /* UNUSED */
441 	return 0;
442 }
443 
444 #endif
445 
446 #ifdef ARCHIVE_CRYPTOR_STUB
447 static int
448 aes_ctr_update(archive_crypto_ctx *ctx, const uint8_t * const in,
449     size_t in_len, uint8_t * const out, size_t *out_len)
450 {
451 	(void)ctx; /* UNUSED */
452 	(void)in; /* UNUSED */
453 	(void)in_len; /* UNUSED */
454 	(void)out; /* UNUSED */
455 	(void)out_len; /* UNUSED */
456 	aes_ctr_encrypt_counter(ctx); /* UNUSED */ /* Fix unused function warning */
457 	return -1;
458 }
459 
460 #else
461 static void
462 aes_ctr_increase_counter(archive_crypto_ctx *ctx)
463 {
464 	uint8_t *const nonce = ctx->nonce;
465 	int j;
466 
467 	for (j = 0; j < 8; j++) {
468 		if (++nonce[j])
469 			break;
470 	}
471 }
472 
473 static int
474 aes_ctr_update(archive_crypto_ctx *ctx, const uint8_t * const in,
475     size_t in_len, uint8_t * const out, size_t *out_len)
476 {
477 	uint8_t *const ebuf = ctx->encr_buf;
478 	unsigned pos = ctx->encr_pos;
479 	unsigned max = (unsigned)((in_len < *out_len)? in_len: *out_len);
480 	unsigned i;
481 
482 	for (i = 0; i < max; ) {
483 		if (pos == AES_BLOCK_SIZE) {
484 			aes_ctr_increase_counter(ctx);
485 			if (aes_ctr_encrypt_counter(ctx) != 0)
486 				return -1;
487 			while (max -i >= AES_BLOCK_SIZE) {
488 				for (pos = 0; pos < AES_BLOCK_SIZE; pos++)
489 					out[i+pos] = in[i+pos] ^ ebuf[pos];
490 				i += AES_BLOCK_SIZE;
491 				aes_ctr_increase_counter(ctx);
492 				if (aes_ctr_encrypt_counter(ctx) != 0)
493 					return -1;
494 			}
495 			pos = 0;
496 			if (i >= max)
497 				break;
498 		}
499 		out[i] = in[i] ^ ebuf[pos++];
500 		i++;
501 	}
502 	ctx->encr_pos = pos;
503 	*out_len = i;
504 
505 	return 0;
506 }
507 #endif /* ARCHIVE_CRYPTOR_STUB */
508 
509 
510 const struct archive_cryptor __archive_cryptor =
511 {
512   &pbkdf2_sha1,
513   &aes_ctr_init,
514   &aes_ctr_update,
515   &aes_ctr_release,
516   &aes_ctr_init,
517   &aes_ctr_update,
518   &aes_ctr_release,
519 };
520