Debian Codegraph @

crt/aws-c-io/tests/pkcs11_test.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
6 /**
7 * See PKCS11.md for instructions on running these tests
8 */
9
10 #include <aws/io/pkcs11.h>
11
12 #include "../source/pkcs11_private.h"
13
14 #include <aws/common/clock.h>
15 #include <aws/common/condition_variable.h>
16 #include <aws/common/environment.h>
17 #include <aws/common/file.h>
18 #include <aws/common/mutex.h>
19 #include <aws/common/process.h>
20 #include <aws/common/string.h>
21 #include <aws/common/uuid.h>
22 #include <aws/io/channel_bootstrap.h>
23 #include <aws/io/event_loop.h>
24 #include <aws/io/logging.h>
25 #include <aws/io/socket.h>
26 #include <aws/io/tls_channel_handler.h>
27 #include <aws/testing/aws_test_harness.h>
28
29 #ifdef _MSC_VER
30 # pragma warning(disable : 4996) /* allow strncpy() */
31 #endif
32
33 AWS_STATIC_STRING_FROM_LITERAL(TEST_PKCS11_LIB, "TEST_PKCS11_LIB");
34 AWS_STATIC_STRING_FROM_LITERAL(TEST_PKCS11_TOKEN_DIR, "TEST_PKCS11_TOKEN_DIR");
35
36 /* Singleton that stores env-var values */
37 struct pkcs11_tester {
38 struct aws_allocator *allocator;
39 struct aws_string *shared_lib_path;
40 struct aws_string *token_dir;
41 struct aws_pkcs11_lib *lib;
42 };
43
44 static struct pkcs11_tester s_pkcs11_tester;
45 const char *TOKEN_LABEL = "my-token";
46 const char *TOKEN_LABEL_RSA = "my-rsa-token";
47 const char *TOKEN_LABEL_EC = "my-ec-token";
48 const char *SO_PIN = "1111";
49 const char *USER_PIN = "0000";
50 const char *DEFAULT_KEY_LABEL = "my-key";
51 const char *DEFAULT_KEY_ID = "AABBCCDD";
52
53 #define TIMEOUT_SEC 10
54 #define TIMEOUT_MILLIS (AWS_TIMESTAMP_MILLIS * TIMEOUT_SEC)
55 #define TIMEOUT_NANOS ((uint64_t)AWS_TIMESTAMP_NANOS * TIMEOUT_SEC)
56
57 struct pkcs11_key_creation_params {
58 const char *key_label;
59 const char *key_id;
60 const CK_ULONG key_length;
61 };
62
63 /* Wipe out all existing tokens by deleting and recreating the SoftHSM token dir */
64 static int s_pkcs11_clear_softhsm(void) {
65 ASSERT_SUCCESS(aws_directory_delete(s_pkcs11_tester.token_dir, true /*recursive*/));
66 ASSERT_SUCCESS(aws_directory_create(s_pkcs11_tester.token_dir));
67 return AWS_OP_SUCCESS;
68 }
69
70 static int s_reload_hsm(void) {
71
72 /* Finalize to make sure that softhsm reads new tokens afresh */
73 aws_pkcs11_lib_release(s_pkcs11_tester.lib);
74 s_pkcs11_tester.lib = NULL;
75
76 /* Load library again */
77 struct aws_pkcs11_lib_options options = {
78 .filename = aws_byte_cursor_from_string(s_pkcs11_tester.shared_lib_path),
79 .initialize_finalize_behavior = AWS_PKCS11_LIB_STRICT_INITIALIZE_FINALIZE,
80 };
81 s_pkcs11_tester.lib = aws_pkcs11_lib_new(s_pkcs11_tester.allocator, &options);
82 ASSERT_NOT_NULL(s_pkcs11_tester.lib, "Failed to load PKCS#11 lib");
83
84 return AWS_OP_SUCCESS;
85 }
86
87 static int s_pkcs11_clear_softhsm_and_reload(void) {
88
89 /* Finalize to make sure that softhsm reads new tokens afresh */
90 aws_pkcs11_lib_release(s_pkcs11_tester.lib);
91 s_pkcs11_tester.lib = NULL;
92
93 /* Clear token dir */
94 ASSERT_SUCCESS(s_pkcs11_clear_softhsm());
95
96 /* Load library again */
97 ASSERT_SUCCESS(s_reload_hsm());
98
99 return AWS_OP_SUCCESS;
100 }
101
102 /* Encryption/Decryption only applies to RSA, not ECC */
103 static int s_pkcs11_rsa_encrypt(
104 struct aws_byte_cursor *message,
105 struct aws_byte_buf *cipher_text,
106 CK_SESSION_HANDLE session,
107 CK_OBJECT_HANDLE public_key) {
108
109 CK_FUNCTION_LIST *pkcs11_function_list = aws_pkcs11_lib_get_function_list(s_pkcs11_tester.lib);
110 struct aws_allocator *allocator = s_pkcs11_tester.allocator;
111
112 CK_MECHANISM mechanism = {.mechanism = CKM_RSA_PKCS};
113 CK_RV rv = pkcs11_function_list->C_EncryptInit(session, &mechanism, public_key);
114 if (rv != CKR_OK) {
115 FAIL("C_EncryptInit fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
116 }
117
118 CK_ULONG cipher_len = 0;
119 rv = pkcs11_function_list->C_Encrypt(session, message->ptr, (CK_ULONG)message->len, NULL, &cipher_len);
120 if (rv != CKR_OK) {
121 FAIL("C_Encrypt fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
122 }
123
124 aws_byte_buf_init(cipher_text, allocator, cipher_len);
125 rv = pkcs11_function_list->C_Encrypt(
126 session, message->ptr, (CK_ULONG)message->len, cipher_text->buffer, &cipher_len);
127 if (rv != CKR_OK) {
128 FAIL("C_Encrypt fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
129 }
130 cipher_text->len = cipher_len;
131 return AWS_OP_SUCCESS;
132 }
133
134 static int s_pkcs11_verify_signature(
135 struct aws_byte_cursor *message,
136 struct aws_byte_buf *signature,
137 CK_SESSION_HANDLE session,
138 CK_OBJECT_HANDLE public_key,
139 CK_MECHANISM_TYPE mechanism_type) {
140
141 CK_FUNCTION_LIST *pkcs11_function_list = aws_pkcs11_lib_get_function_list(s_pkcs11_tester.lib);
142
143 CK_MECHANISM mechanism = {.mechanism = mechanism_type};
144 CK_RV rv = pkcs11_function_list->C_VerifyInit(session, &mechanism, public_key);
145 if (rv != CKR_OK) {
146 FAIL("C_VerifyInit fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
147 }
148
149 rv = pkcs11_function_list->C_Verify(
150 session, message->ptr, (CK_ULONG)message->len, signature->buffer, (CK_ULONG)signature->len);
151 if (rv != CKR_OK) {
152 FAIL("C_Verify fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
153 }
154 return AWS_OP_SUCCESS;
155 }
156
157 static int s_pkcs11_create_rsa_key(
158 struct pkcs11_key_creation_params *params,
159 CK_SESSION_HANDLE session,
160 CK_OBJECT_HANDLE *created_private_key,
161 CK_OBJECT_HANDLE *created_public_key) {
162
163 CK_FUNCTION_LIST *pkcs11_function_list = aws_pkcs11_lib_get_function_list(s_pkcs11_tester.lib);
164
165 /* We only support RSA keys today. */
166 CK_MECHANISM smech = {CKM_RSA_PKCS_KEY_PAIR_GEN, NULL, 0};
167 /* Define key template */
168 static CK_BBOOL truevalue = CK_TRUE;
169 static CK_BBOOL falsevalue = CK_FALSE;
170
171 /* Set public key. Not sure if setting modulus_bits actually generates key as per that. */
172 CK_ATTRIBUTE publickey_template[] = {
173 {CKA_VERIFY, &truevalue, sizeof(truevalue)},
174 {CKA_MODULUS_BITS, (CK_VOID_PTR)&params->key_length, sizeof(params->key_length)},
175 };
176
177 /* Set private key. The parameters here are kind of random, does not affect the test, but trying
178 * to mimic what a real key would look like in terms of attributes */
179 CK_ATTRIBUTE privatekey_template[] = {
180 {CKA_LABEL, (void *)params->key_label, (CK_ULONG)strlen(params->key_label)},
181 {CKA_ID, (void *)params->key_id, (CK_ULONG)strlen(params->key_id)},
182 {CKA_SIGN, &truevalue, sizeof(truevalue)},
183 {CKA_EXTRACTABLE, &falsevalue, sizeof(falsevalue)},
184 };
185 CK_OBJECT_HANDLE privatekey, publickey = CK_INVALID_HANDLE;
186 /* Generate Key pair for signing/verifying */
187 CK_RV rv = pkcs11_function_list->C_GenerateKeyPair(
188 session,
189 &smech,
190 publickey_template,
191 AWS_ARRAY_SIZE(publickey_template),
192 privatekey_template,
193 AWS_ARRAY_SIZE(privatekey_template),
194 &publickey,
195 &privatekey);
196 if (rv != CKR_OK) {
197 FAIL("C_GenerateKeyPair fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
198 }
199 *created_private_key = privatekey;
200 *created_public_key = publickey;
201 return AWS_OP_SUCCESS;
202 }
203
204 static int s_pkcs11_create_ec_key(
205 struct pkcs11_key_creation_params *params,
206 CK_SESSION_HANDLE session,
207 CK_OBJECT_HANDLE *created_private_key,
208 CK_OBJECT_HANDLE *created_public_key) {
209
210 CK_FUNCTION_LIST *pkcs11_function_list = aws_pkcs11_lib_get_function_list(s_pkcs11_tester.lib);
211
212 CK_MECHANISM smech = {CKM_EC_KEY_PAIR_GEN, NULL, 0};
213 /* Define key template */
214 static CK_BBOOL truevalue = CK_TRUE;
215 static CK_BBOOL falsevalue = CK_FALSE;
216 /* DER encoded params for curve P-256 */
217 static CK_BYTE ec_params[] = {0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07};
218
219 CK_ATTRIBUTE publickey_template[] = {
220 {CKA_EC_PARAMS, ec_params, sizeof(ec_params)},
221 {CKA_VERIFY, &truevalue, sizeof(truevalue)},
222 };
223
224 /* Set private key. The parameters here are kind of random, does not affect the test, but trying
225 * to mimic what a real key would look like in terms of attributes */
226 CK_ATTRIBUTE privatekey_template[] = {
227 {CKA_LABEL, (void *)params->key_label, (CK_ULONG)strlen(params->key_label)},
228 {CKA_ID, (void *)params->key_id, (CK_ULONG)strlen(params->key_id)},
229 {CKA_SIGN, &truevalue, sizeof(truevalue)},
230 {CKA_EXTRACTABLE, &falsevalue, sizeof(falsevalue)},
231 };
232 CK_OBJECT_HANDLE privatekey, publickey = CK_INVALID_HANDLE;
233 /* Generate Key pair for signing/verifying */
234 CK_RV rv = pkcs11_function_list->C_GenerateKeyPair(
235 session,
236 &smech,
237 publickey_template,
238 AWS_ARRAY_SIZE(publickey_template),
239 privatekey_template,
240 AWS_ARRAY_SIZE(privatekey_template),
241 &publickey,
242 &privatekey);
243 if (rv != CKR_OK) {
244 FAIL("C_GenerateKeyPair fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
245 }
246 *created_private_key = privatekey;
247 *created_public_key = publickey;
248 return AWS_OP_SUCCESS;
249 }
250
251 /* if tokenInfo is set, finds slot with matching token
252 * if tokenInfo is NULL, finds slot with uninitialized token */
253 static int s_pkcs11_find_slot(const CK_TOKEN_INFO *tokenInfo, CK_SLOT_ID *out_slot) {
254
255 CK_FUNCTION_LIST *pkcs11_function_list = aws_pkcs11_lib_get_function_list(s_pkcs11_tester.lib);
256 CK_ULONG ul_slot_count = 0;
257 CK_SLOT_ID slot_id = 0;
258 CK_RV rv = pkcs11_function_list->C_GetSlotList(CK_TRUE, NULL, &ul_slot_count);
259 if (rv != CKR_OK) {
260 FAIL("ERROR: Could not get the number of slots.");
261 }
262
263 CK_SLOT_ID_PTR p_slot_list = aws_mem_acquire(s_pkcs11_tester.allocator, ul_slot_count * sizeof(CK_SLOT_ID));
264 if (p_slot_list == NULL) {
265 FAIL("ERROR: Could not allocate memory.");
266 }
267
268 rv = pkcs11_function_list->C_GetSlotList(CK_FALSE, p_slot_list, &ul_slot_count);
269 if (rv != CKR_OK) {
270 FAIL("ERROR: Could not get the slot list.");
271 }
272
273 size_t counter = 0;
274 for (CK_ULONG i = 0; i < ul_slot_count; i++) {
275 CK_TOKEN_INFO curr_token_info;
276
277 rv = pkcs11_function_list->C_GetTokenInfo(p_slot_list[i], &curr_token_info);
278 if (rv != CKR_OK) {
279 FAIL("ERROR: Could not get info about the token in slot %lu.", p_slot_list[i]);
280 }
281
282 if (tokenInfo) {
283 if (memcmp(curr_token_info.serialNumber, tokenInfo->serialNumber, sizeof(tokenInfo->serialNumber)) == 0 &&
284 memcmp(curr_token_info.label, tokenInfo->label, sizeof(tokenInfo->label)) == 0) {
285
286 slot_id = p_slot_list[i];
287 counter++;
288 }
289 } else {
290 /* find slots with uninitialized token */
291 if ((curr_token_info.flags & CKF_TOKEN_INITIALIZED) == 0) {
292 slot_id = p_slot_list[i];
293 counter++;
294 }
295 }
296 }
297
298 aws_mem_release(s_pkcs11_tester.allocator, p_slot_list);
299
300 if (counter == 0) {
301 FAIL("ERROR: Could not find a slot/token using --serial, or --token");
302 } else if (counter > 1) {
303 FAIL("ERROR: Found multiple matching slots/tokens.");
304 }
305 /* We found just one matching slot */
306 *out_slot = slot_id;
307 return AWS_OP_SUCCESS;
308 }
309
310 static int s_pkcs11_find_free_slot(CK_SLOT_ID *out_slot) {
311
312 return s_pkcs11_find_slot(NULL, out_slot);
313 }
314
315 /* Creation of slot requires a reload of softhsm, and hence need to re initialize the pkcs11_lib */
316 static int s_pkcs11_softhsm_create_slot(
317 const char *token_name,
318 const char *so_pin,
319 const char *user_pin,
320 CK_SLOT_ID *created_slot) {
321
322 CK_FUNCTION_LIST *pkcs11_function_list = aws_pkcs11_lib_get_function_list(s_pkcs11_tester.lib);
323 CK_RV rv;
324
325 /* API expects ' ' padded string */
326 CK_UTF8CHAR paddedLabel[32];
327 memset(paddedLabel, ' ', sizeof(paddedLabel));
328 memcpy(paddedLabel, token_name, strlen(token_name));
329
330 CK_SLOT_ID slot_id = 0;
331 ASSERT_SUCCESS(s_pkcs11_find_free_slot(&slot_id));
332
333 rv = pkcs11_function_list->C_InitToken(slot_id, (CK_UTF8CHAR_PTR)so_pin, (CK_ULONG)strlen(so_pin), paddedLabel);
334 if (rv != CKR_OK) {
335 FAIL("C_InitToken fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
336 }
337 CK_SESSION_HANDLE session;
338 rv = pkcs11_function_list->C_OpenSession(slot_id, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL, NULL, &session);
339 if (rv != CKR_OK) {
340 FAIL("C_OpenSession fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
341 }
342
343 rv = pkcs11_function_list->C_Login(session, CKU_SO, (CK_UTF8CHAR_PTR)so_pin, (CK_ULONG)strlen(so_pin));
344 if (rv != CKR_OK) {
345 FAIL("C_Login fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
346 }
347
348 rv = pkcs11_function_list->C_InitPIN(session, (CK_UTF8CHAR_PTR)user_pin, (CK_ULONG)strlen(user_pin));
349 if (rv != CKR_OK) {
350 FAIL("C_InitPIN fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
351 }
352 CK_TOKEN_INFO tokenInfo;
353 rv = pkcs11_function_list->C_GetTokenInfo(slot_id, &tokenInfo);
354 if (rv != CKR_OK) {
355 FAIL("C_GetTokenInfo fails: PKCS#11 error: %s (0x%08lX)", aws_pkcs11_ckr_str(rv), rv);
356 }
357 /* Reload the library */
358 ASSERT_SUCCESS(s_reload_hsm());
359
360 CK_SLOT_ID new_slot_id = 0;
361 ASSERT_SUCCESS(s_pkcs11_find_slot(&tokenInfo, &new_slot_id));
362 if (slot_id == new_slot_id) {
363 printf("The token has been initialized on slot %lu\n", new_slot_id);
364 } else {
365 printf("The token has been initialized and is reassigned to slot %lu\n", new_slot_id);
366 }
367
368 *created_slot = new_slot_id;
369 return AWS_OP_SUCCESS;
370 }
371
372 /*
373 * Helper functions to interact with softhsm end
374 * */
375
376 /* Unload PKCS#11 lib
377 * Clear SoftHSM's token dir so that each test ends fresh */
378 static void s_pkcs11_tester_clean_up(void) {
379 aws_pkcs11_lib_release(s_pkcs11_tester.lib);
380 s_pkcs11_tester.lib = NULL;
381 s_pkcs11_clear_softhsm();
382 aws_string_destroy(s_pkcs11_tester.shared_lib_path);
383 aws_string_destroy(s_pkcs11_tester.token_dir);
384 AWS_ZERO_STRUCT(s_pkcs11_tester);
385 aws_io_library_clean_up();
386 }
387
388 /* Read env-vars, raise an error if any necessary ones are missing.
389 * Clear SoftHSM's token dir so that each test starts fresh.
390 * DO NOT load PKCS#11 lib. */
391 static int s_pkcs11_tester_init_without_load(struct aws_allocator *allocator) {
392 aws_io_library_init(allocator);
393
394 const struct aws_string *env_var = TEST_PKCS11_LIB;
395 aws_get_environment_value(allocator, env_var, &s_pkcs11_tester.shared_lib_path);
396 if (s_pkcs11_tester.shared_lib_path == NULL) {
397 FAIL("Missing required env-var '%s'\n", aws_string_c_str(env_var));
398 }
399
400 env_var = TEST_PKCS11_TOKEN_DIR;
401 aws_get_environment_value(allocator, env_var, &s_pkcs11_tester.token_dir);
402 if (s_pkcs11_tester.token_dir == NULL) {
403 FAIL("Missing required env-var '%s'\n", aws_string_c_str(env_var));
404 }
405
406 s_pkcs11_tester.allocator = allocator;
407
408 ASSERT_SUCCESS(s_pkcs11_clear_softhsm());
409
410 return AWS_OP_SUCCESS;
411 }
412
413 /* Read env-vars, raise an error if any necessary ones are missing.
414 * Clear SoftHSM's token dir so that each test starts fresh.
415 * Load PKCS#11 lib. */
416 static int s_pkcs11_tester_init(struct aws_allocator *allocator) {
417 ASSERT_SUCCESS(s_pkcs11_tester_init_without_load(allocator));
418
419 struct aws_pkcs11_lib_options options = {
420 .filename = aws_byte_cursor_from_string(s_pkcs11_tester.shared_lib_path),
421 .initialize_finalize_behavior = AWS_PKCS11_LIB_STRICT_INITIALIZE_FINALIZE,
422 };
423 s_pkcs11_tester.lib = aws_pkcs11_lib_new(s_pkcs11_tester.allocator, &options);
424 ASSERT_NOT_NULL(s_pkcs11_tester.lib, "Failed to load PKCS#11 lib");
425
426 return AWS_OP_SUCCESS;
427 }
428
429 static int s_pkcs11_tester_init_with_session_login(
430 struct aws_allocator *allocator,
431 const char *token_label,
432 CK_SLOT_ID *created_slot,
433 CK_SESSION_HANDLE *session) {
434
435 /* Reset tokens and load library */
436 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
437
438 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
439 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(token_label, SO_PIN, USER_PIN, created_slot));
440
441 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, *created_slot, session /*out*/));
442
443 /* Login user */
444 struct aws_string *user_pin = aws_string_new_from_c_str(allocator, USER_PIN);
445 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, *session, user_pin));
446 aws_string_destroy(user_pin);
447
448 return AWS_OP_SUCCESS;
449 }
450
451 /* Simplest test: Loads and unloads library, calling C_Initialize() and C_Finalize() */
452 static int s_test_pkcs11_lib_sanity_check(struct aws_allocator *allocator, void *ctx) {
453 (void)ctx;
454 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
455 s_pkcs11_tester_clean_up();
456 return AWS_OP_SUCCESS;
457 }
458 AWS_TEST_CASE(pkcs11_lib_sanity_check, s_test_pkcs11_lib_sanity_check)
459
460 /* Stress test the DEFAULT_BEHAVIOR for C_Initialize() / C_Finalize() calls */
461 static int s_test_pkcs11_lib_behavior_default(struct aws_allocator *allocator, void *ctx) {
462 (void)ctx;
463 ASSERT_SUCCESS(s_pkcs11_tester_init_without_load(allocator));
464
465 struct aws_pkcs11_lib_options options_default_behavior = {
466 .filename = aws_byte_cursor_from_string(s_pkcs11_tester.shared_lib_path),
467 .initialize_finalize_behavior = AWS_PKCS11_LIB_DEFAULT_BEHAVIOR,
468 };
469 struct aws_pkcs11_lib *lib_1 = aws_pkcs11_lib_new(allocator, &options_default_behavior);
470 ASSERT_NOT_NULL(lib_1, "Failed to load PKCS#11 lib");
471
472 /* Loading the lib a 2nd time with DEFAULT_BEHAVIOR should be fine,
473 * since CKR_CRYPTOKI_ALREADY_INITIALIZED should be ignored. */
474 struct aws_pkcs11_lib *lib_2 = aws_pkcs11_lib_new(allocator, &options_default_behavior);
475 ASSERT_NOT_NULL(lib_2, "Failed to load a 2nd PKCS#11 lib");
476
477 /* lib_2 should keep working if lib_1 is freed, since C_Finalize() is not called with DEFAULT_BEHAVIOR.
478 * (call C_GetInfo() to confirm the lib_2 still works) */
479 aws_pkcs11_lib_release(lib_1);
480 lib_1 = NULL;
481
482 CK_INFO info;
483 ASSERT_INT_EQUALS(CKR_OK, aws_pkcs11_lib_get_function_list(lib_2)->C_GetInfo(&info));
484
485 /* If all libs are unloaded, and another comes online. That should be fine */
486 aws_pkcs11_lib_release(lib_2);
487 lib_2 = NULL;
488
489 struct aws_pkcs11_lib *lib_3 = aws_pkcs11_lib_new(allocator, &options_default_behavior);
490 ASSERT_NOT_NULL(lib_3, "Failed to load a 3rd PKCS#11 lib");
491
492 /* Clean up */
493 aws_pkcs11_lib_release(lib_3);
494 s_pkcs11_tester_clean_up();
495 return AWS_OP_SUCCESS;
496 }
497 AWS_TEST_CASE(pkcs11_lib_behavior_default, s_test_pkcs11_lib_behavior_default)
498
499 /* Stress test the OMIT_INITIALIZE behavior, where neither C_Initialize() or C_Finalize() is called */
500 static int s_test_pkcs11_lib_behavior_omit_initialize(struct aws_allocator *allocator, void *ctx) {
501 (void)ctx;
502 ASSERT_SUCCESS(s_pkcs11_tester_init_without_load(allocator));
503
504 struct aws_pkcs11_lib_options options_omit_initialize = {
505 .filename = aws_byte_cursor_from_string(s_pkcs11_tester.shared_lib_path),
506 .initialize_finalize_behavior = AWS_PKCS11_LIB_OMIT_INITIALIZE,
507 };
508
509 /* Test that we fail gracefully if OMIT_INITIALIZE behavior is used,
510 * but no one else has initialized the underlying PKCS#11 library */
511 struct aws_pkcs11_lib *pkcs11_lib_should_fail = aws_pkcs11_lib_new(allocator, &options_omit_initialize);
512 ASSERT_NULL(pkcs11_lib_should_fail);
513 ASSERT_INT_EQUALS(AWS_ERROR_PKCS11_CKR_CRYPTOKI_NOT_INITIALIZED, aws_last_error());
514
515 /* Test that it's fine to use OMIT_INITIALIZE behavior to have the library loaded multiple times. */
516
517 /* First create a lib that DOES call C_Initialize() */
518 struct aws_pkcs11_lib_options options_initialize_finalize = {
519 .filename = aws_byte_cursor_from_string(s_pkcs11_tester.shared_lib_path),
520 .initialize_finalize_behavior = AWS_PKCS11_LIB_STRICT_INITIALIZE_FINALIZE,
521 };
522 struct aws_pkcs11_lib *lib_initialize_finalize = aws_pkcs11_lib_new(allocator, &options_initialize_finalize);
523 ASSERT_NOT_NULL(lib_initialize_finalize);
524
525 /* Now test that it's fine to create a 2nd lib using OMIT_INITIALIZE */
526 struct aws_pkcs11_lib *lib_2 = aws_pkcs11_lib_new(allocator, &options_omit_initialize);
527 ASSERT_NOT_NULL(lib_2);
528
529 /* Clean up */
530 aws_pkcs11_lib_release(lib_2);
531 aws_pkcs11_lib_release(lib_initialize_finalize);
532 s_pkcs11_tester_clean_up();
533 return AWS_OP_SUCCESS;
534 }
535 AWS_TEST_CASE(pkcs11_lib_behavior_omit_initialize, s_test_pkcs11_lib_behavior_omit_initialize)
536
537 /* Stress test the STRICT_INITIALIZE_FINALIZE behavior */
538 static int s_test_pkcs11_lib_behavior_strict_initialize_finalize(struct aws_allocator *allocator, void *ctx) {
539 (void)ctx;
540 ASSERT_SUCCESS(s_pkcs11_tester_init_without_load(allocator));
541
542 /* Creating the 1st lib should succeed */
543 struct aws_pkcs11_lib_options options_initialize_finalize = {
544 .filename = aws_byte_cursor_from_string(s_pkcs11_tester.shared_lib_path),
545 .initialize_finalize_behavior = AWS_PKCS11_LIB_STRICT_INITIALIZE_FINALIZE,
546 };
547 struct aws_pkcs11_lib *lib_1 = aws_pkcs11_lib_new(allocator, &options_initialize_finalize);
548 ASSERT_NOT_NULL(lib_1);
549
550 /* Creating the 2nd lib should fail due to already-initialized errors */
551 struct aws_pkcs11_lib *lib_2_should_fail = aws_pkcs11_lib_new(allocator, &options_initialize_finalize);
552 ASSERT_NULL(lib_2_should_fail);
553 ASSERT_INT_EQUALS(AWS_ERROR_PKCS11_CKR_CRYPTOKI_ALREADY_INITIALIZED, aws_last_error());
554
555 /* It should be safe to release a STRICT lib, then create another */
556 aws_pkcs11_lib_release(lib_1);
557 lib_1 = NULL;
558
559 struct aws_pkcs11_lib *lib_2_should_succeed = aws_pkcs11_lib_new(allocator, &options_initialize_finalize);
560 ASSERT_NOT_NULL(lib_2_should_succeed);
561
562 /* Clean up */
563 aws_pkcs11_lib_release(lib_2_should_succeed);
564 s_pkcs11_tester_clean_up();
565 return AWS_OP_SUCCESS;
566 }
567 AWS_TEST_CASE(pkcs11_lib_behavior_strict_initialize_finalize, s_test_pkcs11_lib_behavior_strict_initialize_finalize)
568
569 static int s_test_pkcs11_session_tests(struct aws_allocator *allocator, void *ctx) {
570 (void)ctx;
571 /* Reset PKCS#11 tokens and load library */
572 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
573
574 /* Assert that creating a session for an invalid slot fails.
575 *
576 * NOTE: We omit this part of the test when AddressSanitizer is being used,
577 * because SoftHSM v2.2 triggers it in this scenario. I've tried using a
578 * suppression file to ignore the issue, but the suppression isn't
579 * working and I still don't understand why after 1+ hours of effort.
580 * But this ifdef does the trick so that's what I'm doing. */
581 #if defined(__has_feature)
582 # if __has_feature(address_sanitizer)
583 # define ADDRESS_SANITIZER_ENABLED 1
584 # endif
585 #endif
586 #if !ADDRESS_SANITIZER_ENABLED
587 CK_SESSION_HANDLE session = CK_INVALID_HANDLE;
588 /* we haven't created any slots and we are starting from a clean softhsm, so any slot value is invalid. */
589 CK_SLOT_ID slot = 1;
590 ASSERT_FAILS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, slot, &session /*out*/));
591 #endif
592
593 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
594 CK_SLOT_ID created_slot = 0;
595 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(TOKEN_LABEL, SO_PIN, USER_PIN, &created_slot));
596
597 CK_SESSION_HANDLE first_session = CK_INVALID_HANDLE;
598 CK_SESSION_HANDLE second_session = CK_INVALID_HANDLE;
599 /* Now, creation of a session on a valid slot will be a success */
600 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &first_session /*out*/));
601 ASSERT_TRUE(first_session != CK_INVALID_HANDLE);
602
603 /* create one more session */
604 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &second_session /*out*/));
605 ASSERT_TRUE(second_session != CK_INVALID_HANDLE);
606 ASSERT_TRUE(first_session != second_session);
607
608 /* Close both sessions */
609 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, first_session);
610 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, second_session);
611
612 /* Clean up */
613 s_pkcs11_tester_clean_up();
614 return AWS_OP_SUCCESS;
615 }
616 AWS_TEST_CASE(pkcs11_session_tests, s_test_pkcs11_session_tests)
617
618 static int s_test_pkcs11_login_tests(struct aws_allocator *allocator, void *ctx) {
619 (void)ctx;
620 /* Reset PKCS#11 tokens and load library */
621 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
622
623 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
624 CK_SLOT_ID created_slot = 0;
625 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(TOKEN_LABEL, SO_PIN, USER_PIN, &created_slot));
626
627 /* Try to login with in invalid session, we have not created any session on this token
628 * So, any session value is invalid */
629 struct aws_string *pin = aws_string_new_from_c_str(allocator, USER_PIN);
630 CK_SESSION_HANDLE invalid_session = 1UL;
631 ASSERT_FAILS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, invalid_session, pin));
632
633 /* Now create a valid session */
634 CK_SESSION_HANDLE session = CK_INVALID_HANDLE;
635 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session /*out*/));
636
637 /* Try an invalid pin on a valid slot */
638 struct aws_string *invalid_pin = aws_string_new_from_c_str(allocator, "INVALID_PIN");
639 ASSERT_FAILS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session, invalid_pin));
640
641 /* Try a valid pin on a valid slot */
642 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session, pin));
643
644 /* A re login should succeed, as we are already logged in now */
645 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session, pin));
646
647 /* Now create one more session */
648 CK_SESSION_HANDLE session_2 = CK_INVALID_HANDLE;
649 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_2 /*out*/));
650
651 /* A re login should succeed, as we are already logged in another session and
652 * the spec only requires login once on any of the session in an application
653 * */
654 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session_2, pin));
655
656 /* Close the first session */
657 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session);
658
659 /* A re login should succeed again on the second session, as login is only required once */
660 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session_2, pin));
661
662 /* Close the second session */
663 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session_2);
664
665 /* Clean up */
666 aws_string_destroy(pin);
667 aws_string_destroy(invalid_pin);
668 s_pkcs11_tester_clean_up();
669 return AWS_OP_SUCCESS;
670 }
671 AWS_TEST_CASE(pkcs11_login_tests, s_test_pkcs11_login_tests)
672
673 static int s_test_pkcs11_find_private_key_for_different_rsa_types(struct aws_allocator *allocator, void *ctx) {
674 (void)ctx;
675 /* Reset PKCS#11 tokens and load library */
676 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
677
678 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
679 CK_SLOT_ID created_slot = 0;
680 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(TOKEN_LABEL_RSA, SO_PIN, USER_PIN, &created_slot));
681
682 /* Do not close the session while running a test, objects created by a session are cleaned up
683 * when the session is closed.
684 * http://docs.oasis-open.org/pkcs11/pkcs11-ug/v2.40/cn02/pkcs11-ug-v2.40-cn02.html#_Toc386027485
685 * */
686 /* Open a different session to access the created key, and a different one to create */
687 CK_SESSION_HANDLE session_to_access_key;
688 CK_SESSION_HANDLE session_to_create_key;
689 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_access_key /*out*/));
690 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_create_key /*out*/));
691
692 /* Login user */
693 struct aws_string *user_pin = aws_string_new_from_c_str(allocator, USER_PIN);
694 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session_to_access_key, user_pin));
695
696 CK_OBJECT_HANDLE created_priv_key = CK_INVALID_HANDLE;
697 CK_OBJECT_HANDLE created_pub_key = CK_INVALID_HANDLE;
698 char *key_label_1024 = "1024_Key";
699 char *key_id_1024 = "1024_id";
700 struct pkcs11_key_creation_params params_1024 = {
701 .key_label = key_label_1024, .key_id = key_id_1024, .key_length = 1024};
702 ASSERT_SUCCESS(s_pkcs11_create_rsa_key(&params_1024, session_to_create_key, &created_priv_key, &created_pub_key));
703
704 /* Find key */
705 CK_OBJECT_HANDLE pkey_handle = CK_INVALID_HANDLE;
706 CK_KEY_TYPE pkey_type;
707 struct aws_string *key_label_str = aws_string_new_from_c_str(allocator, key_label_1024);
708 ASSERT_SUCCESS(aws_pkcs11_lib_find_private_key(
709 s_pkcs11_tester.lib, session_to_access_key, key_label_str, &pkey_handle, &pkey_type));
710 ASSERT_INT_EQUALS(created_priv_key, pkey_handle);
711 ASSERT_INT_EQUALS(CKK_RSA, pkey_type);
712
713 /* Create another RSA key */
714 CK_OBJECT_HANDLE created_key_2048 = CK_INVALID_HANDLE;
715 char *key_label_2048 = "2048_Key";
716 char *key_id_2048 = "2048_id";
717 struct pkcs11_key_creation_params params_2048 = {
718 .key_label = key_label_2048, .key_id = key_id_2048, .key_length = 2048};
719 ASSERT_SUCCESS(s_pkcs11_create_rsa_key(&params_2048, session_to_create_key, &created_key_2048, &created_pub_key));
720
721 /* Find key */
722 struct aws_string *key_label_str_2048 = aws_string_new_from_c_str(allocator, key_label_2048);
723 ASSERT_SUCCESS(aws_pkcs11_lib_find_private_key(
724 s_pkcs11_tester.lib, session_to_access_key, key_label_str_2048, &pkey_handle, &pkey_type));
725 ASSERT_INT_EQUALS(created_key_2048, pkey_handle);
726 ASSERT_INT_EQUALS(CKK_RSA, pkey_type);
727
728 /* Create another RSA key */
729 CK_OBJECT_HANDLE created_key_4096 = CK_INVALID_HANDLE;
730 char *key_label_4096 = "4096_Key";
731 char *key_id_4096 = "4096_id";
732 struct pkcs11_key_creation_params params_4096 = {
733 .key_label = key_label_4096, .key_id = key_id_4096, .key_length = 4096};
734 ASSERT_SUCCESS(s_pkcs11_create_rsa_key(&params_4096, session_to_create_key, &created_key_4096, &created_pub_key));
735
736 /* Find key */
737 struct aws_string *key_label_str_4096 = aws_string_new_from_c_str(allocator, key_label_4096);
738 ASSERT_SUCCESS(aws_pkcs11_lib_find_private_key(
739 s_pkcs11_tester.lib, session_to_access_key, key_label_str_4096, &pkey_handle, &pkey_type));
740 ASSERT_INT_EQUALS(created_key_4096, pkey_handle);
741 ASSERT_INT_EQUALS(CKK_RSA, pkey_type);
742
743 /* Clean up */
744 aws_string_destroy(user_pin);
745 aws_string_destroy(key_label_str);
746 aws_string_destroy(key_label_str_2048);
747 aws_string_destroy(key_label_str_4096);
748 s_pkcs11_tester_clean_up();
749 return AWS_OP_SUCCESS;
750 }
751 AWS_TEST_CASE(pkcs11_find_private_key_for_different_rsa_types, s_test_pkcs11_find_private_key_for_different_rsa_types)
752
753 static int s_test_pkcs11_find_private_key_for_ec(struct aws_allocator *allocator, void *ctx) {
754 (void)ctx;
755 /* Reset PKCS#11 tokens and load library */
756 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
757
758 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
759 CK_SLOT_ID created_slot = 0;
760 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(TOKEN_LABEL, SO_PIN, USER_PIN, &created_slot));
761
762 /* Do not close the session while running a test, objects created by a session are cleaned up
763 * when the session is closed.
764 * http://docs.oasis-open.org/pkcs11/pkcs11-ug/v2.40/cn02/pkcs11-ug-v2.40-cn02.html#_Toc386027485
765 * */
766 /* Open a different session to access the created key, and a different one to create */
767 CK_SESSION_HANDLE session_to_access_key;
768 CK_SESSION_HANDLE session_to_create_key;
769 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_access_key /*out*/));
770 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_create_key /*out*/));
771
772 /* Login user */
773 struct aws_string *user_pin = aws_string_new_from_c_str(allocator, USER_PIN);
774 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session_to_access_key, user_pin));
775
776 /* Create an EC key */
777 CK_OBJECT_HANDLE created_pub_key = CK_INVALID_HANDLE;
778 CK_OBJECT_HANDLE created_key_ec_256 = CK_INVALID_HANDLE;
779 char *key_label_ec_256 = "EC_256_Key";
780 char *key_id_ec_256 = "EC_256_id";
781 struct pkcs11_key_creation_params params_ec_256 = {.key_label = key_label_ec_256, .key_id = key_id_ec_256};
782 ASSERT_SUCCESS(
783 s_pkcs11_create_ec_key(&params_ec_256, session_to_create_key, &created_key_ec_256, &created_pub_key));
784
785 /* Find key */
786 CK_OBJECT_HANDLE pkey_handle = CK_INVALID_HANDLE;
787 CK_KEY_TYPE pkey_type;
788 struct aws_string *key_label_str_ec_256 = aws_string_new_from_c_str(allocator, key_label_ec_256);
789 ASSERT_SUCCESS(aws_pkcs11_lib_find_private_key(
790 s_pkcs11_tester.lib, session_to_access_key, key_label_str_ec_256, &pkey_handle, &pkey_type));
791 ASSERT_INT_EQUALS(created_key_ec_256, pkey_handle);
792 ASSERT_INT_EQUALS(CKK_EC, pkey_type);
793
794 /* Clean up */
795 aws_string_destroy(user_pin);
796 aws_string_destroy(key_label_str_ec_256);
797 s_pkcs11_tester_clean_up();
798 return AWS_OP_SUCCESS;
799 }
800 AWS_TEST_CASE(pkcs11_find_private_key_for_ec, s_test_pkcs11_find_private_key_for_ec)
801
802 static int s_test_pkcs11_find_multiple_private_key(struct aws_allocator *allocator, void *ctx) {
803 (void)ctx;
804 /* Reset PKCS#11 tokens and load library */
805 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
806
807 const char *key_label_1 = "RSA_KEY";
808 const char *key_id_1 = "BEEFCAFE";
809 const char *key_label_2 = "DES_KEY_2";
810 const char *key_id_2 = "BEEFCAFEDEAD";
811
812 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
813 CK_SLOT_ID created_slot = 0;
814 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(TOKEN_LABEL, SO_PIN, USER_PIN, &created_slot));
815
816 CK_SESSION_HANDLE session_to_access_key;
817 CK_SESSION_HANDLE session_to_create_key_1;
818 CK_SESSION_HANDLE session_to_create_key_2;
819
820 /* Open a session to access the created key */
821 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_access_key /*out*/));
822 /* Open sessions to create keys, 1 session is probably enough, but test creation with multiple sessions */
823 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_create_key_1 /*out*/));
824 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_create_key_2 /*out*/));
825
826 /* Login user */
827 struct aws_string *user_pin = aws_string_new_from_c_str(allocator, USER_PIN);
828 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session_to_access_key, user_pin));
829
830 CK_OBJECT_HANDLE created_key_1 = CK_INVALID_HANDLE;
831 CK_OBJECT_HANDLE created_key_2 = CK_INVALID_HANDLE;
832 CK_OBJECT_HANDLE created_pub_key = CK_INVALID_HANDLE;
833 struct pkcs11_key_creation_params params_1 = {.key_label = key_label_1, .key_id = key_id_1, .key_length = 1024};
834 struct pkcs11_key_creation_params params_2 = {.key_label = key_label_2, .key_id = key_id_2, .key_length = 1024};
835 ASSERT_SUCCESS(s_pkcs11_create_rsa_key(&params_1, session_to_create_key_1, &created_key_1, &created_pub_key));
836 ASSERT_SUCCESS(s_pkcs11_create_rsa_key(&params_2, session_to_create_key_2, &created_key_2, &created_pub_key));
837
838 /* Since there are 2 keys, a lookup without label should fail */
839 struct aws_string *key_label_str = aws_string_new_from_c_str(allocator, key_label_1);
840 struct aws_string *key_label_2_str = aws_string_new_from_c_str(allocator, key_label_2);
841 CK_OBJECT_HANDLE pkey_handle = CK_INVALID_HANDLE;
842 CK_KEY_TYPE pkey_type;
843 ASSERT_FAILS(
844 aws_pkcs11_lib_find_private_key(s_pkcs11_tester.lib, session_to_access_key, NULL, &pkey_handle, &pkey_type));
845
846 /* a lookup with label for the first key should find the first key */
847 pkey_handle = CK_INVALID_HANDLE;
848 ASSERT_SUCCESS(aws_pkcs11_lib_find_private_key(
849 s_pkcs11_tester.lib, session_to_access_key, key_label_str, &pkey_handle, &pkey_type));
850 ASSERT_INT_EQUALS(created_key_1, pkey_handle);
851 ASSERT_INT_EQUALS(CKK_RSA, pkey_type);
852
853 /* a lookup with label for the second key should find the second key */
854 pkey_handle = CK_INVALID_HANDLE;
855 ASSERT_SUCCESS(aws_pkcs11_lib_find_private_key(
856 s_pkcs11_tester.lib, session_to_access_key, key_label_2_str, &pkey_handle, &pkey_type));
857 ASSERT_INT_EQUALS(created_key_2, pkey_handle);
858 ASSERT_INT_EQUALS(CKK_RSA, pkey_type);
859
860 /* Clean up */
861 aws_string_destroy(key_label_str);
862 aws_string_destroy(key_label_2_str);
863 aws_string_destroy(user_pin);
864 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session_to_access_key);
865 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session_to_create_key_1);
866 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session_to_create_key_2);
867 s_pkcs11_tester_clean_up();
868 return AWS_OP_SUCCESS;
869 }
870 AWS_TEST_CASE(pkcs11_find_multiple_private_key, s_test_pkcs11_find_multiple_private_key)
871
872 static int s_test_pkcs11_find_private_key(struct aws_allocator *allocator, void *ctx) {
873 (void)ctx;
874 /* Reset PKCS#11 tokens and load library */
875 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
876
877 const char *key_label_1 = "RSA_KEY";
878 const char *key_id_1 = "BEEFCAFE";
879 const char *label_1 = "label!@#$%^&*-_=+{}[]<>?,./():_1";
880 const char *so_pin_1 = "qwertyuioplaksjdhfgbn341269504732";
881 const char *user_pin_1 = "341269504732";
882
883 /* Create a new slot, Use values other than defaults for label/pins */
884 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
885 CK_SLOT_ID created_slot = 0;
886 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(label_1, so_pin_1, user_pin_1, &created_slot));
887
888 /* Do not close the session while running a test, objects created by a session are cleaned up
889 * when the session is closed.
890 * http://docs.oasis-open.org/pkcs11/pkcs11-ug/v2.40/cn02/pkcs11-ug-v2.40-cn02.html#_Toc386027485
891 * */
892 /* Open a different session to access the created key, and a different one to create */
893 CK_SESSION_HANDLE session_to_access_key;
894 CK_SESSION_HANDLE session_to_create_key;
895 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_access_key /*out*/));
896 ASSERT_SUCCESS(aws_pkcs11_lib_open_session(s_pkcs11_tester.lib, created_slot, &session_to_create_key /*out*/));
897
898 /* Login user */
899 struct aws_string *user_pin = aws_string_new_from_c_str(allocator, user_pin_1);
900 ASSERT_SUCCESS(aws_pkcs11_lib_login_user(s_pkcs11_tester.lib, session_to_access_key, user_pin));
901
902 CK_OBJECT_HANDLE created_key = CK_INVALID_HANDLE;
903 CK_OBJECT_HANDLE created_pub_key = CK_INVALID_HANDLE;
904 struct pkcs11_key_creation_params params = {.key_label = key_label_1, .key_id = key_id_1, .key_length = 1024};
905 ASSERT_SUCCESS(s_pkcs11_create_rsa_key(&params, session_to_create_key, &created_key, &created_pub_key));
906
907 /* Find key */
908 CK_OBJECT_HANDLE pkey_handle = CK_INVALID_HANDLE;
909 CK_KEY_TYPE pkey_type;
910 struct aws_string *key_label_str = aws_string_new_from_c_str(allocator, key_label_1);
911 ASSERT_SUCCESS(aws_pkcs11_lib_find_private_key(
912 s_pkcs11_tester.lib, session_to_access_key, key_label_str, &pkey_handle, &pkey_type));
913 ASSERT_TRUE(CK_INVALID_HANDLE != pkey_handle);
914 ASSERT_INT_EQUALS(created_key, pkey_handle);
915 ASSERT_INT_EQUALS(CKK_RSA, pkey_type);
916
917 /* Since there is only one key, a lookup without label should also return the key */
918 pkey_handle = CK_INVALID_HANDLE;
919 ASSERT_SUCCESS(
920 aws_pkcs11_lib_find_private_key(s_pkcs11_tester.lib, session_to_access_key, NULL, &pkey_handle, &pkey_type));
921 ASSERT_INT_EQUALS(created_key, pkey_handle);
922 ASSERT_INT_EQUALS(CKK_RSA, pkey_type);
923
924 /* Clean up */
925 aws_string_destroy(key_label_str);
926 aws_string_destroy(user_pin);
927 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session_to_access_key);
928 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session_to_create_key);
929 s_pkcs11_tester_clean_up();
930 return AWS_OP_SUCCESS;
931 }
932 AWS_TEST_CASE(pkcs11_find_private_key, s_test_pkcs11_find_private_key)
933
934 static int s_test_pkcs11_find_slot(struct aws_allocator *allocator, void *ctx) {
935 (void)ctx;
936 /* Reset PKCS#11 tokens and load library */
937 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
938
939 /* softhsm does not like ;| as part of label */
940 const char *const label = "label!@#$%^&*-_=+{}[]<>?,./():_1";
941
942 const char *const so_pin = "qwertyuioplaksjdhfgbn341269504732";
943 const char *const user_pin = "341269504732";
944
945 CK_SLOT_ID slot_id = 0;
946 /*
947 * Softhsm always has one uninitialized token which is returned by the GetSlotList() API,
948 * so there is no way to start without any slot at all
949 * */
950
951 /* Call aws_pkcs11_lib_find_slot_with_token with 1 token, but no matching criteria */
952 ASSERT_SUCCESS(
953 aws_pkcs11_lib_find_slot_with_token(s_pkcs11_tester.lib, NULL /*match_slot_id*/, NULL, &slot_id /*out*/));
954
955 /* Create a new slot, this reloads the softhsm library but the labels/slots remain intact */
956 CK_SLOT_ID created_slot = 0;
957 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(label, so_pin, user_pin, &created_slot));
958
959 /* Call aws_pkcs11_lib_find_slot_with_token with 2 tokens, but no matching criteria */
960 slot_id = (CK_SLOT_ID)-1;
961 ASSERT_FAILS(
962 aws_pkcs11_lib_find_slot_with_token(s_pkcs11_tester.lib, NULL /*match_slot_id*/, NULL, &slot_id /*out*/));
963 ASSERT_INT_EQUALS((CK_SLOT_ID)-1, slot_id);
964
965 /* Call aws_pkcs11_lib_find_slot_with_token with 2 tokens, but match the slot this time */
966 uint64_t match_slot_id = created_slot;
967 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(s_pkcs11_tester.lib, &match_slot_id, NULL, &slot_id /*out*/));
968 ASSERT_INT_EQUALS(created_slot, slot_id);
969
970 /* Call aws_pkcs11_lib_find_slot_with_token with 2 tokens, but match the label this time */
971 slot_id = 0;
972 struct aws_string *match_label = aws_string_new_from_c_str(allocator, label);
973 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(
974 s_pkcs11_tester.lib, NULL /*match_slot_id*/, match_label, &slot_id /*out*/));
975 ASSERT_INT_EQUALS(created_slot, slot_id);
976
977 /* clear softhsm and make sure that no tokens match with previous slot/label */
978 ASSERT_SUCCESS(s_pkcs11_clear_softhsm_and_reload());
979
980 /*
981 * Call aws_pkcs11_lib_find_slot_with_token with just the uninitialized token,
982 * and assert that previous label does not match anymore
983 * */
984 slot_id = (CK_SLOT_ID)-1;
985 ASSERT_FAILS(aws_pkcs11_lib_find_slot_with_token(
986 s_pkcs11_tester.lib, NULL /*match_slot_id*/, match_label /*match_token_label*/, &slot_id /*out*/));
987 ASSERT_INT_EQUALS((CK_SLOT_ID)-1, slot_id);
988
989 /* Clean up */
990 aws_string_destroy(match_label);
991 s_pkcs11_tester_clean_up();
992 return AWS_OP_SUCCESS;
993 }
994 AWS_TEST_CASE(pkcs11_find_slot, s_test_pkcs11_find_slot)
995
996 static int s_test_pkcs11_find_slot_many_tokens(struct aws_allocator *allocator, void *ctx) {
997 (void)ctx;
998 /* Reset PKCS#11 tokens and load library */
999 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
1000
1001 const char *const label_1 = "label_1";
1002 const char *const label_2 = "label_2";
1003
1004 const char *const so_pin_1 = "ABCD";
1005 const char *const so_pin_2 = "0111";
1006
1007 const char *const user_pin_1 = "ABCD";
1008 const char *const user_pin_2 = "0111";
1009
1010 /* Create 2 new slots.
1011 * WARNING: SoftHSM may change ALL the slot_ids whenever a new token is added, and the library is reloaded */
1012 CK_SLOT_ID slot_id = (CK_SLOT_ID)-1;
1013 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(label_1, so_pin_1, user_pin_1, &slot_id));
1014 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(label_2, so_pin_2, user_pin_2, &slot_id));
1015
1016 /* Call aws_pkcs11_lib_find_slot_with_token with 3 tokens, match the label 1 this time */
1017 struct aws_string *match_label_1 = aws_string_new_from_c_str(allocator, label_1);
1018 CK_SLOT_ID created_slot_1 = (CK_SLOT_ID)-1;
1019 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(
1020 s_pkcs11_tester.lib, NULL /*match_slot_id*/, match_label_1 /*match_token_label*/, &created_slot_1 /*out*/));
1021
1022 /* Call aws_pkcs11_lib_find_slot_with_token with 3 tokens, match the label 2 this time */
1023 struct aws_string *match_label_2 = aws_string_new_from_c_str(allocator, label_2);
1024 CK_SLOT_ID created_slot_2 = (CK_SLOT_ID)-1;
1025 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(
1026 s_pkcs11_tester.lib, NULL /*match_slot_id*/, match_label_2 /*match_token_label*/, &created_slot_2 /*out*/));
1027 ASSERT_TRUE(created_slot_2 != created_slot_1);
1028
1029 /* Call aws_pkcs11_lib_find_slot_with_token with 3 tokens on softhsm, but no matching criteria */
1030 slot_id = (CK_SLOT_ID)-1;
1031 ASSERT_FAILS(aws_pkcs11_lib_find_slot_with_token(
1032 s_pkcs11_tester.lib, NULL /*match_slot_id*/, NULL /*match_token_label*/, &slot_id /*out*/));
1033 ASSERT_INT_EQUALS((CK_SLOT_ID)-1, slot_id);
1034
1035 /* Call aws_pkcs11_lib_find_slot_with_token with 3 tokens, but match the slot 1 this time */
1036 const uint64_t match_slot_id_1 = created_slot_1;
1037 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(
1038 s_pkcs11_tester.lib, &match_slot_id_1 /*match_slot_id*/, NULL /*match_token_label*/, &slot_id /*out*/));
1039 ASSERT_INT_EQUALS(created_slot_1, slot_id);
1040
1041 /* Call aws_pkcs11_lib_find_slot_with_token with 3 tokens, but match the slot 2 this time */
1042 const uint64_t match_slot_id_2 = created_slot_2;
1043 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(
1044 s_pkcs11_tester.lib, &match_slot_id_2 /*match_slot_id*/, NULL /*match_token_label*/, &slot_id /*out*/));
1045 ASSERT_INT_EQUALS(created_slot_2, slot_id);
1046
1047 /*
1048 * Call aws_pkcs11_lib_find_slot_with_token with 3 tokens,
1049 * but a mismatch for a slot and label should return error
1050 * */
1051 slot_id = (CK_SLOT_ID)-1;
1052 ASSERT_FAILS(aws_pkcs11_lib_find_slot_with_token(
1053 s_pkcs11_tester.lib,
1054 &match_slot_id_1 /*match_slot_id*/,
1055 match_label_2 /*match_token_label*/,
1056 &slot_id /*out*/));
1057 ASSERT_INT_EQUALS((CK_SLOT_ID)-1, slot_id);
1058
1059 slot_id = (CK_SLOT_ID)-1;
1060 ASSERT_FAILS(aws_pkcs11_lib_find_slot_with_token(
1061 s_pkcs11_tester.lib,
1062 &match_slot_id_2 /*match_slot_id*/,
1063 match_label_1 /*match_token_label*/,
1064 &slot_id /*out*/));
1065 ASSERT_INT_EQUALS((CK_SLOT_ID)-1, slot_id);
1066 /*
1067 * Call aws_pkcs11_lib_find_slot_with_token with 3 tokens,
1068 * but match for both, slot and label should return success
1069 * */
1070 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(
1071 s_pkcs11_tester.lib,
1072 &match_slot_id_1 /*match_slot_id*/,
1073 match_label_1 /*match_token_label*/,
1074 &slot_id /*out*/));
1075 ASSERT_INT_EQUALS(created_slot_1, slot_id);
1076
1077 ASSERT_SUCCESS(aws_pkcs11_lib_find_slot_with_token(
1078 s_pkcs11_tester.lib,
1079 &match_slot_id_2 /*match_slot_id*/,
1080 match_label_2 /*match_token_label*/,
1081 &slot_id /*out*/));
1082 ASSERT_INT_EQUALS(created_slot_2, slot_id);
1083
1084 /* clear softhsm and make sure that no tokens match with previous slot/label */
1085 ASSERT_SUCCESS(s_pkcs11_clear_softhsm_and_reload());
1086
1087 /*
1088 * Call aws_pkcs11_lib_find_slot_with_token with just the uninitialized token,
1089 * and assert that previous label does not match anymore
1090 * */
1091 slot_id = (CK_SLOT_ID)-1;
1092 ASSERT_FAILS(aws_pkcs11_lib_find_slot_with_token(
1093 s_pkcs11_tester.lib, NULL /*match_slot_id*/, match_label_2 /*match_token_label*/, &slot_id /*out*/));
1094 ASSERT_INT_EQUALS((CK_SLOT_ID)-1, slot_id);
1095
1096 /* Clean up */
1097 aws_string_destroy(match_label_1);
1098 aws_string_destroy(match_label_2);
1099 s_pkcs11_tester_clean_up();
1100 return AWS_OP_SUCCESS;
1101 }
1102 AWS_TEST_CASE(pkcs11_find_slot_many_tokens, s_test_pkcs11_find_slot_many_tokens)
1103
1104 static int s_test_pkcs11_prepare_rsa_2048_sign(
1105 CK_SESSION_HANDLE session,
1106 CK_OBJECT_HANDLE *pri_key,
1107 CK_OBJECT_HANDLE *pub_key) {
1108 struct pkcs11_key_creation_params params = {
1109 .key_label = DEFAULT_KEY_LABEL, .key_id = DEFAULT_KEY_ID, .key_length = 2048};
1110 return s_pkcs11_create_rsa_key(&params, session, pri_key, pub_key);
1111 }
1112
1113 static int s_test_pkcs11_prepare_ec_256_sign(
1114 CK_SESSION_HANDLE session,
1115 CK_OBJECT_HANDLE *pri_key,
1116 CK_OBJECT_HANDLE *pub_key) {
1117 struct pkcs11_key_creation_params params = {
1118 .key_label = DEFAULT_KEY_LABEL, .key_id = DEFAULT_KEY_ID, .key_length = 256};
1119 return s_pkcs11_create_ec_key(&params, session, pri_key, pub_key);
1120 }
1121
1122 /* Encryption/Decryption only applies to RSA, not ECC */
1123 static int s_test_pkcs11_rsa_decrypt(struct aws_allocator *allocator, void *ctx) {
1124 (void)ctx;
1125 /* Reset PKCS#11 tokens, load library */
1126 CK_SLOT_ID created_slot = 0;
1127 CK_SESSION_HANDLE session = CK_INVALID_HANDLE;
1128 s_pkcs11_tester_init_with_session_login(allocator, TOKEN_LABEL_RSA, &created_slot, &session);
1129
1130 CK_OBJECT_HANDLE created_key = CK_INVALID_HANDLE;
1131 CK_OBJECT_HANDLE created_pub_key = CK_INVALID_HANDLE;
1132 ASSERT_SUCCESS(s_test_pkcs11_prepare_rsa_2048_sign(session, &created_key, &created_pub_key));
1133
1134 struct aws_byte_cursor input_cursor = aws_byte_cursor_from_c_str("ABCDEFGHIJKL");
1135 struct aws_byte_buf output_buf; /* initialized later */
1136 AWS_ZERO_STRUCT(output_buf);
1137
1138 /* Encrypt our text */
1139 ASSERT_SUCCESS(s_pkcs11_rsa_encrypt(&input_cursor, &output_buf, session, created_pub_key));
1140
1141 struct aws_byte_cursor cipher_text = aws_byte_cursor_from_buf(&output_buf);
1142 struct aws_byte_buf output_decrypted; /* initialized later */
1143 AWS_ZERO_STRUCT(output_decrypted);
1144 ASSERT_SUCCESS(aws_pkcs11_lib_decrypt(
1145 s_pkcs11_tester.lib, session, created_key, CKK_RSA, cipher_text, allocator, &output_decrypted));
1146
1147 ASSERT_BIN_ARRAYS_EQUALS(output_decrypted.buffer, output_decrypted.len, input_cursor.ptr, input_cursor.len);
1148
1149 /* Assert that sign fails for invalid / mismatch key type */
1150 /* TODO: Move ASSERT_FAILS to ASSERT_ERROR */
1151 CK_KEY_TYPE unsupported_key_type = CKK_GENERIC_SECRET;
1152 aws_byte_buf_clean_up(&output_decrypted);
1153 ASSERT_FAILS(aws_pkcs11_lib_decrypt(
1154 s_pkcs11_tester.lib, session, created_key, unsupported_key_type, cipher_text, allocator, &output_decrypted));
1155
1156 /* Invalid session handle should fail */
1157 ASSERT_FAILS(aws_pkcs11_lib_decrypt(
1158 s_pkcs11_tester.lib, CK_INVALID_HANDLE, created_key, CKK_RSA, cipher_text, allocator, &output_decrypted));
1159
1160 /* Invalid key handle should fail */
1161 ASSERT_FAILS(aws_pkcs11_lib_decrypt(
1162 s_pkcs11_tester.lib, session, CK_INVALID_HANDLE, CKK_RSA, cipher_text, allocator, &output_decrypted));
1163
1164 struct aws_byte_cursor empty_message_to_decrypt = aws_byte_cursor_from_c_str("");
1165 ASSERT_FAILS(aws_pkcs11_lib_decrypt(
1166 s_pkcs11_tester.lib, session, created_key, CKK_RSA, empty_message_to_decrypt, allocator, &output_decrypted));
1167 /* Clean up */
1168 aws_byte_buf_clean_up(&output_buf);
1169 aws_byte_buf_clean_up(&output_decrypted);
1170 s_pkcs11_tester_clean_up();
1171 return AWS_OP_SUCCESS;
1172 }
1173
1174 AWS_TEST_CASE(pkcs11_rsa_decrypt, s_test_pkcs11_rsa_decrypt)
1175
1176 static int s_test_pkcs11_sign_rsa(struct aws_allocator *allocator, void *ctx, enum aws_tls_hash_algorithm digest_alg) {
1177 (void)ctx;
1178 /* Reset PKCS#11 tokens, load library */
1179 CK_SLOT_ID created_slot = 0;
1180 CK_SESSION_HANDLE session = CK_INVALID_HANDLE;
1181 s_pkcs11_tester_init_with_session_login(allocator, TOKEN_LABEL_RSA, &created_slot, &session);
1182
1183 CK_OBJECT_HANDLE created_key = CK_INVALID_HANDLE;
1184 CK_OBJECT_HANDLE created_pub_key = CK_INVALID_HANDLE;
1185 ASSERT_SUCCESS(s_test_pkcs11_prepare_rsa_2048_sign(session, &created_key, &created_pub_key));
1186
1187 struct aws_byte_cursor message_to_sign = aws_byte_cursor_from_c_str("ABCDEFGHIJKL");
1188 struct aws_byte_buf signature; /* initialized later */
1189 AWS_ZERO_STRUCT(signature);
1190
1191 /* Sign a message */
1192 ASSERT_SUCCESS(aws_pkcs11_lib_sign(
1193 s_pkcs11_tester.lib,
1194 session,
1195 created_key,
1196 CKK_RSA,
1197 message_to_sign,
1198 allocator,
1199 digest_alg,
1200 AWS_TLS_SIGNATURE_RSA,
1201 &signature));
1202
1203 struct aws_byte_buf prefixed_input;
1204 /* There is no good way to validate without this, as we append this prefix internally before signing. */
1205 struct aws_byte_cursor prefix;
1206 ASSERT_SUCCESS(aws_get_prefix_to_rsa_sig(digest_alg, &prefix));
1207
1208 aws_byte_buf_init(&prefixed_input, allocator, message_to_sign.len + prefix.len); /* cannot fail */
1209 aws_byte_buf_write(&prefixed_input, prefix.ptr, prefix.len);
1210 aws_byte_buf_write_from_whole_cursor(&prefixed_input, message_to_sign);
1211 struct aws_byte_cursor input_message_to_verify = aws_byte_cursor_from_buf(&prefixed_input);
1212
1213 /* Verify the signature */
1214 ASSERT_SUCCESS(
1215 s_pkcs11_verify_signature(&input_message_to_verify, &signature, session, created_pub_key, CKM_RSA_PKCS));
1216
1217 /* Assert that sign fails for invalid key type */
1218 CK_KEY_TYPE unsupported_key_type = CKK_GENERIC_SECRET;
1219 aws_byte_buf_clean_up(&signature);
1220 ASSERT_FAILS(aws_pkcs11_lib_sign(
1221 s_pkcs11_tester.lib,
1222 session,
1223 created_key,
1224 unsupported_key_type,
1225 message_to_sign,
1226 allocator,
1227 digest_alg,
1228 AWS_TLS_SIGNATURE_RSA,
1229 &signature));
1230
1231 /* Invalid session handle should fail */
1232 ASSERT_FAILS(aws_pkcs11_lib_sign(
1233 s_pkcs11_tester.lib,
1234 CK_INVALID_HANDLE,
1235 created_key,
1236 CKK_RSA,
1237 message_to_sign,
1238 allocator,
1239 digest_alg,
1240 AWS_TLS_SIGNATURE_RSA,
1241 &signature));
1242
1243 /* Invalid key handle should fail */
1244 ASSERT_FAILS(aws_pkcs11_lib_sign(
1245 s_pkcs11_tester.lib,
1246 session,
1247 CK_INVALID_HANDLE,
1248 CKK_RSA,
1249 message_to_sign,
1250 allocator,
1251 digest_alg,
1252 AWS_TLS_SIGNATURE_RSA,
1253 &signature));
1254
1255 /* Clean up */
1256 aws_byte_buf_clean_up(&prefixed_input);
1257 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session);
1258 s_pkcs11_tester_clean_up();
1259 return AWS_OP_SUCCESS;
1260 }
1261
1262 static int s_test_pkcs11_sign_rsa_sha1(struct aws_allocator *allocator, void *ctx) {
1263 return s_test_pkcs11_sign_rsa(allocator, ctx, AWS_TLS_HASH_SHA1);
1264 }
1265 AWS_TEST_CASE(pkcs11_sign_rsa_sha1, s_test_pkcs11_sign_rsa_sha1)
1266
1267 static int s_test_pkcs11_sign_rsa_sha512(struct aws_allocator *allocator, void *ctx) {
1268 return s_test_pkcs11_sign_rsa(allocator, ctx, AWS_TLS_HASH_SHA512);
1269 }
1270 AWS_TEST_CASE(pkcs11_sign_rsa_sha512, s_test_pkcs11_sign_rsa_sha512)
1271
1272 static int s_test_pkcs11_sign_rsa_sha384(struct aws_allocator *allocator, void *ctx) {
1273 return s_test_pkcs11_sign_rsa(allocator, ctx, AWS_TLS_HASH_SHA384);
1274 }
1275 AWS_TEST_CASE(pkcs11_sign_rsa_sha384, s_test_pkcs11_sign_rsa_sha384)
1276
1277 static int s_test_pkcs11_sign_rsa_sha256(struct aws_allocator *allocator, void *ctx) {
1278 return s_test_pkcs11_sign_rsa(allocator, ctx, AWS_TLS_HASH_SHA256);
1279 }
1280 AWS_TEST_CASE(pkcs11_sign_rsa_sha256, s_test_pkcs11_sign_rsa_sha256)
1281
1282 static int s_test_pkcs11_sign_rsa_sha224(struct aws_allocator *allocator, void *ctx) {
1283 return s_test_pkcs11_sign_rsa(allocator, ctx, AWS_TLS_HASH_SHA224);
1284 }
1285 AWS_TEST_CASE(pkcs11_sign_rsa_sha224, s_test_pkcs11_sign_rsa_sha224)
1286
1287 static int s_verify_bigint(
1288 struct aws_allocator *allocator,
1289 uint8_t *ptr,
1290 size_t len_in,
1291 uint8_t *ptr_out,
1292 size_t len_out) {
1293 struct aws_byte_buf buffer;
1294 struct aws_byte_cursor src_array = aws_byte_cursor_from_array(ptr, len_in);
1295 aws_byte_buf_init(&buffer, allocator, len_in + 4);
1296 ASSERT_SUCCESS(aws_pkcs11_asn1_enc_ubigint(&buffer, src_array));
1297 ASSERT_INT_EQUALS(len_out, buffer.len);
1298 for (size_t i = 0; i < len_out; i++) {
1299 ASSERT_HEX_EQUALS(ptr_out[i], buffer.buffer[i], "Mismatch at position %zu", i);
1300 }
1301 aws_byte_buf_clean_up(&buffer);
1302 return AWS_OP_SUCCESS;
1303 }
1304
1305 static int s_test_pkcs11_asn1_bigint(struct aws_allocator *allocator, void *ctx) {
1306 (void)ctx;
1307 /*
1308 * ECDSA relies on this working correct, so test this first to avoid intermittent failures
1309 */
1310 uint8_t pos_int_1_in[4] = {0x12, 0x34, 0x56, 0x78};
1311 uint8_t pos_int_1_out[6] = {0x02, 0x04, 0x12, 0x34, 0x56, 0x78};
1312 ASSERT_SUCCESS(
1313 s_verify_bigint(allocator, pos_int_1_in, sizeof(pos_int_1_in), pos_int_1_out, sizeof(pos_int_1_out)));
1314 uint8_t pos_int_2_in[4] = {0x00, 0x34, 0x56, 0x78};
1315 uint8_t pos_int_2_out[5] = {0x02, 0x03, 0x34, 0x56, 0x78};
1316 ASSERT_SUCCESS(
1317 s_verify_bigint(allocator, pos_int_2_in, sizeof(pos_int_2_in), pos_int_2_out, sizeof(pos_int_2_out)));
1318 uint8_t pos_int_3_in[4] = {0x00, 0x00, 0x56, 0x78};
1319 uint8_t pos_int_3_out[4] = {0x02, 0x02, 0x56, 0x78};
1320 ASSERT_SUCCESS(
1321 s_verify_bigint(allocator, pos_int_3_in, sizeof(pos_int_3_in), pos_int_3_out, sizeof(pos_int_3_out)));
1322 uint8_t pos_int_4_in[4] = {0x00, 0x00, 0x00, 0x78};
1323 uint8_t pos_int_4_out[3] = {0x02, 0x01, 0x78};
1324 ASSERT_SUCCESS(
1325 s_verify_bigint(allocator, pos_int_4_in, sizeof(pos_int_4_in), pos_int_4_out, sizeof(pos_int_4_out)));
1326 uint8_t pos_int_5_in[4] = {0x00, 0x00, 0x00, 0x00};
1327 uint8_t pos_int_5_out[3] = {0x02, 0x01, 0x00};
1328 ASSERT_SUCCESS(
1329 s_verify_bigint(allocator, pos_int_5_in, sizeof(pos_int_5_in), pos_int_5_out, sizeof(pos_int_5_out)));
1330 uint8_t pos_int_6_in[1] = {0}; // actually we specify 0-length, but not all compilers support empty array
1331 uint8_t pos_int_6_out[3] = {0x02, 0x01, 0x00};
1332 ASSERT_SUCCESS(s_verify_bigint(allocator, pos_int_6_in, 0, pos_int_6_out, sizeof(pos_int_6_out)));
1333 uint8_t pos_int_7_in[4] = {0x00, 0x84, 0x56, 0x78};
1334 uint8_t pos_int_7_out[6] = {0x02, 0x04, 0x00, 0x84, 0x56, 0x78};
1335 ASSERT_SUCCESS(
1336 s_verify_bigint(allocator, pos_int_7_in, sizeof(pos_int_7_in), pos_int_7_out, sizeof(pos_int_7_out)));
1337 uint8_t pos_int_8_in[4] = {0x82, 0x34, 0x56, 0x78};
1338 uint8_t pos_int_8_out[7] = {0x02, 0x05, 0x00, 0x82, 0x34, 0x56, 0x78};
1339 ASSERT_SUCCESS(
1340 s_verify_bigint(allocator, pos_int_8_in, sizeof(pos_int_8_in), pos_int_8_out, sizeof(pos_int_8_out)));
1341
1342 return AWS_OP_SUCCESS;
1343 }
1344 AWS_TEST_CASE(pkcs11_asn1_bigint, s_test_pkcs11_asn1_bigint)
1345
1346 static int s_decode_asn1(struct aws_byte_cursor *src, uint8_t *identifier, struct aws_byte_cursor *split) {
1347 ASSERT_TRUE(src->len >= 2, "ASN1 structure too small for header, length=%u", src->len);
1348 *identifier = src->ptr[0];
1349 uint8_t small_len = src->ptr[1];
1350 src->ptr += 2;
1351 src->len -= 2;
1352 ASSERT_TRUE(small_len < 0x80, "ASN1 multi-byte length specified: %u", small_len);
1353 ASSERT_TRUE(small_len <= src->len, "ASN1 length too big: %u > %u", small_len, src->len);
1354 *split = aws_byte_cursor_from_array(src->ptr, small_len);
1355 src->ptr += small_len;
1356 src->len -= small_len;
1357 return AWS_OP_SUCCESS;
1358 }
1359
1360 static int s_write_bigint(struct aws_byte_buf *buf, struct aws_byte_cursor *num, size_t len) {
1361 if (num->len > len && num->len > 1 && num->ptr[0] == 0x00 && (num->ptr[1] & 0x80) != 0) {
1362 // only scenario we allow length to be bigger
1363 num->ptr++;
1364 num->len--;
1365 }
1366 ASSERT_TRUE(num->len <= len, "ASN1 number is too big: %u > %u", num->len, len);
1367 if (num->len < len) {
1368 uint8_t fill = num->ptr[0] & 0x80 ? 0xff : 0x00;
1369 while (len > num->len) {
1370 aws_byte_buf_write(buf, &fill, 1);
1371 len--;
1372 }
1373 }
1374 aws_byte_buf_write_from_whole_cursor(buf, *num);
1375 return AWS_OP_SUCCESS;
1376 }
1377
1378 static int s_test_pkcs11_sign_ec(
1379 struct aws_allocator *allocator,
1380 void *ctx,
1381 int sig_len,
1382 int (*prepare)(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE *pri_key, CK_OBJECT_HANDLE *pub_key)) {
1383 (void)ctx;
1384 /* Reset PKCS#11 tokens, load library */
1385 CK_SLOT_ID created_slot = 0;
1386 CK_SESSION_HANDLE session = CK_INVALID_HANDLE;
1387 s_pkcs11_tester_init_with_session_login(allocator, TOKEN_LABEL_EC, &created_slot, &session);
1388
1389 CK_OBJECT_HANDLE created_key = CK_INVALID_HANDLE;
1390 CK_OBJECT_HANDLE created_pub_key = CK_INVALID_HANDLE;
1391 ASSERT_SUCCESS(prepare(session, &created_key, &created_pub_key));
1392
1393 struct aws_byte_cursor message_to_sign = aws_byte_cursor_from_c_str("ABCDEFGHIJKL");
1394 struct aws_byte_buf signature; /* initialized later */
1395 struct aws_byte_buf sig_verify; /* initialized later */
1396 AWS_ZERO_STRUCT(signature);
1397 AWS_ZERO_STRUCT(sig_verify);
1398
1399 /* Sign a message */
1400 ASSERT_SUCCESS(aws_pkcs11_lib_sign(
1401 s_pkcs11_tester.lib,
1402 session,
1403 created_key,
1404 CKK_EC,
1405 message_to_sign,
1406 allocator,
1407 AWS_TLS_HASH_UNKNOWN, // digest handled entirely by S2N
1408 AWS_TLS_SIGNATURE_ECDSA,
1409 &signature));
1410
1411 /*
1412 * Verify we have a structure of 2 ASN1 encoded integers
1413 */
1414 uint8_t identifier;
1415 struct aws_byte_cursor sig_curs = aws_byte_cursor_from_buf(&signature);
1416 struct aws_byte_cursor struct_body;
1417 ASSERT_SUCCESS(s_decode_asn1(&sig_curs, &identifier, &struct_body));
1418 ASSERT_HEX_EQUALS(0x30, identifier); // compound structure
1419 ASSERT_INT_EQUALS(sig_curs.len, 0);
1420 struct aws_byte_cursor r;
1421 struct aws_byte_cursor s;
1422 ASSERT_SUCCESS(s_decode_asn1(&struct_body, &identifier, &r));
1423 ASSERT_HEX_EQUALS(0x02, identifier); // integer
1424 ASSERT_SUCCESS(s_decode_asn1(&struct_body, &identifier, &s));
1425 ASSERT_HEX_EQUALS(0x02, identifier); // integer
1426 ASSERT_INT_EQUALS(struct_body.len, 0);
1427 // rewrite signature in format PKCS11 expects
1428 aws_byte_buf_init(&sig_verify, allocator, sig_len * 2);
1429 s_write_bigint(&sig_verify, &r, sig_len);
1430 s_write_bigint(&sig_verify, &s, sig_len);
1431 struct aws_byte_cursor message_to_verify = aws_byte_cursor_from_c_str("ABCDEFGHIJKL");
1432
1433 /* Verify the signature */
1434 ASSERT_SUCCESS(s_pkcs11_verify_signature(&message_to_verify, &sig_verify, session, created_pub_key, CKM_ECDSA));
1435
1436 aws_byte_buf_clean_up(&signature);
1437 aws_byte_buf_clean_up(&sig_verify);
1438
1439 /* Assert that sign fails for invalid key type */
1440 CK_KEY_TYPE unsupported_key_type = CKK_GENERIC_SECRET;
1441 ASSERT_FAILS(aws_pkcs11_lib_sign(
1442 s_pkcs11_tester.lib,
1443 session,
1444 created_key,
1445 unsupported_key_type,
1446 message_to_sign,
1447 allocator,
1448 AWS_TLS_HASH_UNKNOWN,
1449 AWS_TLS_SIGNATURE_ECDSA,
1450 &signature));
1451
1452 /* Invalid session handle should fail */
1453 ASSERT_FAILS(aws_pkcs11_lib_sign(
1454 s_pkcs11_tester.lib,
1455 CK_INVALID_HANDLE,
1456 created_key,
1457 CKK_EC,
1458 message_to_sign,
1459 allocator,
1460 AWS_TLS_HASH_UNKNOWN,
1461 AWS_TLS_SIGNATURE_ECDSA,
1462 &signature));
1463
1464 /* Invalid key handle should fail */
1465 ASSERT_FAILS(aws_pkcs11_lib_sign(
1466 s_pkcs11_tester.lib,
1467 session,
1468 CK_INVALID_HANDLE,
1469 CKK_EC,
1470 message_to_sign,
1471 allocator,
1472 AWS_TLS_HASH_UNKNOWN,
1473 AWS_TLS_SIGNATURE_ECDSA,
1474 &signature));
1475
1476 /* Clean up */
1477 aws_byte_buf_clean_up(&signature);
1478 aws_pkcs11_lib_close_session(s_pkcs11_tester.lib, session);
1479 s_pkcs11_tester_clean_up();
1480 return AWS_OP_SUCCESS;
1481 }
1482
1483 static int s_test_pkcs11_sign_ec_256(struct aws_allocator *allocator, void *ctx) {
1484 return s_test_pkcs11_sign_ec(allocator, ctx, 32, s_test_pkcs11_prepare_ec_256_sign);
1485 }
1486 AWS_TEST_CASE(pkcs11_sign_ec_256, s_test_pkcs11_sign_ec_256)
1487
1488 #ifndef BYO_CRYPTO
1489
1490 /*
1491 * Helper function to interact with softhsm begin
1492 */
1493 static int s_run_cmd(const char *fmt, ...) {
1494 char cmd[1024];
1495 va_list args;
1496 va_start(args, fmt);
1497 vsnprintf(cmd, sizeof(cmd), fmt, args);
1498 va_end(args);
1499
1500 printf("Executing command: %s\n", cmd);
1501 struct aws_run_command_options cmd_opts = {.command = cmd};
1502 struct aws_run_command_result cmd_result;
1503 ASSERT_SUCCESS(aws_run_command_result_init(s_pkcs11_tester.allocator, &cmd_result));
1504 ASSERT_SUCCESS(aws_run_command(s_pkcs11_tester.allocator, &cmd_opts, &cmd_result));
1505 int ret_code = cmd_result.ret_code;
1506 aws_run_command_result_cleanup(&cmd_result);
1507 return ret_code;
1508 }
1509
1510 struct tls_tester {
1511 struct {
1512 struct aws_mutex mutex;
1513 struct aws_condition_variable cvar;
1514
1515 bool server_results_ready;
1516 int server_error_code;
1517
1518 bool client_results_ready;
1519 int client_error_code;
1520 } synced;
1521 };
1522 static struct tls_tester s_tls_tester;
1523
1524 static bool s_are_client_results_ready(void *user_data) {
1525 (void)user_data;
1526 return s_tls_tester.synced.client_results_ready;
1527 }
1528
1529 static bool s_are_server_results_ready(void *user_data) {
1530 (void)user_data;
1531 return s_tls_tester.synced.server_results_ready;
1532 }
1533
1534 /* callback when client TLS connection established (or failed) */
1535 static void s_on_tls_client_channel_setup(
1536 struct aws_client_bootstrap *bootstrap,
1537 int error_code,
1538 struct aws_channel *channel,
1539 void *user_data) {
1540
1541 (void)bootstrap;
1542 (void)user_data;
1543 AWS_LOGF_INFO(AWS_LS_IO_PKCS11, "TLS test client setup. error_code=%s", aws_error_name(error_code));
1544
1545 /* if negotiation succeeds: shutdown channel nicely
1546 * if negotiation fails: store error code and notify main thread */
1547 if (error_code == 0) {
1548 aws_channel_shutdown(channel, 0);
1549 } else {
1550 aws_mutex_lock(&s_tls_tester.synced.mutex);
1551 s_tls_tester.synced.client_error_code = error_code;
1552 s_tls_tester.synced.client_results_ready = true;
1553 aws_mutex_unlock(&s_tls_tester.synced.mutex);
1554 aws_condition_variable_notify_all(&s_tls_tester.synced.cvar);
1555 }
1556 }
1557
1558 /* callback when client TLS connection finishes shutdown (doesn't fire if setup failed) */
1559 static void s_on_tls_client_channel_shutdown(
1560 struct aws_client_bootstrap *bootstrap,
1561 int error_code,
1562 struct aws_channel *channel,
1563 void *user_data) {
1564
1565 (void)bootstrap;
1566 (void)channel;
1567 (void)user_data;
1568 AWS_LOGF_INFO(AWS_LS_IO_PKCS11, "TLS test client shutdown. error_code=%s", aws_error_name(error_code));
1569
1570 /* store error code and notify main thread */
1571 aws_mutex_lock(&s_tls_tester.synced.mutex);
1572 s_tls_tester.synced.client_error_code = error_code;
1573 s_tls_tester.synced.client_results_ready = true;
1574 aws_mutex_unlock(&s_tls_tester.synced.mutex);
1575 aws_condition_variable_notify_all(&s_tls_tester.synced.cvar);
1576 }
1577
1578 /* callback when server TLS connection established (or failed) */
1579 static void s_on_tls_server_channel_setup(
1580 struct aws_server_bootstrap *bootstrap,
1581 int error_code,
1582 struct aws_channel *channel,
1583 void *user_data) {
1584
1585 (void)bootstrap;
1586 (void)channel;
1587 (void)user_data;
1588 AWS_LOGF_INFO(AWS_LS_IO_PKCS11, "TLS test server setup. error_code=%s", aws_error_name(error_code));
1589
1590 if (error_code == 0) {
1591 /* do nothing, the client will shut down this channel */
1592 return;
1593 } else {
1594 /* store error code and notify main thread */
1595 aws_mutex_lock(&s_tls_tester.synced.mutex);
1596 s_tls_tester.synced.server_error_code = error_code;
1597 s_tls_tester.synced.server_results_ready = true;
1598 aws_mutex_unlock(&s_tls_tester.synced.mutex);
1599 aws_condition_variable_notify_all(&s_tls_tester.synced.cvar);
1600 }
1601 }
1602
1603 /* callback when server TLS connection established (or failed) */
1604 static void s_on_tls_server_channel_shutdown(
1605 struct aws_server_bootstrap *bootstrap,
1606 int error_code,
1607 struct aws_channel *channel,
1608 void *user_data) {
1609
1610 (void)bootstrap;
1611 (void)channel;
1612 (void)user_data;
1613 AWS_LOGF_INFO(AWS_LS_IO_PKCS11, "TLS test server shutdown. error_code=%s", aws_error_name(error_code));
1614
1615 /* store error code and notify main thread */
1616 aws_mutex_lock(&s_tls_tester.synced.mutex);
1617 s_tls_tester.synced.server_error_code = error_code;
1618 s_tls_tester.synced.server_results_ready = true;
1619 aws_mutex_unlock(&s_tls_tester.synced.mutex);
1620 aws_condition_variable_notify_all(&s_tls_tester.synced.cvar);
1621 }
1622
1623 /* Connect a client client and server, where the client is using PKCS#11 for private key operations */
1624 static int s_test_pkcs11_tls_negotiation_succeeds_common(
1625 struct aws_allocator *allocator,
1626 const char *token_label,
1627 const char *p8key_path,
1628 const char *cert_path,
1629 const char *pkey_path) {
1630 ASSERT_SUCCESS(s_pkcs11_tester_init(allocator));
1631
1632 /* Create token for provided key */
1633
1634 CK_SLOT_ID slot = 0;
1635 ASSERT_SUCCESS(s_pkcs11_softhsm_create_slot(token_label, SO_PIN, USER_PIN, &slot));
1636
1637 aws_pkcs11_lib_release(s_pkcs11_tester.lib);
1638 s_pkcs11_tester.lib = NULL;
1639
1640 /* use softhsm2-util to import key */
1641 ASSERT_SUCCESS(s_run_cmd(
1642 "softhsm2-util --import %s --module \"%s\" --slot %lu --label %s --id %s --pin %s",
1643 p8key_path,
1644 aws_string_c_str(s_pkcs11_tester.shared_lib_path),
1645 slot,
1646 DEFAULT_KEY_LABEL,
1647 DEFAULT_KEY_ID,
1648 USER_PIN));
1649
1650 ASSERT_SUCCESS(s_reload_hsm());
1651
1652 /* Set up resources that aren't specific to server or client */
1653 ASSERT_SUCCESS(aws_mutex_init(&s_tls_tester.synced.mutex));
1654 ASSERT_SUCCESS(aws_condition_variable_init(&s_tls_tester.synced.cvar));
1655
1656 struct aws_event_loop_group_options elg_options = {
1657 .loop_count = 1,
1658 };
1659 struct aws_event_loop_group *event_loop_group = aws_event_loop_group_new(allocator, &elg_options);
1660 ASSERT_NOT_NULL(event_loop_group);
1661
1662 struct aws_host_resolver_default_options resolver_opts = {
1663 .el_group = event_loop_group,
1664 };
1665 struct aws_host_resolver *host_resolver = aws_host_resolver_new_default(allocator, &resolver_opts);
1666 ASSERT_NOT_NULL(host_resolver);
1667
1668 /* use randomly named local domain socket */
1669 struct aws_socket_endpoint endpoint = {.address = {0}, .port = 0};
1670 {
1671 struct aws_byte_buf addr_buf = aws_byte_buf_from_empty_array(endpoint.address, sizeof(endpoint.address));
1672 ASSERT_TRUE(aws_byte_buf_write_from_whole_cursor(&addr_buf, aws_byte_cursor_from_c_str("testsock-")));
1673
1674 struct aws_uuid addr_uuid;
1675 ASSERT_SUCCESS(aws_uuid_init(&addr_uuid));
1676 ASSERT_SUCCESS(aws_uuid_to_str(&addr_uuid, &addr_buf));
1677
1678 ASSERT_TRUE(aws_byte_buf_write_from_whole_cursor(&addr_buf, aws_byte_cursor_from_c_str(".sock")));
1679 }
1680
1681 struct aws_socket_options sock_opts = {
1682 .type = AWS_SOCKET_STREAM,
1683 .domain = AWS_SOCKET_LOCAL,
1684 .connect_timeout_ms = TIMEOUT_MILLIS,
1685 };
1686
1687 /* Set up a server that does mutual TLS. The server will not use PKCS#11 */
1688
1689 struct aws_tls_ctx_options server_tls_opts;
1690 ASSERT_SUCCESS(
1691 aws_tls_ctx_options_init_default_server_from_path(&server_tls_opts, allocator, cert_path, pkey_path));
1692
1693 /* trust the client's self-signed certificate */
1694 ASSERT_SUCCESS(
1695 aws_tls_ctx_options_override_default_trust_store_from_path(&server_tls_opts, NULL /*ca_path*/, cert_path));
1696
1697 aws_tls_ctx_options_set_verify_peer(&server_tls_opts, true);
1698
1699 struct aws_tls_ctx *server_tls_ctx = aws_tls_server_ctx_new(allocator, &server_tls_opts);
1700 ASSERT_NOT_NULL(server_tls_ctx);
1701 aws_tls_ctx_options_clean_up(&server_tls_opts);
1702
1703 struct aws_tls_connection_options server_tls_connection_opts;
1704 aws_tls_connection_options_init_from_ctx(&server_tls_connection_opts, server_tls_ctx);
1705
1706 struct aws_server_bootstrap *server_bootstrap = aws_server_bootstrap_new(allocator, event_loop_group);
1707 ASSERT_NOT_NULL(server_bootstrap);
1708
1709 struct aws_server_socket_channel_bootstrap_options server_listener_sock_opts = {
1710 .bootstrap = server_bootstrap,
1711 .host_name = endpoint.address,
1712 .port = endpoint.port,
1713 .socket_options = &sock_opts,
1714 .tls_options = &server_tls_connection_opts,
1715 .incoming_callback = s_on_tls_server_channel_setup,
1716 .shutdown_callback = s_on_tls_server_channel_shutdown,
1717 };
1718
1719 struct aws_socket *server_listener_sock = aws_server_bootstrap_new_socket_listener(&server_listener_sock_opts);
1720 ASSERT_NOT_NULL(server_listener_sock);
1721
1722 /* Set up a client that does mutual TLS, using PKCS#11 for private key operations */
1723
1724 struct aws_tls_ctx_options client_tls_opts;
1725
1726 # if 1 /* Toggle this to run without actually using PKCS#11. Useful for debugging this test. */
1727 struct aws_tls_ctx_pkcs11_options client_pkcs11_tls_opts = {
1728 .pkcs11_lib = s_pkcs11_tester.lib,
1729 .token_label = aws_byte_cursor_from_c_str(token_label),
1730 .user_pin = aws_byte_cursor_from_c_str(USER_PIN),
1731 .private_key_object_label = aws_byte_cursor_from_c_str(DEFAULT_KEY_LABEL),
1732 .cert_file_path = aws_byte_cursor_from_c_str(cert_path),
1733 };
1734 ASSERT_SUCCESS(
1735 aws_tls_ctx_options_init_client_mtls_with_pkcs11(&client_tls_opts, allocator, &client_pkcs11_tls_opts));
1736 # else
1737 ASSERT_SUCCESS(aws_tls_ctx_options_init_client_mtls_from_path(&client_tls_opts, allocator, cert_path, pkey_path));
1738 # endif
1739
1740 /* trust the server's self-signed certificate */
1741 ASSERT_SUCCESS(
1742 aws_tls_ctx_options_override_default_trust_store_from_path(&client_tls_opts, NULL /*ca_path*/, cert_path));
1743
1744 struct aws_tls_ctx *client_tls_ctx = aws_tls_client_ctx_new(allocator, &client_tls_opts);
1745 ASSERT_NOT_NULL(client_tls_ctx);
1746 aws_tls_ctx_options_clean_up(&client_tls_opts);
1747
1748 struct aws_client_bootstrap_options client_bootstrap_opts = {
1749 .event_loop_group = event_loop_group,
1750 .host_resolver = host_resolver,
1751 };
1752 struct aws_client_bootstrap *client_bootstrap = aws_client_bootstrap_new(allocator, &client_bootstrap_opts);
1753 ASSERT_NOT_NULL(client_bootstrap);
1754
1755 struct aws_byte_cursor server_name = aws_byte_cursor_from_c_str("localhost");
1756 struct aws_tls_connection_options client_tls_connection_opts;
1757 aws_tls_connection_options_init_from_ctx(&client_tls_connection_opts, client_tls_ctx);
1758 ASSERT_SUCCESS(aws_tls_connection_options_set_server_name(&client_tls_connection_opts, allocator, &server_name));
1759 struct aws_socket_channel_bootstrap_options client_channel_opts = {
1760 .bootstrap = client_bootstrap,
1761 .host_name = endpoint.address,
1762 .port = endpoint.port,
1763 .socket_options = &sock_opts,
1764 .tls_options = &client_tls_connection_opts,
1765 .setup_callback = s_on_tls_client_channel_setup,
1766 .shutdown_callback = s_on_tls_client_channel_shutdown,
1767 };
1768
1769 /* finally, tell the client to connect */
1770 ASSERT_SUCCESS(aws_client_bootstrap_new_socket_channel(&client_channel_opts));
1771
1772 /* Wait for connection to go through */
1773
1774 /* CRITICAL SECTION */
1775 {
1776 ASSERT_SUCCESS(aws_mutex_lock(&s_tls_tester.synced.mutex));
1777
1778 /* wait for client to successfully create connection and tear it down */
1779 ASSERT_SUCCESS(aws_condition_variable_wait_for_pred(
1780 &s_tls_tester.synced.cvar,
1781 &s_tls_tester.synced.mutex,
1782 (int64_t)TIMEOUT_NANOS,
1783 s_are_client_results_ready,
1784 NULL /*user_data*/));
1785 ASSERT_INT_EQUALS(0, s_tls_tester.synced.client_error_code);
1786
1787 /* ensure the server also had a good experience */
1788 ASSERT_SUCCESS(aws_condition_variable_wait_for_pred(
1789 &s_tls_tester.synced.cvar,
1790 &s_tls_tester.synced.mutex,
1791 (int64_t)TIMEOUT_NANOS,
1792 s_are_server_results_ready,
1793 NULL /*user_data*/));
1794 ASSERT_INT_EQUALS(0, s_tls_tester.synced.server_error_code);
1795
1796 ASSERT_SUCCESS(aws_mutex_unlock(&s_tls_tester.synced.mutex));
1797 }
1798 /* CRITICAL SECTION */
1799
1800 /* clean up */
1801 aws_tls_ctx_release(client_tls_ctx);
1802 aws_client_bootstrap_release(client_bootstrap);
1803 aws_tls_connection_options_clean_up(&client_tls_connection_opts);
1804
1805 aws_server_bootstrap_destroy_socket_listener(server_bootstrap, server_listener_sock);
1806 aws_tls_connection_options_clean_up(&server_tls_connection_opts);
1807 aws_server_bootstrap_release(server_bootstrap);
1808 aws_tls_ctx_release(server_tls_ctx);
1809 aws_host_resolver_release(host_resolver);
1810 aws_event_loop_group_release(event_loop_group);
1811
1812 /* wait for event-loop threads to wrap up */
1813 aws_thread_set_managed_join_timeout_ns(TIMEOUT_NANOS * 10);
1814 ASSERT_SUCCESS(aws_thread_join_all_managed());
1815
1816 aws_condition_variable_clean_up(&s_tls_tester.synced.cvar);
1817 aws_mutex_clean_up(&s_tls_tester.synced.mutex);
1818 s_pkcs11_tester_clean_up();
1819 return AWS_OP_SUCCESS;
1820 }
1821
1822 /* Connect a client and server, where the client is using PKCS#11 RSA certificate for private key operations */
1823 static int s_test_pkcs11_tls_rsa_negotiation_succeeds(struct aws_allocator *allocator, void *ctx) {
1824 (void)ctx;
1825
1826 return s_test_pkcs11_tls_negotiation_succeeds_common(
1827 allocator, TOKEN_LABEL_RSA, "unittests.p8", "unittests.crt", "unittests.key");
1828 }
1829 AWS_TEST_CASE(pkcs11_tls_rsa_negotiation_succeeds, s_test_pkcs11_tls_rsa_negotiation_succeeds)
1830
1831 /* Connect a client and server, where the client is using PKCS#11 EC certificate for private key operations */
1832 static int s_test_pkcs11_tls_ec_negotiation_succeeds(struct aws_allocator *allocator, void *ctx) {
1833 (void)ctx;
1834
1835 return s_test_pkcs11_tls_negotiation_succeeds_common(
1836 allocator, TOKEN_LABEL_EC, "ec_unittests.p8", "ec_unittests.crt", "ec_unittests.key");
1837 }
1838 AWS_TEST_CASE(pkcs11_tls_ec_negotiation_succeeds, s_test_pkcs11_tls_ec_negotiation_succeeds)
1839 #endif /* !BYO_CRYPTO */