Debian Codegraph @

crt/aws-c-cal/source/windows/bcrypt_aes.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include <aws/cal/private/symmetric_cipher_priv.h>
6
7 #include <windows.h>
8
9 /* keep the space to prevent formatters from reordering this with the windows.h header. */
10 #include <bcrypt.h>
11
12 /* handles for AES modes and algorithms we'll be using. These are initialized once and allowed to leak. */
13 static aws_thread_once s_aes_thread_once = AWS_THREAD_ONCE_STATIC_INIT;
14 static BCRYPT_ALG_HANDLE s_aes_cbc_algorithm_handle = NULL;
15 static BCRYPT_ALG_HANDLE s_aes_gcm_algorithm_handle = NULL;
16 static BCRYPT_ALG_HANDLE s_aes_ctr_algorithm_handle = NULL;
17 static BCRYPT_ALG_HANDLE s_aes_keywrap_algorithm_handle = NULL;
18
19 struct aes_bcrypt_cipher {
20 struct aws_symmetric_cipher cipher;
21 BCRYPT_ALG_HANDLE alg_handle;
22 /* the loaded key handle. */
23 BCRYPT_KEY_HANDLE key_handle;
24 /* Used for GCM mode to store IV, tag, and aad */
25 BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO *auth_info_ptr;
26 /* Updated on the fly for things like constant-time CBC padding and GCM hash chaining */
27 DWORD cipher_flags;
28 /* For things to work, they have to be in 16 byte chunks in several scenarios. Use this
29 Buffer for storing excess bytes until we have 16 bytes to operate on. */
30 struct aws_byte_buf overflow;
31 /* This gets updated as the algorithms run so it isn't the original IV. That's why its separate */
32 struct aws_byte_buf working_iv;
33 /* A buffer to keep around for the GMAC for GCM. Purely for BCrypt needs, we dont touch it. */
34 struct aws_byte_buf working_mac_buffer;
35 };
36
37 static void s_load_alg_handles(void *user_data) {
38 (void)user_data;
39
40 /* this function is incredibly slow, LET IT LEAK*/
41 NTSTATUS status = BCryptOpenAlgorithmProvider(&s_aes_cbc_algorithm_handle, BCRYPT_AES_ALGORITHM, NULL, 0);
42 AWS_FATAL_ASSERT(s_aes_cbc_algorithm_handle && "BCryptOpenAlgorithmProvider() failed");
43
44 status = BCryptSetProperty(
45 s_aes_cbc_algorithm_handle,
46 BCRYPT_CHAINING_MODE,
47 (PUCHAR)BCRYPT_CHAIN_MODE_CBC,
48 (ULONG)(wcslen(BCRYPT_CHAIN_MODE_CBC) + 1),
49 0);
50
51 AWS_FATAL_ASSERT(BCRYPT_SUCCESS(status) && "BCryptSetProperty for CBC chaining mode failed");
52
53 /* Set up GCM algorithm */
54 status = BCryptOpenAlgorithmProvider(&s_aes_gcm_algorithm_handle, BCRYPT_AES_ALGORITHM, NULL, 0);
55 AWS_FATAL_ASSERT(s_aes_gcm_algorithm_handle && "BCryptOpenAlgorithmProvider() failed");
56
57 status = BCryptSetProperty(
58 s_aes_gcm_algorithm_handle,
59 BCRYPT_CHAINING_MODE,
60 (PUCHAR)BCRYPT_CHAIN_MODE_GCM,
61 (ULONG)(wcslen(BCRYPT_CHAIN_MODE_GCM) + 1),
62 0);
63
64 AWS_FATAL_ASSERT(BCRYPT_SUCCESS(status) && "BCryptSetProperty for GCM chaining mode failed");
65
66 /* Setup CTR algorithm */
67 status = BCryptOpenAlgorithmProvider(&s_aes_ctr_algorithm_handle, BCRYPT_AES_ALGORITHM, NULL, 0);
68 AWS_FATAL_ASSERT(s_aes_ctr_algorithm_handle && "BCryptOpenAlgorithmProvider() failed");
69
70 /* This is ECB because windows doesn't do CTR mode for you.
71 Instead we use ECB and XOR the encrypted IV and data to operate on for each block. */
72 status = BCryptSetProperty(
73 s_aes_ctr_algorithm_handle,
74 BCRYPT_CHAINING_MODE,
75 (PUCHAR)BCRYPT_CHAIN_MODE_ECB,
76 (ULONG)(wcslen(BCRYPT_CHAIN_MODE_ECB) + 1),
77 0);
78
79 AWS_FATAL_ASSERT(BCRYPT_SUCCESS(status) && "BCryptSetProperty for ECB chaining mode failed");
80
81 /* Setup KEYWRAP algorithm */
82 status = BCryptOpenAlgorithmProvider(&s_aes_keywrap_algorithm_handle, BCRYPT_AES_ALGORITHM, NULL, 0);
83 AWS_FATAL_ASSERT(s_aes_ctr_algorithm_handle && "BCryptOpenAlgorithmProvider() failed");
84
85 AWS_FATAL_ASSERT(BCRYPT_SUCCESS(status) && "BCryptSetProperty for KeyWrap failed");
86 }
87
88 static BCRYPT_KEY_HANDLE s_import_key_blob(
89 BCRYPT_ALG_HANDLE algHandle,
90 struct aws_allocator *allocator,
91 struct aws_byte_buf *key) {
92 NTSTATUS status = 0;
93
94 BCRYPT_KEY_DATA_BLOB_HEADER key_data;
95 key_data.dwMagic = BCRYPT_KEY_DATA_BLOB_MAGIC;
96 key_data.dwVersion = BCRYPT_KEY_DATA_BLOB_VERSION1;
97 key_data.cbKeyData = (ULONG)key->len;
98
99 struct aws_byte_buf key_data_buf;
100 aws_byte_buf_init(&key_data_buf, allocator, sizeof(key_data) + key->len);
101 aws_byte_buf_write(&key_data_buf, (const uint8_t *)&key_data, sizeof(key_data));
102 aws_byte_buf_write(&key_data_buf, key->buffer, key->len);
103
104 BCRYPT_KEY_HANDLE key_handle;
105 status = BCryptImportKey(
106 algHandle, NULL, BCRYPT_KEY_DATA_BLOB, &key_handle, NULL, 0, key_data_buf.buffer, (ULONG)key_data_buf.len, 0);
107
108 aws_byte_buf_clean_up_secure(&key_data_buf);
109
110 if (!BCRYPT_SUCCESS(status)) {
111 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
112 return NULL;
113 }
114
115 return key_handle;
116 }
117
118 static void s_aes_default_destroy(struct aws_symmetric_cipher *cipher) {
119 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
120
121 aws_byte_buf_clean_up_secure(&cipher->key);
122 aws_byte_buf_clean_up_secure(&cipher->iv);
123 aws_byte_buf_clean_up_secure(&cipher->tag);
124 aws_byte_buf_clean_up_secure(&cipher->aad);
125
126 /* clean_up_secure exists in versions of aws-c-common that don't check that the
127 buffer has a buffer and an allocator before freeing the memory. Instead,
128 check here. If it's set the buffer was owned and needs to be cleaned up, otherwise
129 it can just be dropped as it was an alias.*/
130 if (cipher_impl->working_iv.allocator) {
131 aws_byte_buf_clean_up_secure(&cipher_impl->working_iv);
132 }
133
134 aws_byte_buf_clean_up_secure(&cipher_impl->overflow);
135 aws_byte_buf_clean_up_secure(&cipher_impl->working_mac_buffer);
136
137 if (cipher_impl->key_handle) {
138 BCryptDestroyKey(cipher_impl->key_handle);
139 cipher_impl->key_handle = NULL;
140 }
141
142 if (cipher_impl->auth_info_ptr) {
143 aws_mem_release(cipher->allocator, cipher_impl->auth_info_ptr);
144 cipher_impl->auth_info_ptr = NULL;
145 }
146
147 aws_mem_release(cipher->allocator, cipher_impl);
148 }
149
150 /* just a utility function for setting up windows Ciphers and keys etc....
151 Handles copying key/iv etc... data to the right buffers and then setting them
152 on the windows handles used for the encryption operations. */
153 static int s_initialize_cipher_materials(
154 struct aes_bcrypt_cipher *cipher,
155 const struct aws_byte_cursor *key,
156 const struct aws_byte_cursor *iv,
157 const struct aws_byte_cursor *aad,
158 size_t iv_size,
159 bool is_ctr_mode,
160 bool is_gcm) {
161
162 if (!cipher->cipher.key.len) {
163 if (key) {
164 aws_byte_buf_init_copy_from_cursor(&cipher->cipher.key, cipher->cipher.allocator, *key);
165 } else {
166 aws_byte_buf_init(&cipher->cipher.key, cipher->cipher.allocator, AWS_AES_256_KEY_BYTE_LEN);
167 aws_symmetric_cipher_generate_key(AWS_AES_256_KEY_BYTE_LEN, &cipher->cipher.key);
168 }
169 }
170
171 if (!cipher->cipher.iv.len && iv_size) {
172 if (iv) {
173 aws_byte_buf_init_copy_from_cursor(&cipher->cipher.iv, cipher->cipher.allocator, *iv);
174 } else {
175 aws_byte_buf_init(&cipher->cipher.iv, cipher->cipher.allocator, iv_size);
176 aws_symmetric_cipher_generate_initialization_vector(iv_size, is_ctr_mode, &cipher->cipher.iv);
177 }
178 }
179
180 aws_byte_buf_clean_up_secure(&cipher->cipher.tag);
181
182 /* these fields are only used in GCM mode. */
183 if (is_gcm) {
184 if (!cipher->cipher.aad.len) {
185 if (aad) {
186 aws_byte_buf_init_copy_from_cursor(&cipher->cipher.aad, cipher->cipher.allocator, *aad);
187 }
188 }
189
190 if (!cipher->working_mac_buffer.len) {
191 aws_byte_buf_init(&cipher->working_mac_buffer, cipher->cipher.allocator, AWS_AES_256_CIPHER_BLOCK_SIZE);
192 aws_byte_buf_secure_zero(&cipher->working_mac_buffer);
193 /* windows handles this, just go ahead and tell the API it's got a length. */
194 cipher->working_mac_buffer.len = AWS_AES_256_CIPHER_BLOCK_SIZE;
195 }
196 }
197
198 cipher->key_handle = s_import_key_blob(cipher->alg_handle, cipher->cipher.allocator, &cipher->cipher.key);
199
200 if (!cipher->key_handle) {
201 cipher->cipher.state = AWS_SYMMETRIC_CIPHER_ERROR;
202 return AWS_OP_ERR;
203 }
204
205 cipher->cipher_flags = 0;
206
207 /* In GCM mode, the IV is set on the auth info pointer and a working copy
208 is passed to each encrypt call. CBC and CTR mode function differently here
209 and the IV is set on the key itself. */
210 if (!is_gcm && cipher->cipher.iv.len) {
211 NTSTATUS status = BCryptSetProperty(
212 cipher->key_handle,
213 BCRYPT_INITIALIZATION_VECTOR,
214 cipher->cipher.iv.buffer,
215 (ULONG)cipher->cipher.iv.len,
216 0);
217
218 if (!BCRYPT_SUCCESS(status)) {
219 cipher->cipher.state = AWS_SYMMETRIC_CIPHER_ERROR;
220 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
221 }
222 } else if (is_gcm) {
223
224 cipher->auth_info_ptr =
225 aws_mem_acquire(cipher->cipher.allocator, sizeof(BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO));
226
227 /* Create a new authenticated cipher mode info object for GCM mode */
228 BCRYPT_INIT_AUTH_MODE_INFO(*cipher->auth_info_ptr);
229 cipher->auth_info_ptr->pbNonce = cipher->cipher.iv.buffer;
230 cipher->auth_info_ptr->cbNonce = (ULONG)cipher->cipher.iv.len;
231 cipher->auth_info_ptr->dwFlags = BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG;
232 cipher->auth_info_ptr->pbTag = NULL;
233 cipher->auth_info_ptr->cbTag = 0;
234 cipher->auth_info_ptr->pbMacContext = cipher->working_mac_buffer.buffer;
235 cipher->auth_info_ptr->cbMacContext = (ULONG)cipher->working_mac_buffer.len;
236
237 if (cipher->cipher.aad.len) {
238 cipher->auth_info_ptr->pbAuthData = (PUCHAR)cipher->cipher.aad.buffer;
239 cipher->auth_info_ptr->cbAuthData = (ULONG)cipher->cipher.aad.len;
240 }
241 }
242
243 return AWS_OP_SUCCESS;
244 }
245
246 /* Free up as few resources as possible so we can quickly reuse the cipher. */
247 static void s_clear_reusable_components(struct aws_symmetric_cipher *cipher) {
248 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
249 bool working_iv_optimized = cipher->iv.buffer == cipher_impl->working_iv.buffer;
250
251 if (!working_iv_optimized) {
252 aws_byte_buf_secure_zero(&cipher_impl->working_iv);
253 }
254
255 /* These can't always be reused in the next operation, so go ahead and destroy it
256 and create another. */
257 if (cipher_impl->key_handle) {
258 BCryptDestroyKey(cipher_impl->key_handle);
259 cipher_impl->key_handle = NULL;
260 }
261
262 if (cipher_impl->auth_info_ptr) {
263 aws_mem_release(cipher->allocator, cipher_impl->auth_info_ptr);
264 cipher_impl->auth_info_ptr = NULL;
265 }
266
267 aws_byte_buf_secure_zero(&cipher_impl->overflow);
268
269 if (cipher_impl->working_mac_buffer.capacity != 0) {
270 aws_byte_buf_secure_zero(&cipher_impl->working_mac_buffer);
271 /* windows handles this, just go ahead and tell the API it's got a length. */
272 cipher_impl->working_mac_buffer.len = AWS_AES_256_CIPHER_BLOCK_SIZE;
273 }
274 }
275
276 static int s_reset_cbc_cipher(struct aws_symmetric_cipher *cipher) {
277 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
278
279 s_clear_reusable_components(cipher);
280 return s_initialize_cipher_materials(cipher_impl, NULL, NULL, NULL, AWS_AES_256_CIPHER_BLOCK_SIZE, false, false);
281 }
282
283 static int s_reset_ctr_cipher(struct aws_symmetric_cipher *cipher) {
284 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
285
286 s_clear_reusable_components(cipher);
287 struct aws_byte_cursor iv_cur = aws_byte_cursor_from_buf(&cipher->iv);
288 /* reset the working iv back to the original IV. We do this because
289 we're manually maintaining the counter. */
290 aws_byte_buf_append_dynamic(&cipher_impl->working_iv, &iv_cur);
291 return s_initialize_cipher_materials(cipher_impl, NULL, NULL, NULL, AWS_AES_256_CIPHER_BLOCK_SIZE, true, false);
292 }
293
294 static int s_reset_gcm_cipher(struct aws_symmetric_cipher *cipher) {
295 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
296
297 s_clear_reusable_components(cipher);
298 return s_initialize_cipher_materials(cipher_impl, NULL, NULL, NULL, AWS_AES_256_CIPHER_BLOCK_SIZE - 4, false, true);
299 }
300
301 static int s_aes_default_encrypt(
302 struct aws_symmetric_cipher *cipher,
303 const struct aws_byte_cursor *to_encrypt,
304 struct aws_byte_buf *out) {
305 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
306
307 size_t predicted_write_length =
308 cipher_impl->cipher_flags & BCRYPT_BLOCK_PADDING
309 ? to_encrypt->len + (AWS_AES_256_CIPHER_BLOCK_SIZE - (to_encrypt->len % AWS_AES_256_CIPHER_BLOCK_SIZE))
310 : to_encrypt->len;
311
312 ULONG length_written = (ULONG)(predicted_write_length);
313
314 if (aws_symmetric_cipher_try_ensure_sufficient_buffer_space(out, predicted_write_length)) {
315 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
316 }
317
318 PUCHAR iv = NULL;
319 ULONG iv_size = 0;
320
321 if (cipher_impl->auth_info_ptr) {
322 iv = cipher_impl->working_iv.buffer;
323 /* this is looking for buffer size, and the working_iv has only been written to by windows the GCM case.
324 * So use capacity rather than length */
325 iv_size = (ULONG)cipher_impl->working_iv.capacity;
326 }
327
328 /* iv was set on the key itself, so we don't need to pass it here. */
329 NTSTATUS status = BCryptEncrypt(
330 cipher_impl->key_handle,
331 to_encrypt->ptr,
332 (ULONG)to_encrypt->len,
333 cipher_impl->auth_info_ptr,
334 iv,
335 iv_size,
336 out->buffer + out->len,
337 (ULONG)(out->capacity - out->len),
338 &length_written,
339 cipher_impl->cipher_flags);
340
341 if (!BCRYPT_SUCCESS(status)) {
342 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
343 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
344 }
345
346 out->len += length_written;
347 return AWS_OP_SUCCESS;
348 }
349
350 /* manages making sure encryption operations can operate on 16 byte blocks. Stores the excess in the overflow
351 buffer and moves stuff around each time to make sure everything is in order. */
352 static struct aws_byte_buf s_fill_in_overflow(
353 struct aws_symmetric_cipher *cipher,
354 const struct aws_byte_cursor *to_operate) {
355 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
356
357 static const size_t RESERVE_SIZE = AWS_AES_256_CIPHER_BLOCK_SIZE * 2;
358 cipher_impl->cipher_flags = 0;
359
360 struct aws_byte_buf final_to_operate_on;
361 AWS_ZERO_STRUCT(final_to_operate_on);
362
363 if (cipher_impl->overflow.len > 0) {
364 aws_byte_buf_init_copy(&final_to_operate_on, cipher->allocator, &cipher_impl->overflow);
365 aws_byte_buf_append_dynamic(&final_to_operate_on, to_operate);
366 aws_byte_buf_secure_zero(&cipher_impl->overflow);
367 } else {
368 aws_byte_buf_init_copy_from_cursor(&final_to_operate_on, cipher->allocator, *to_operate);
369 }
370
371 size_t overflow = final_to_operate_on.len % RESERVE_SIZE;
372
373 if (final_to_operate_on.len > RESERVE_SIZE) {
374 size_t offset = overflow == 0 ? RESERVE_SIZE : overflow;
375
376 struct aws_byte_cursor slice_for_overflow = aws_byte_cursor_from_buf(&final_to_operate_on);
377 aws_byte_cursor_advance(&slice_for_overflow, final_to_operate_on.len - offset);
378 aws_byte_buf_append_dynamic(&cipher_impl->overflow, &slice_for_overflow);
379 final_to_operate_on.len -= offset;
380 } else {
381 struct aws_byte_cursor final_cur = aws_byte_cursor_from_buf(&final_to_operate_on);
382 aws_byte_buf_append_dynamic(&cipher_impl->overflow, &final_cur);
383 aws_byte_buf_clean_up_secure(&final_to_operate_on);
384 }
385
386 return final_to_operate_on;
387 }
388
389 static int s_aes_cbc_encrypt(
390 struct aws_symmetric_cipher *cipher,
391 struct aws_byte_cursor to_encrypt,
392 struct aws_byte_buf *out) {
393
394 struct aws_byte_buf final_to_encrypt = s_fill_in_overflow(cipher, &to_encrypt);
395 struct aws_byte_cursor final_cur = aws_byte_cursor_from_buf(&final_to_encrypt);
396 int ret_val = AWS_OP_SUCCESS;
397 if (final_cur.len > 0) {
398 ret_val = s_aes_default_encrypt(cipher, &final_cur, out);
399 }
400
401 aws_byte_buf_clean_up_secure(&final_to_encrypt);
402
403 return ret_val;
404 }
405
406 static int s_aes_cbc_finalize_encryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out) {
407 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
408
409 if (cipher->state == AWS_SYMMETRIC_CIPHER_READY && cipher_impl->overflow.len > 0) {
410 cipher_impl->cipher_flags = BCRYPT_BLOCK_PADDING;
411 /* take the rest of the overflow and turn padding on so the remainder is properly padded
412 without timing attack vulnerabilities. */
413 struct aws_byte_cursor remaining_cur = aws_byte_cursor_from_buf(&cipher_impl->overflow);
414 int ret_val = s_aes_default_encrypt(cipher, &remaining_cur, out);
415 aws_byte_buf_secure_zero(&cipher_impl->overflow);
416 return ret_val;
417 }
418
419 return AWS_OP_SUCCESS;
420 }
421
422 static int s_default_aes_decrypt(
423 struct aws_symmetric_cipher *cipher,
424 const struct aws_byte_cursor *to_decrypt,
425 struct aws_byte_buf *out) {
426 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
427
428 PUCHAR iv = NULL;
429 ULONG iv_size = 0;
430
431 if (cipher_impl->auth_info_ptr) {
432 iv = cipher_impl->working_iv.buffer;
433 /* this is looking for buffer size, and the working_iv has only been written to by windows the GCM case.
434 * So use capacity rather than length */
435 iv_size = (ULONG)cipher_impl->working_iv.capacity;
436 }
437
438 size_t predicted_write_length = to_decrypt->len;
439 ULONG length_written = (ULONG)(predicted_write_length);
440
441 if (aws_symmetric_cipher_try_ensure_sufficient_buffer_space(out, predicted_write_length)) {
442 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
443 }
444
445 /* iv was set on the key itself, so we don't need to pass it here. */
446 NTSTATUS status = BCryptDecrypt(
447 cipher_impl->key_handle,
448 to_decrypt->ptr,
449 (ULONG)to_decrypt->len,
450 cipher_impl->auth_info_ptr,
451 iv,
452 iv_size,
453 out->buffer + out->len,
454 (ULONG)(out->capacity - out->len),
455 &length_written,
456 cipher_impl->cipher_flags);
457
458 if (!BCRYPT_SUCCESS(status)) {
459 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
460 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
461 }
462
463 out->len += length_written;
464 return AWS_OP_SUCCESS;
465 }
466
467 static int s_aes_cbc_decrypt(
468 struct aws_symmetric_cipher *cipher,
469 struct aws_byte_cursor to_decrypt,
470 struct aws_byte_buf *out) {
471 struct aws_byte_buf final_to_decrypt = s_fill_in_overflow(cipher, &to_decrypt);
472 struct aws_byte_cursor final_cur = aws_byte_cursor_from_buf(&final_to_decrypt);
473 int ret_val = AWS_OP_SUCCESS;
474 if (final_cur.len > 0) {
475 ret_val = s_default_aes_decrypt(cipher, &final_cur, out);
476 }
477
478 aws_byte_buf_clean_up_secure(&final_to_decrypt);
479
480 return ret_val;
481 }
482
483 static int s_aes_cbc_finalize_decryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out) {
484 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
485
486 if (cipher->state == AWS_SYMMETRIC_CIPHER_READY && cipher_impl->overflow.len > 0) {
487 cipher_impl->cipher_flags = BCRYPT_BLOCK_PADDING;
488 /* take the rest of the overflow and turn padding on so the remainder is properly padded
489 without timing attack vulnerabilities. */
490 struct aws_byte_cursor remaining_cur = aws_byte_cursor_from_buf(&cipher_impl->overflow);
491 int ret_val = s_default_aes_decrypt(cipher, &remaining_cur, out);
492 aws_byte_buf_secure_zero(&cipher_impl->overflow);
493 return ret_val;
494 }
495
496 return AWS_OP_SUCCESS;
497 }
498
499 static struct aws_symmetric_cipher_vtable s_aes_cbc_vtable = {
500 .alg_name = "AES-CBC 256",
501 .provider = "Windows CNG",
502 .decrypt = s_aes_cbc_decrypt,
503 .encrypt = s_aes_cbc_encrypt,
504 .finalize_encryption = s_aes_cbc_finalize_encryption,
505 .finalize_decryption = s_aes_cbc_finalize_decryption,
506 .destroy = s_aes_default_destroy,
507 .reset = s_reset_cbc_cipher,
508 };
509
510 struct aws_symmetric_cipher *aws_aes_cbc_256_new_impl(
511 struct aws_allocator *allocator,
512 const struct aws_byte_cursor *key,
513 const struct aws_byte_cursor *iv) {
514
515 aws_thread_call_once(&s_aes_thread_once, s_load_alg_handles, NULL);
516
517 struct aes_bcrypt_cipher *cipher = aws_mem_calloc(allocator, 1, sizeof(struct aes_bcrypt_cipher));
518
519 cipher->cipher.allocator = allocator;
520 cipher->cipher.block_size = AWS_AES_256_CIPHER_BLOCK_SIZE;
521 cipher->cipher.key_length_bits = AWS_AES_256_KEY_BIT_LEN;
522 cipher->alg_handle = s_aes_cbc_algorithm_handle;
523 cipher->cipher.vtable = &s_aes_cbc_vtable;
524
525 if (s_initialize_cipher_materials(cipher, key, iv, NULL, AWS_AES_256_CIPHER_BLOCK_SIZE, false, false) !=
526 AWS_OP_SUCCESS) {
527 goto error;
528 }
529
530 aws_byte_buf_init(&cipher->overflow, allocator, AWS_AES_256_CIPHER_BLOCK_SIZE * 2);
531 cipher->working_iv = cipher->cipher.iv;
532 /* make sure the cleanup doesn't do anything. */
533 cipher->working_iv.allocator = NULL;
534 cipher->cipher.impl = cipher;
535 cipher->cipher.state = AWS_SYMMETRIC_CIPHER_READY;
536
537 return &cipher->cipher;
538
539 error:
540 return NULL;
541 }
542
543 /*
544 * The buffer management for gcm mode is a good deal easier than ctr and cbc modes because we don't care about padding.
545 * In chained mode, BCrypt expects the data to be passed in in multiples of block size,
546 * followed by a finalize call that turns off chaining and provides any remaining data.
547 * This function takes care of managing this state - you give it data to work and cipher state and
548 * it will return what data can be sent to bcrypt now and as side effect will update the cipher state
549 * with any leftover data.
550 * Note: this function takes a scratch buffer that might be used for to back data returned by the cursor.
551 * It is on caller to cleanup that scratch buffer.
552 */
553 static struct aws_byte_cursor s_gcm_get_working_slice(
554 struct aes_bcrypt_cipher *cipher_impl,
555 struct aws_byte_cursor data,
556 struct aws_byte_buf *scratch) {
557 AWS_PRECONDITION(cipher_impl);
558 AWS_PRECONDITION(scratch);
559
560 AWS_ZERO_STRUCT(*scratch);
561
562 struct aws_byte_cursor working_cur;
563 AWS_ZERO_STRUCT(working_cur);
564 /* If there's overflow, prepend it to the working buffer, then append the data */
565 if (cipher_impl->overflow.len) {
566 aws_byte_buf_init(scratch, cipher_impl->cipher.allocator, cipher_impl->overflow.len + data.len);
567 struct aws_byte_cursor overflow_cur = aws_byte_cursor_from_buf(&cipher_impl->overflow);
568 aws_byte_buf_append(scratch, &overflow_cur);
569 aws_byte_buf_reset(&cipher_impl->overflow, true);
570 aws_byte_buf_append(scratch, &data);
571 working_cur = aws_byte_cursor_from_buf(scratch);
572 } else {
573 working_cur = data;
574 }
575
576 struct aws_byte_cursor return_cur;
577 AWS_ZERO_STRUCT(return_cur);
578
579 if (working_cur.len >= AWS_AES_256_CIPHER_BLOCK_SIZE) {
580 size_t seek_to = working_cur.len - (working_cur.len % AWS_AES_256_CIPHER_BLOCK_SIZE);
581 return_cur = aws_byte_cursor_advance(&working_cur, seek_to);
582 aws_byte_buf_append_dynamic(&cipher_impl->overflow, &working_cur);
583
584 } else {
585 aws_byte_buf_append_dynamic(&cipher_impl->overflow, &working_cur);
586 }
587
588 return return_cur;
589 }
590
591 /*
592 * bcrypt requires pbTag and cbTag initialized before starting chained encrypt or decrypt.
593 * why bcrypt needs it initialized early and every other lib can wait until is a mystery.
594 * following function is a helper to init the state correctly for encrypt (and decrypt has a similar function later).
595 * For encrypt this blows away whatever tag user might have set and ensures that it's at least block size.
596 * Note: gcm supports shorter tags, but bcrypt always generates block sized one
597 * (caller can decide to make them shorter by removing bytes from the end).
598 */
599 static void s_gcm_ensure_tag_setup_for_encrypt(struct aws_symmetric_cipher *cipher) {
600 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
601
602 if (cipher_impl->auth_info_ptr->pbTag == NULL) {
603 if (cipher->tag.buffer == NULL) {
604 aws_byte_buf_init(&cipher->tag, cipher->allocator, AWS_AES_256_CIPHER_BLOCK_SIZE);
605 } else {
606 aws_byte_buf_secure_zero(&cipher->tag);
607 aws_byte_buf_reserve(&cipher->tag, AWS_AES_256_CIPHER_BLOCK_SIZE);
608 }
609 cipher_impl->auth_info_ptr->pbTag = cipher->tag.buffer;
610 cipher_impl->auth_info_ptr->cbTag = (ULONG)cipher->tag.capacity;
611 /* bcrypt will either end up filling full tag buffer or in an error state,
612 /* in which tag will not be correct */
613 cipher->tag.len = AWS_AES_256_CIPHER_BLOCK_SIZE;
614 }
615 }
616
617 static int s_aes_gcm_encrypt(
618 struct aws_symmetric_cipher *cipher,
619 struct aws_byte_cursor to_encrypt,
620 struct aws_byte_buf *out) {
621 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
622
623 s_gcm_ensure_tag_setup_for_encrypt(cipher);
624
625 struct aws_byte_buf working_buffer;
626 struct aws_byte_cursor working_cur = s_gcm_get_working_slice(cipher_impl, to_encrypt, &working_buffer);
627
628 int ret_val = AWS_OP_SUCCESS;
629 if (working_cur.len > 0) {
630 ret_val = s_aes_default_encrypt(cipher, &working_cur, out);
631 }
632
633 aws_byte_buf_clean_up_secure(&working_buffer);
634 return ret_val;
635 }
636
637 static int s_gcm_ensure_tag_setup_for_decrypt(struct aws_symmetric_cipher *cipher) {
638 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
639
640 if (cipher->tag.buffer == NULL) {
641 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
642 }
643
644 if (cipher_impl->auth_info_ptr->pbTag == NULL) {
645 cipher_impl->auth_info_ptr->pbTag = cipher->tag.buffer;
646 cipher_impl->auth_info_ptr->cbTag = (ULONG)cipher->tag.len;
647 }
648
649 return AWS_OP_SUCCESS;
650 }
651
652 static int s_aes_gcm_decrypt(
653 struct aws_symmetric_cipher *cipher,
654 struct aws_byte_cursor to_decrypt,
655 struct aws_byte_buf *out) {
656 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
657
658 if (s_gcm_ensure_tag_setup_for_decrypt(cipher)) {
659 return AWS_OP_ERR;
660 }
661
662 struct aws_byte_buf working_buffer;
663 struct aws_byte_cursor working_cur = s_gcm_get_working_slice(cipher_impl, to_decrypt, &working_buffer);
664
665 int ret_val = AWS_OP_SUCCESS;
666 if (working_cur.len > 0) {
667 ret_val = s_default_aes_decrypt(cipher, &working_cur, out);
668 }
669
670 aws_byte_buf_clean_up_secure(&working_buffer);
671 return ret_val;
672 }
673
674 static int s_aes_gcm_finalize_encryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out) {
675 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
676
677 s_gcm_ensure_tag_setup_for_encrypt(cipher);
678
679 cipher_impl->auth_info_ptr->dwFlags &= ~BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG;
680
681 /* take whatever is remaining, make the final encrypt call with the auth chain flag turned off. */
682 struct aws_byte_cursor remaining_cur = aws_byte_cursor_from_buf(&cipher_impl->overflow);
683 int ret_val = s_aes_default_encrypt(cipher, &remaining_cur, out);
684
685 aws_byte_buf_secure_zero(&cipher_impl->overflow);
686 aws_byte_buf_secure_zero(&cipher_impl->working_iv);
687 return ret_val;
688 }
689
690 static int s_aes_gcm_finalize_decryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out) {
691 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
692
693 if (s_gcm_ensure_tag_setup_for_decrypt(cipher)) {
694 return AWS_OP_ERR;
695 }
696
697 cipher_impl->auth_info_ptr->dwFlags &= ~BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG;
698
699 /* take whatever is remaining, make the final decrypt call with the auth chain flag turned off. */
700 struct aws_byte_cursor remaining_cur = aws_byte_cursor_from_buf(&cipher_impl->overflow);
701 int ret_val = s_default_aes_decrypt(cipher, &remaining_cur, out);
702 aws_byte_buf_secure_zero(&cipher_impl->overflow);
703 aws_byte_buf_secure_zero(&cipher_impl->working_iv);
704 return ret_val;
705 }
706
707 static struct aws_symmetric_cipher_vtable s_aes_gcm_vtable = {
708 .alg_name = "AES-GCM 256",
709 .provider = "Windows CNG",
710 .decrypt = s_aes_gcm_decrypt,
711 .encrypt = s_aes_gcm_encrypt,
712 .finalize_encryption = s_aes_gcm_finalize_encryption,
713 .finalize_decryption = s_aes_gcm_finalize_decryption,
714 .destroy = s_aes_default_destroy,
715 .reset = s_reset_gcm_cipher,
716 };
717
718 struct aws_symmetric_cipher *aws_aes_gcm_256_new_impl(
719 struct aws_allocator *allocator,
720 const struct aws_byte_cursor *key,
721 const struct aws_byte_cursor *iv,
722 const struct aws_byte_cursor *aad) {
723
724 aws_thread_call_once(&s_aes_thread_once, s_load_alg_handles, NULL);
725 struct aes_bcrypt_cipher *cipher = aws_mem_calloc(allocator, 1, sizeof(struct aes_bcrypt_cipher));
726
727 cipher->cipher.allocator = allocator;
728 cipher->cipher.block_size = AWS_AES_256_CIPHER_BLOCK_SIZE;
729 cipher->cipher.key_length_bits = AWS_AES_256_KEY_BIT_LEN;
730 cipher->alg_handle = s_aes_gcm_algorithm_handle;
731 cipher->cipher.vtable = &s_aes_gcm_vtable;
732
733 /* GCM does the counting under the hood, so we let it handle the final 4 bytes of the IV. */
734 if (s_initialize_cipher_materials(cipher, key, iv, aad, AWS_AES_256_CIPHER_BLOCK_SIZE - 4, false, true) !=
735 AWS_OP_SUCCESS) {
736 goto error;
737 }
738
739 aws_byte_buf_init(&cipher->overflow, allocator, AWS_AES_256_CIPHER_BLOCK_SIZE * 2);
740 aws_byte_buf_init(&cipher->working_iv, allocator, AWS_AES_256_CIPHER_BLOCK_SIZE);
741 aws_byte_buf_secure_zero(&cipher->working_iv);
742
743 cipher->cipher.impl = cipher;
744 cipher->cipher.state = AWS_SYMMETRIC_CIPHER_READY;
745
746 return &cipher->cipher;
747
748 error:
749 if (cipher != NULL) {
750 s_aes_default_destroy(&cipher->cipher);
751 }
752
753 return NULL;
754 }
755
756 /* Take a and b, XOR them and store it in dest. Notice the XOR is done up to the length of the smallest input.
757 If there's a bug in here, it's being hit inside the finalize call when there's an input stream that isn't an even
758 multiple of 16.
759 */
760 static int s_xor_cursors(const struct aws_byte_cursor *a, const struct aws_byte_cursor *b, struct aws_byte_buf *dest) {
761 size_t min_size = aws_min_size(b->len, a->len);
762
763 if (aws_symmetric_cipher_try_ensure_sufficient_buffer_space(dest, min_size)) {
764 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
765 }
766
767 /* If the profiler is saying this is slow, SIMD the loop below. */
768 uint8_t *array_ref = dest->buffer + dest->len;
769
770 for (size_t i = 0; i < min_size; ++i) {
771 array_ref[i] = a->ptr[i] ^ b->ptr[i];
772 }
773
774 dest->len += min_size;
775
776 return AWS_OP_SUCCESS;
777 }
778
779 /* There is no CTR mode on windows. Instead, we use AES ECB to encrypt the IV a block at a time.
780 That value is then XOR'd with the to_encrypt cursor and appended to out. The counter then needs
781 to be incremented by 1 for the next call. This has to be done a block at a time, so we slice
782 to_encrypt into a cursor per block and do this process for each block. Also notice that CTR mode
783 is symmetric for encryption and decryption (encrypt and decrypt are the same thing). */
784 static int s_aes_ctr_encrypt(
785 struct aws_symmetric_cipher *cipher,
786 struct aws_byte_cursor to_encrypt,
787 struct aws_byte_buf *out) {
788 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
789
790 if (to_encrypt.len == 0) {
791 return AWS_OP_SUCCESS;
792 }
793
794 struct aws_byte_buf working_buffer;
795 AWS_ZERO_STRUCT(working_buffer);
796
797 /* prepend overflow to the working buffer and then append to_encrypt to it. */
798 if (cipher_impl->overflow.len && to_encrypt.ptr != cipher_impl->overflow.buffer) {
799 struct aws_byte_cursor overflow_cur = aws_byte_cursor_from_buf(&cipher_impl->overflow);
800 aws_byte_buf_init_copy_from_cursor(&working_buffer, cipher->allocator, overflow_cur);
801 aws_byte_buf_reset(&cipher_impl->overflow, true);
802 aws_byte_buf_append_dynamic(&working_buffer, &to_encrypt);
803 } else {
804 aws_byte_buf_init_copy_from_cursor(&working_buffer, cipher->allocator, to_encrypt);
805 }
806
807 /* slice working_buffer into a slice per block. */
808 struct aws_array_list sliced_buffers;
809 aws_array_list_init_dynamic(
810 &sliced_buffers,
811 cipher->allocator,
812 (to_encrypt.len / AWS_AES_256_CIPHER_BLOCK_SIZE) + 1,
813 sizeof(struct aws_byte_cursor));
814
815 struct aws_byte_cursor working_buf_cur = aws_byte_cursor_from_buf(&working_buffer);
816 while (working_buf_cur.len) {
817 struct aws_byte_cursor slice = working_buf_cur;
818
819 if (working_buf_cur.len >= AWS_AES_256_CIPHER_BLOCK_SIZE) {
820 slice = aws_byte_cursor_advance(&working_buf_cur, AWS_AES_256_CIPHER_BLOCK_SIZE);
821 } else {
822 aws_byte_cursor_advance(&working_buf_cur, slice.len);
823 }
824
825 aws_array_list_push_back(&sliced_buffers, &slice);
826 }
827
828 int ret_val = AWS_OP_ERR;
829
830 size_t sliced_buffers_cnt = aws_array_list_length(&sliced_buffers);
831
832 /* for each slice, if it's a full block, do ECB on the IV, xor it to the slice, and then increment the counter. */
833 for (size_t i = 0; i < sliced_buffers_cnt; ++i) {
834 struct aws_byte_cursor buffer_cur;
835 AWS_ZERO_STRUCT(buffer_cur);
836
837 aws_array_list_get_at(&sliced_buffers, &buffer_cur, i);
838 if (buffer_cur.len == AWS_AES_256_CIPHER_BLOCK_SIZE ||
839 /* this part of the branch is for handling the finalize call, which does not have to be on an even
840 block boundary. */
841 (cipher_impl->overflow.len > 0 && sliced_buffers_cnt) == 1) {
842
843 ULONG lengthWritten = (ULONG)AWS_AES_256_CIPHER_BLOCK_SIZE;
844 uint8_t temp_buffer[AWS_AES_256_CIPHER_BLOCK_SIZE] = {0};
845 struct aws_byte_cursor temp_cur = aws_byte_cursor_from_array(temp_buffer, sizeof(temp_buffer));
846
847 NTSTATUS status = BCryptEncrypt(
848 cipher_impl->key_handle,
849 cipher_impl->working_iv.buffer,
850 (ULONG)cipher_impl->working_iv.len,
851 NULL,
852 NULL,
853 0,
854 temp_cur.ptr,
855 (ULONG)temp_cur.len,
856 &lengthWritten,
857 cipher_impl->cipher_flags);
858
859 if (!BCRYPT_SUCCESS(status)) {
860 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
861 ret_val = aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
862 goto clean_up;
863 }
864
865 /* this does the XOR, after this call the final encrypted output is added to out. */
866 if (s_xor_cursors(&buffer_cur, &temp_cur, out)) {
867 ret_val = AWS_OP_ERR;
868 goto clean_up;
869 }
870
871 /* increment the counter. Get the buffers aligned for it first though. */
872 size_t counter_offset = AWS_AES_256_CIPHER_BLOCK_SIZE - sizeof(uint32_t);
873 struct aws_byte_buf counter_buf = cipher_impl->working_iv;
874 /* roll it back 4 so the write works. */
875 counter_buf.len = counter_offset;
876 struct aws_byte_cursor counter_cur = aws_byte_cursor_from_buf(&cipher_impl->working_iv);
877 aws_byte_cursor_advance(&counter_cur, counter_offset);
878
879 /* read current counter value as a Big-endian 32-bit integer*/
880 uint32_t counter = 0;
881 aws_byte_cursor_read_be32(&counter_cur, &counter);
882
883 /* check for overflow here. */
884 if (aws_add_u32_checked(counter, 1, &counter) != AWS_OP_SUCCESS) {
885 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
886 ret_val = AWS_OP_ERR;
887 goto clean_up;
888 }
889 /* put the incremented counter back. */
890 aws_byte_buf_write_be32(&counter_buf, counter);
891 } else {
892 /* otherwise dump it into the overflow and wait til the next call */
893 aws_byte_buf_append_dynamic(&cipher_impl->overflow, &buffer_cur);
894 }
895
896 ret_val = AWS_OP_SUCCESS;
897 }
898
899 clean_up:
900 aws_array_list_clean_up_secure(&sliced_buffers);
901 aws_byte_buf_clean_up_secure(&working_buffer);
902
903 return ret_val;
904 }
905
906 static int s_aes_ctr_finalize_encryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out) {
907 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
908
909 struct aws_byte_cursor remaining_cur = aws_byte_cursor_from_buf(&cipher_impl->overflow);
910 /* take the final overflow, and do the final encrypt call for it. */
911 int ret_val = s_aes_ctr_encrypt(cipher, remaining_cur, out);
912 aws_byte_buf_secure_zero(&cipher_impl->overflow);
913 aws_byte_buf_secure_zero(&cipher_impl->working_iv);
914 return ret_val;
915 }
916
917 static struct aws_symmetric_cipher_vtable s_aes_ctr_vtable = {
918 .alg_name = "AES-CTR 256",
919 .provider = "Windows CNG",
920 .decrypt = s_aes_ctr_encrypt,
921 .encrypt = s_aes_ctr_encrypt,
922 .finalize_encryption = s_aes_ctr_finalize_encryption,
923 .finalize_decryption = s_aes_ctr_finalize_encryption,
924 .destroy = s_aes_default_destroy,
925 .reset = s_reset_ctr_cipher,
926 };
927
928 struct aws_symmetric_cipher *aws_aes_ctr_256_new_impl(
929 struct aws_allocator *allocator,
930 const struct aws_byte_cursor *key,
931 const struct aws_byte_cursor *iv) {
932
933 aws_thread_call_once(&s_aes_thread_once, s_load_alg_handles, NULL);
934 struct aes_bcrypt_cipher *cipher = aws_mem_calloc(allocator, 1, sizeof(struct aes_bcrypt_cipher));
935
936 cipher->cipher.allocator = allocator;
937 cipher->cipher.block_size = AWS_AES_256_CIPHER_BLOCK_SIZE;
938 cipher->cipher.key_length_bits = AWS_AES_256_KEY_BIT_LEN;
939 cipher->alg_handle = s_aes_ctr_algorithm_handle;
940 cipher->cipher.vtable = &s_aes_ctr_vtable;
941
942 if (s_initialize_cipher_materials(cipher, key, iv, NULL, AWS_AES_256_CIPHER_BLOCK_SIZE, true, false) !=
943 AWS_OP_SUCCESS) {
944 goto error;
945 }
946
947 aws_byte_buf_init(&cipher->overflow, allocator, AWS_AES_256_CIPHER_BLOCK_SIZE * 2);
948 aws_byte_buf_init_copy(&cipher->working_iv, allocator, &cipher->cipher.iv);
949
950 cipher->cipher.impl = cipher;
951 cipher->cipher.state = AWS_SYMMETRIC_CIPHER_READY;
952
953 return &cipher->cipher;
954
955 error:
956 if (cipher != NULL) {
957 s_aes_default_destroy(&cipher->cipher);
958 }
959
960 return NULL;
961 }
962
963 /* This is just an encrypted key. Append them to a buffer and on finalize export/import the key using AES keywrap. */
964 static int s_key_wrap_encrypt_decrypt(
965 struct aws_symmetric_cipher *cipher,
966 const struct aws_byte_cursor input,
967 struct aws_byte_buf *out) {
968 (void)out;
969 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
970
971 return aws_byte_buf_append_dynamic(&cipher_impl->overflow, &input);
972 }
973
974 /* Import the buffer we've been appending to as an AES key. Then export it using AES Keywrap format. */
975 static int s_keywrap_finalize_encryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out) {
976 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
977
978 BCRYPT_KEY_HANDLE key_handle_to_encrypt =
979 s_import_key_blob(s_aes_keywrap_algorithm_handle, cipher->allocator, &cipher_impl->overflow);
980
981 if (!key_handle_to_encrypt) {
982 return AWS_OP_ERR;
983 }
984
985 NTSTATUS status = 0;
986
987 ULONG output_size = 0;
988 /* Call with NULL first to get the required size. */
989 status = BCryptExportKey(
990 key_handle_to_encrypt, cipher_impl->key_handle, BCRYPT_AES_WRAP_KEY_BLOB, NULL, 0, &output_size, 0);
991
992 if (!BCRYPT_SUCCESS(status)) {
993 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
994 return aws_raise_error(AWS_ERROR_INVALID_STATE);
995 }
996
997 int ret_val = AWS_OP_ERR;
998
999 if (aws_symmetric_cipher_try_ensure_sufficient_buffer_space(out, output_size)) {
1000 goto clean_up;
1001 }
1002
1003 /* now actually export the key */
1004 ULONG len_written = 0;
1005 status = BCryptExportKey(
1006 key_handle_to_encrypt,
1007 cipher_impl->key_handle,
1008 BCRYPT_AES_WRAP_KEY_BLOB,
1009 out->buffer + out->len,
1010 output_size,
1011 &len_written,
1012 0);
1013
1014 if (!BCRYPT_SUCCESS(status)) {
1015 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
1016 goto clean_up;
1017 }
1018
1019 out->len += len_written;
1020
1021 ret_val = AWS_OP_SUCCESS;
1022
1023 clean_up:
1024 if (key_handle_to_encrypt) {
1025 BCryptDestroyKey(key_handle_to_encrypt);
1026 }
1027
1028 return ret_val;
1029 }
1030
1031 /* Import the buffer we've been appending to as an AES Key Wrapped key. Then export the raw AES key. */
1032
1033 static int s_keywrap_finalize_decryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out) {
1034 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
1035
1036 BCRYPT_KEY_HANDLE import_key = NULL;
1037
1038 /* use the cipher key to import the buffer as an AES keywrapped key. */
1039 NTSTATUS status = BCryptImportKey(
1040 s_aes_keywrap_algorithm_handle,
1041 cipher_impl->key_handle,
1042 BCRYPT_AES_WRAP_KEY_BLOB,
1043 &import_key,
1044 NULL,
1045 0,
1046 cipher_impl->overflow.buffer,
1047 (ULONG)cipher_impl->overflow.len,
1048 0);
1049 int ret_val = AWS_OP_ERR;
1050
1051 if (BCRYPT_SUCCESS(status) && import_key) {
1052 ULONG export_size = 0;
1053
1054 struct aws_byte_buf key_data_blob;
1055 aws_byte_buf_init(
1056 &key_data_blob, cipher->allocator, sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + cipher_impl->overflow.len);
1057
1058 /* Now just export the key out as a raw AES key. */
1059 status = BCryptExportKey(
1060 import_key,
1061 NULL,
1062 BCRYPT_KEY_DATA_BLOB,
1063 key_data_blob.buffer,
1064 (ULONG)key_data_blob.capacity,
1065 &export_size,
1066 0);
1067
1068 key_data_blob.len += export_size;
1069
1070 if (BCRYPT_SUCCESS(status)) {
1071
1072 if (aws_symmetric_cipher_try_ensure_sufficient_buffer_space(out, export_size)) {
1073 goto clean_up;
1074 }
1075
1076 BCRYPT_KEY_DATA_BLOB_HEADER *stream_header = (BCRYPT_KEY_DATA_BLOB_HEADER *)key_data_blob.buffer;
1077
1078 AWS_FATAL_ASSERT(
1079 aws_byte_buf_write(
1080 out, key_data_blob.buffer + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER), stream_header->cbKeyData) &&
1081 "Copying key data failed but the allocation should have already occurred successfully");
1082 ret_val = AWS_OP_SUCCESS;
1083
1084 } else {
1085 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1086 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
1087 }
1088
1089 clean_up:
1090 aws_byte_buf_clean_up_secure(&key_data_blob);
1091 BCryptDestroyKey(import_key);
1092
1093 } else {
1094 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1095 cipher->state = AWS_SYMMETRIC_CIPHER_ERROR;
1096 }
1097
1098 return ret_val;
1099 }
1100
1101 static int s_reset_keywrap_cipher(struct aws_symmetric_cipher *cipher) {
1102 struct aes_bcrypt_cipher *cipher_impl = cipher->impl;
1103
1104 s_clear_reusable_components(cipher);
1105
1106 return s_initialize_cipher_materials(cipher_impl, NULL, NULL, NULL, 0, false, false);
1107 }
1108
1109 static struct aws_symmetric_cipher_vtable s_aes_keywrap_vtable = {
1110 .alg_name = "AES-KEYWRAP 256",
1111 .provider = "Windows CNG",
1112 .decrypt = s_key_wrap_encrypt_decrypt,
1113 .encrypt = s_key_wrap_encrypt_decrypt,
1114 .finalize_encryption = s_keywrap_finalize_encryption,
1115 .finalize_decryption = s_keywrap_finalize_decryption,
1116 .destroy = s_aes_default_destroy,
1117 .reset = s_reset_keywrap_cipher,
1118 };
1119
1120 struct aws_symmetric_cipher *aws_aes_keywrap_256_new_impl(
1121 struct aws_allocator *allocator,
1122 const struct aws_byte_cursor *key) {
1123
1124 aws_thread_call_once(&s_aes_thread_once, s_load_alg_handles, NULL);
1125 struct aes_bcrypt_cipher *cipher = aws_mem_calloc(allocator, 1, sizeof(struct aes_bcrypt_cipher));
1126
1127 cipher->cipher.allocator = allocator;
1128 cipher->cipher.block_size = 8;
1129 cipher->cipher.key_length_bits = AWS_AES_256_KEY_BIT_LEN;
1130 cipher->alg_handle = s_aes_keywrap_algorithm_handle;
1131 cipher->cipher.vtable = &s_aes_keywrap_vtable;
1132
1133 if (s_initialize_cipher_materials(cipher, key, NULL, NULL, 0, false, false) != AWS_OP_SUCCESS) {
1134 goto error;
1135 }
1136
1137 aws_byte_buf_init(&cipher->overflow, allocator, (AWS_AES_256_CIPHER_BLOCK_SIZE * 2) + 8);
1138
1139 cipher->cipher.impl = cipher;
1140 cipher->cipher.state = AWS_SYMMETRIC_CIPHER_READY;
1141
1142 return &cipher->cipher;
1143
1144 error:
1145 if (cipher != NULL) {
1146 s_aes_default_destroy(&cipher->cipher);
1147 }
1148
1149 return NULL;
1150 }