Debian Codegraph @

crt/aws-c-cal/source/darwin/securityframework_rsa.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/rsa.h>
6
7 #include <aws/cal/cal.h>
8 #include <aws/common/encoding.h>
9
10 #include <Security/SecKey.h>
11 #include <Security/Security.h>
12
13 struct sec_rsa_key_pair {
14 struct aws_rsa_key_pair base;
15 CFAllocatorRef cf_allocator;
16 SecKeyRef priv_key_ref;
17 SecKeyRef pub_key_ref;
18 };
19
20 static void s_rsa_destroy_key(void *key_pair) {
21 if (key_pair == NULL) {
22 return;
23 }
24
25 struct aws_rsa_key_pair *base = key_pair;
26 struct sec_rsa_key_pair *impl = base->impl;
27
28 if (impl->pub_key_ref) {
29 CFRelease(impl->pub_key_ref);
30 }
31
32 if (impl->priv_key_ref) {
33 CFRelease(impl->priv_key_ref);
34 }
35
36 if (impl->cf_allocator) {
37 aws_wrapped_cf_allocator_destroy(impl->cf_allocator);
38 }
39
40 aws_rsa_key_pair_base_clean_up(base);
41
42 aws_mem_release(base->allocator, impl);
43 }
44
45 /*
46 * Transforms security error code into crt error code and raises it as necessary.
47 * Docs on what security apis can throw are fairly sparse and so far in testing
48 * it only threw generic -50 error. So just log for now and we can add additional
49 * error translation later.
50 */
51 static int s_reinterpret_sec_error_as_crt(CFErrorRef error, const char *function_name) {
52 if (error == NULL) {
53 return AWS_OP_SUCCESS;
54 }
55
56 CFIndex error_code = CFErrorGetCode(error);
57 CFStringRef error_message = CFErrorCopyDescription(error); /* This function never returns NULL */
58
59 /*
60 * Note: CFStringGetCStringPtr returns NULL quite often.
61 * Refer to writeup at the start of CFString.h as to why.
62 * To reliably get an error message we need to use the following function
63 * that will copy error string into our buffer.
64 */
65 const char *error_cstr = NULL;
66 char buffer[128];
67 if (CFStringGetCString(error_message, buffer, 128, kCFStringEncodingUTF8)) {
68 error_cstr = buffer;
69 }
70
71 int crt_error = AWS_ERROR_CAL_CRYPTO_OPERATION_FAILED;
72
73 /*
74 * Mac seems throws errSecVerifyFailed for any signature verification
75 * failures (based on testing and not review of their code).
76 * Which makes it impossible to distinguish between signature validation
77 * failure and api call failure.
78 * So let errSecVerifyFailed as signature validation failure, rather than a
79 * more generic Crypto Failure as it seems more intuitive to caller that
80 * signature cannot be verified, rather than something wrong with crypto (and
81 * in most cases crypto is working correctly, but returning non-specific error).
82 */
83 if (error_code == errSecVerifyFailed) {
84 crt_error = AWS_ERROR_CAL_SIGNATURE_VALIDATION_FAILED;
85 }
86
87 AWS_LOGF_ERROR(
88 AWS_LS_CAL_RSA,
89 "%s() failed. CFError:%ld(%s) aws_error:%s",
90 function_name,
91 error_code,
92 error_cstr ? error_cstr : "",
93 aws_error_name(crt_error));
94
95 CFRelease(error_message);
96
97 return aws_raise_error(crt_error);
98 }
99
100 /*
101 * Maps crt encryption algo enum to Security Framework equivalent.
102 * Fails with AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM if mapping cannot be done for
103 * some reason.
104 * Mapped value is passed back through out variable.
105 */
106 static int s_map_rsa_encryption_algo_to_sec(enum aws_rsa_encryption_algorithm algorithm, SecKeyAlgorithm *out) {
107
108 switch (algorithm) {
109 case AWS_CAL_RSA_ENCRYPTION_PKCS1_5:
110 *out = kSecKeyAlgorithmRSAEncryptionPKCS1;
111 return AWS_OP_SUCCESS;
112 case AWS_CAL_RSA_ENCRYPTION_OAEP_SHA256:
113 *out = kSecKeyAlgorithmRSAEncryptionOAEPSHA256;
114 return AWS_OP_SUCCESS;
115 case AWS_CAL_RSA_ENCRYPTION_OAEP_SHA512:
116 *out = kSecKeyAlgorithmRSAEncryptionOAEPSHA512;
117 return AWS_OP_SUCCESS;
118 }
119
120 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
121 }
122
123 /*
124 * Maps crt encryption algo enum to Security Framework equivalent.
125 * Fails with AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM if mapping cannot be done for
126 * some reason.
127 * Mapped value is passed back through out variable.
128 */
129 static int s_map_rsa_signing_algo_to_sec(enum aws_rsa_signature_algorithm algorithm, SecKeyAlgorithm *out) {
130
131 switch (algorithm) {
132 case AWS_CAL_RSA_SIGNATURE_PKCS1_5_SHA256:
133 *out = kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256;
134 return AWS_OP_SUCCESS;
135 case AWS_CAL_RSA_SIGNATURE_PKCS1_5_SHA1:
136 *out = kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA1;
137 return AWS_OP_SUCCESS;
138 case AWS_CAL_RSA_SIGNATURE_PSS_SHA256:
139 #if (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101300 /* macOS 10.13 */)) || \
140 (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* iOS v11 */)) || \
141 (defined(__TV_OS_VERSION_MAX_ALLOWED) && (__TV_OS_VERSION_MAX_ALLOWED >= 110000 /* tvos v11 */)) || \
142 (defined(__WATCH_OS_VERSION_MAX_ALLOWED) && (__WATCH_OS_VERSION_MAX_ALLOWED >= 40000 /* watchos v4 */))
143 if (__builtin_available(macos 10.13, ios 11.0, tvos 11.0, watchos 4.0, *)) {
144 *out = kSecKeyAlgorithmRSASignatureDigestPSSSHA256;
145 return AWS_OP_SUCCESS;
146 } else {
147 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
148 }
149 #else
150 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
151 #endif
152 }
153
154 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
155 }
156
157 static int s_rsa_encrypt(
158 const struct aws_rsa_key_pair *key_pair,
159 enum aws_rsa_encryption_algorithm algorithm,
160 struct aws_byte_cursor plaintext,
161 struct aws_byte_buf *out) {
162 struct sec_rsa_key_pair *key_pair_impl = key_pair->impl;
163
164 if (key_pair_impl->pub_key_ref == NULL) {
165 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "RSA Key Pair is missing Public Key required for encrypt operation.");
166 return aws_raise_error(AWS_ERROR_CAL_MISSING_REQUIRED_KEY_COMPONENT);
167 }
168
169 SecKeyAlgorithm alg;
170 if (s_map_rsa_encryption_algo_to_sec(algorithm, &alg)) {
171 return AWS_OP_ERR;
172 }
173
174 if (!SecKeyIsAlgorithmSupported(key_pair_impl->pub_key_ref, kSecKeyOperationTypeEncrypt, alg)) {
175 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "Algo is not supported for this operation");
176 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
177 }
178
179 CFDataRef plaintext_ref =
180 CFDataCreateWithBytesNoCopy(key_pair_impl->cf_allocator, plaintext.ptr, plaintext.len, kCFAllocatorNull);
181 AWS_FATAL_ASSERT(plaintext_ref);
182
183 CFErrorRef error = NULL;
184 CFDataRef ciphertext_ref = SecKeyCreateEncryptedData(key_pair_impl->pub_key_ref, alg, plaintext_ref, &error);
185 if (s_reinterpret_sec_error_as_crt(error, "SecKeyCreateEncryptedData")) {
186 CFRelease(error);
187 goto on_error;
188 }
189
190 struct aws_byte_cursor ciphertext_cur =
191 aws_byte_cursor_from_array(CFDataGetBytePtr(ciphertext_ref), CFDataGetLength(ciphertext_ref));
192
193 if (aws_byte_buf_append(out, &ciphertext_cur)) {
194 aws_raise_error(AWS_ERROR_SHORT_BUFFER);
195 goto on_error;
196 }
197
198 CFRelease(plaintext_ref);
199 CFRelease(ciphertext_ref);
200 return AWS_OP_SUCCESS;
201
202 on_error:
203 if (plaintext_ref != NULL) {
204 CFRelease(plaintext_ref);
205 }
206
207 if (ciphertext_ref != NULL) {
208 CFRelease(ciphertext_ref);
209 }
210
211 return AWS_OP_ERR;
212 }
213
214 static int s_rsa_decrypt(
215 const struct aws_rsa_key_pair *key_pair,
216 enum aws_rsa_encryption_algorithm algorithm,
217 struct aws_byte_cursor ciphertext,
218 struct aws_byte_buf *out) {
219 struct sec_rsa_key_pair *key_pair_impl = key_pair->impl;
220
221 if (key_pair_impl->priv_key_ref == NULL) {
222 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "RSA Key Pair is missing Private Key required for encrypt operation.");
223 return aws_raise_error(AWS_ERROR_CAL_MISSING_REQUIRED_KEY_COMPONENT);
224 }
225
226 SecKeyAlgorithm alg;
227 if (s_map_rsa_encryption_algo_to_sec(algorithm, &alg)) {
228 return AWS_OP_ERR;
229 }
230
231 if (!SecKeyIsAlgorithmSupported(key_pair_impl->priv_key_ref, kSecKeyOperationTypeDecrypt, alg)) {
232 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "Algo is not supported for this operation");
233 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
234 }
235
236 CFDataRef ciphertext_ref =
237 CFDataCreateWithBytesNoCopy(key_pair_impl->cf_allocator, ciphertext.ptr, ciphertext.len, kCFAllocatorNull);
238 AWS_FATAL_ASSERT(ciphertext_ref);
239
240 CFErrorRef error = NULL;
241 CFDataRef plaintext_ref = SecKeyCreateDecryptedData(key_pair_impl->priv_key_ref, alg, ciphertext_ref, &error);
242 if (s_reinterpret_sec_error_as_crt(error, "SecKeyCreateDecryptedData")) {
243 CFRelease(error);
244 goto on_error;
245 }
246
247 struct aws_byte_cursor plaintext_cur =
248 aws_byte_cursor_from_array(CFDataGetBytePtr(plaintext_ref), CFDataGetLength(plaintext_ref));
249
250 if (aws_byte_buf_append(out, &plaintext_cur)) {
251 aws_raise_error(AWS_ERROR_SHORT_BUFFER);
252 goto on_error;
253 }
254
255 CFRelease(plaintext_ref);
256 CFRelease(ciphertext_ref);
257 return AWS_OP_SUCCESS;
258
259 on_error:
260 if (plaintext_ref != NULL) {
261 CFRelease(plaintext_ref);
262 }
263
264 if (ciphertext_ref != NULL) {
265 CFRelease(ciphertext_ref);
266 }
267
268 return AWS_OP_ERR;
269 }
270
271 static int s_rsa_sign(
272 const struct aws_rsa_key_pair *key_pair,
273 enum aws_rsa_signature_algorithm algorithm,
274 struct aws_byte_cursor digest,
275 struct aws_byte_buf *out) {
276 struct sec_rsa_key_pair *key_pair_impl = key_pair->impl;
277
278 if (key_pair_impl->priv_key_ref == NULL) {
279 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "RSA Key Pair is missing Private Key required for sign operation.");
280 return aws_raise_error(AWS_ERROR_CAL_MISSING_REQUIRED_KEY_COMPONENT);
281 }
282
283 SecKeyAlgorithm alg;
284 if (s_map_rsa_signing_algo_to_sec(algorithm, &alg)) {
285 return AWS_OP_ERR;
286 }
287
288 if (!SecKeyIsAlgorithmSupported(key_pair_impl->priv_key_ref, kSecKeyOperationTypeSign, alg)) {
289 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "Algo is not supported for this operation");
290 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
291 }
292
293 CFDataRef digest_ref =
294 CFDataCreateWithBytesNoCopy(key_pair_impl->cf_allocator, digest.ptr, digest.len, kCFAllocatorNull);
295 AWS_FATAL_ASSERT(digest_ref);
296
297 CFErrorRef error = NULL;
298 CFDataRef signature_ref = SecKeyCreateSignature(key_pair_impl->priv_key_ref, alg, digest_ref, &error);
299 if (s_reinterpret_sec_error_as_crt(error, "SecKeyCreateSignature")) {
300 CFRelease(error);
301 goto on_error;
302 }
303
304 struct aws_byte_cursor signature_cur =
305 aws_byte_cursor_from_array(CFDataGetBytePtr(signature_ref), CFDataGetLength(signature_ref));
306
307 if (aws_byte_buf_append(out, &signature_cur)) {
308 aws_raise_error(AWS_ERROR_SHORT_BUFFER);
309 goto on_error;
310 }
311
312 CFRelease(digest_ref);
313 CFRelease(signature_ref);
314
315 return AWS_OP_SUCCESS;
316
317 on_error:
318 CFRelease(digest_ref);
319
320 if (signature_ref != NULL) {
321 CFRelease(signature_ref);
322 }
323
324 return AWS_OP_ERR;
325 }
326
327 static int s_rsa_verify(
328 const struct aws_rsa_key_pair *key_pair,
329 enum aws_rsa_signature_algorithm algorithm,
330 struct aws_byte_cursor digest,
331 struct aws_byte_cursor signature) {
332 struct sec_rsa_key_pair *key_pair_impl = key_pair->impl;
333
334 if (key_pair_impl->pub_key_ref == NULL) {
335 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "RSA Key Pair is missing Public Key required for verify operation.");
336 return aws_raise_error(AWS_ERROR_CAL_MISSING_REQUIRED_KEY_COMPONENT);
337 }
338
339 SecKeyAlgorithm alg;
340 if (s_map_rsa_signing_algo_to_sec(algorithm, &alg)) {
341 return AWS_OP_ERR;
342 }
343
344 if (!SecKeyIsAlgorithmSupported(key_pair_impl->pub_key_ref, kSecKeyOperationTypeVerify, alg)) {
345 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "Algo is not supported for this operation");
346 return aws_raise_error(AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM);
347 }
348
349 CFDataRef digest_ref =
350 CFDataCreateWithBytesNoCopy(key_pair_impl->cf_allocator, digest.ptr, digest.len, kCFAllocatorNull);
351 CFDataRef signature_ref =
352 CFDataCreateWithBytesNoCopy(key_pair_impl->cf_allocator, signature.ptr, signature.len, kCFAllocatorNull);
353 AWS_FATAL_ASSERT(digest_ref && signature_ref);
354
355 CFErrorRef error = NULL;
356 Boolean result = SecKeyVerifySignature(key_pair_impl->pub_key_ref, alg, digest_ref, signature_ref, &error);
357
358 CFRelease(digest_ref);
359 CFRelease(signature_ref);
360 if (s_reinterpret_sec_error_as_crt(error, "SecKeyVerifySignature")) {
361 CFRelease(error);
362 return AWS_OP_ERR;
363 }
364
365 return result ? AWS_OP_SUCCESS : aws_raise_error(AWS_ERROR_CAL_SIGNATURE_VALIDATION_FAILED);
366 }
367
368 static struct aws_rsa_key_vtable s_rsa_key_pair_vtable = {
369 .encrypt = s_rsa_encrypt,
370 .decrypt = s_rsa_decrypt,
371 .sign = s_rsa_sign,
372 .verify = s_rsa_verify,
373 };
374
375 struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_private_key_pkcs1_impl(
376 struct aws_allocator *allocator,
377 struct aws_byte_cursor key) {
378 struct sec_rsa_key_pair *key_pair_impl = aws_mem_calloc(allocator, 1, sizeof(struct sec_rsa_key_pair));
379
380 CFMutableDictionaryRef key_attributes = NULL;
381 CFDataRef private_key_data = NULL;
382
383 aws_ref_count_init(&key_pair_impl->base.ref_count, &key_pair_impl->base, s_rsa_destroy_key);
384 key_pair_impl->base.impl = key_pair_impl;
385 key_pair_impl->base.allocator = allocator;
386 key_pair_impl->cf_allocator = aws_wrapped_cf_allocator_new(allocator);
387 aws_byte_buf_init_copy_from_cursor(&key_pair_impl->base.priv, allocator, key);
388
389 private_key_data = CFDataCreate(key_pair_impl->cf_allocator, key.ptr, key.len);
390 AWS_FATAL_ASSERT(private_key_data);
391
392 key_attributes = CFDictionaryCreateMutable(key_pair_impl->cf_allocator, 0, NULL, NULL);
393 AWS_FATAL_ASSERT(key_attributes);
394
395 CFDictionaryAddValue(key_attributes, kSecClass, kSecClassKey);
396 CFDictionaryAddValue(key_attributes, kSecAttrKeyType, kSecAttrKeyTypeRSA);
397 CFDictionaryAddValue(key_attributes, kSecAttrKeyClass, kSecAttrKeyClassPrivate);
398
399 CFErrorRef error = NULL;
400 key_pair_impl->priv_key_ref = SecKeyCreateWithData(private_key_data, key_attributes, &error);
401 if (s_reinterpret_sec_error_as_crt(error, "SecKeyCreateWithData")) {
402 CFRelease(error);
403 goto on_error;
404 }
405
406 key_pair_impl->pub_key_ref = SecKeyCopyPublicKey(key_pair_impl->priv_key_ref);
407 AWS_FATAL_ASSERT(key_pair_impl->pub_key_ref);
408
409 key_pair_impl->base.vtable = &s_rsa_key_pair_vtable;
410 size_t block_size = SecKeyGetBlockSize(key_pair_impl->priv_key_ref);
411
412 if (block_size < (AWS_CAL_RSA_MIN_SUPPORTED_KEY_SIZE_IN_BITS / 8) ||
413 block_size > (AWS_CAL_RSA_MAX_SUPPORTED_KEY_SIZE_IN_BITS / 8)) {
414 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "Unsupported key size: %zu", block_size);
415 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
416 goto on_error;
417 }
418
419 key_pair_impl->base.key_size_in_bits = block_size * 8;
420
421 CFRelease(key_attributes);
422 CFRelease(private_key_data);
423
424 return &key_pair_impl->base;
425
426 on_error:
427 if (private_key_data) {
428 CFRelease(private_key_data);
429 }
430
431 if (key_attributes) {
432 CFRelease(key_attributes);
433 }
434 s_rsa_destroy_key(&key_pair_impl->base);
435 return NULL;
436 }
437
438 struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_public_key_pkcs1_impl(
439 struct aws_allocator *allocator,
440 struct aws_byte_cursor key) {
441 struct sec_rsa_key_pair *key_pair_impl = aws_mem_calloc(allocator, 1, sizeof(struct sec_rsa_key_pair));
442
443 CFMutableDictionaryRef key_attributes = NULL;
444 CFDataRef public_key_data = NULL;
445
446 aws_ref_count_init(&key_pair_impl->base.ref_count, &key_pair_impl->base, s_rsa_destroy_key);
447 key_pair_impl->base.impl = key_pair_impl;
448 key_pair_impl->base.allocator = allocator;
449 key_pair_impl->cf_allocator = aws_wrapped_cf_allocator_new(allocator);
450 aws_byte_buf_init_copy_from_cursor(&key_pair_impl->base.pub, allocator, key);
451
452 public_key_data = CFDataCreate(key_pair_impl->cf_allocator, key.ptr, key.len);
453 AWS_FATAL_ASSERT(public_key_data);
454
455 key_attributes = CFDictionaryCreateMutable(key_pair_impl->cf_allocator, 0, NULL, NULL);
456 AWS_FATAL_ASSERT(key_attributes);
457
458 CFDictionaryAddValue(key_attributes, kSecClass, kSecClassKey);
459 CFDictionaryAddValue(key_attributes, kSecAttrKeyType, kSecAttrKeyTypeRSA);
460 CFDictionaryAddValue(key_attributes, kSecAttrKeyClass, kSecAttrKeyClassPublic);
461
462 CFErrorRef error = NULL;
463 key_pair_impl->pub_key_ref = SecKeyCreateWithData(public_key_data, key_attributes, &error);
464 if (s_reinterpret_sec_error_as_crt(error, "SecKeyCreateWithData")) {
465 CFRelease(error);
466 goto on_error;
467 }
468
469 key_pair_impl->base.vtable = &s_rsa_key_pair_vtable;
470 size_t block_size = SecKeyGetBlockSize(key_pair_impl->pub_key_ref);
471 if (block_size < (AWS_CAL_RSA_MIN_SUPPORTED_KEY_SIZE_IN_BITS / 8) ||
472 block_size > (AWS_CAL_RSA_MAX_SUPPORTED_KEY_SIZE_IN_BITS / 8)) {
473 AWS_LOGF_ERROR(AWS_LS_CAL_RSA, "Unsupported key size: %zu", block_size);
474 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
475 goto on_error;
476 }
477 key_pair_impl->base.key_size_in_bits = block_size * 8;
478
479 CFRelease(key_attributes);
480 CFRelease(public_key_data);
481
482 return &key_pair_impl->base;
483
484 on_error:
485 if (public_key_data) {
486 CFRelease(public_key_data);
487 }
488
489 if (key_attributes) {
490 CFRelease(key_attributes);
491 }
492 s_rsa_destroy_key(&key_pair_impl->base);
493 return NULL;
494 }