Fix -O3 -Werror=unused-result build in dcache.c (#420)
[heimdal.git] / lib / hx509 / ks_keychain.c
blob9b8224f1d23761c1b3cf1886a2fe0b297e4294bc
1 /*
2 * Copyright (c) 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
34 #include "hx_locl.h"
36 #ifdef HAVE_FRAMEWORK_SECURITY
38 #pragma clang diagnostic push
39 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
41 #include <Security/Security.h>
43 /* Missing function decls in pre Leopard */
44 #ifdef NEED_SECKEYGETCSPHANDLE_PROTO
45 OSStatus SecKeyGetCSPHandle(SecKeyRef, CSSM_CSP_HANDLE *);
46 OSStatus SecKeyGetCredentials(SecKeyRef, CSSM_ACL_AUTHORIZATION_TAG,
47 int, const CSSM_ACCESS_CREDENTIALS **);
48 #define kSecCredentialTypeDefault 0
49 #define CSSM_SIZE uint32_t
50 #endif
53 static int
54 getAttribute(SecKeychainItemRef itemRef, SecItemAttr item,
55 SecKeychainAttributeList **attrs)
57 SecKeychainAttributeInfo attrInfo;
58 UInt32 attrFormat = 0;
59 OSStatus ret;
61 *attrs = NULL;
63 attrInfo.count = 1;
64 attrInfo.tag = &item;
65 attrInfo.format = &attrFormat;
67 ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
68 attrs, NULL, NULL);
69 if (ret)
70 return EINVAL;
71 return 0;
79 struct kc_rsa {
80 SecKeychainItemRef item;
81 size_t keysize;
85 static int
86 kc_rsa_public_encrypt(int flen,
87 const unsigned char *from,
88 unsigned char *to,
89 RSA *rsa,
90 int padding)
92 return -1;
95 static int
96 kc_rsa_public_decrypt(int flen,
97 const unsigned char *from,
98 unsigned char *to,
99 RSA *rsa,
100 int padding)
102 return -1;
106 static int
107 kc_rsa_private_encrypt(int flen,
108 const unsigned char *from,
109 unsigned char *to,
110 RSA *rsa,
111 int padding)
113 struct kc_rsa *kc = RSA_get_app_data(rsa);
115 CSSM_RETURN cret;
116 OSStatus ret;
117 const CSSM_ACCESS_CREDENTIALS *creds;
118 SecKeyRef privKeyRef = (SecKeyRef)kc->item;
119 CSSM_CSP_HANDLE cspHandle;
120 const CSSM_KEY *cssmKey;
121 CSSM_CC_HANDLE sigHandle = 0;
122 CSSM_DATA sig, in;
123 int fret = 0;
125 if (padding != RSA_PKCS1_PADDING)
126 return -1;
128 cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey);
129 if(cret) abort();
131 cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle);
132 if(cret) abort();
134 ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_SIGN,
135 kSecCredentialTypeDefault, &creds);
136 if(ret) abort();
138 ret = CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_RSA,
139 creds, cssmKey, &sigHandle);
140 if(ret) abort();
142 in.Data = (uint8 *)from;
143 in.Length = flen;
145 sig.Data = (uint8 *)to;
146 sig.Length = kc->keysize;
148 cret = CSSM_SignData(sigHandle, &in, 1, CSSM_ALGID_NONE, &sig);
149 if(cret) {
150 /* cssmErrorString(cret); */
151 fret = -1;
152 } else
153 fret = sig.Length;
155 if(sigHandle)
156 CSSM_DeleteContext(sigHandle);
158 return fret;
161 static int
162 kc_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
163 RSA * rsa, int padding)
165 struct kc_rsa *kc = RSA_get_app_data(rsa);
167 CSSM_RETURN cret;
168 OSStatus ret;
169 const CSSM_ACCESS_CREDENTIALS *creds;
170 SecKeyRef privKeyRef = (SecKeyRef)kc->item;
171 CSSM_CSP_HANDLE cspHandle;
172 const CSSM_KEY *cssmKey;
173 CSSM_CC_HANDLE handle = 0;
174 CSSM_DATA out, in, rem;
175 int fret = 0;
176 CSSM_SIZE outlen = 0;
177 char remdata[1024];
179 if (padding != RSA_PKCS1_PADDING)
180 return -1;
182 cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey);
183 if(cret) abort();
185 cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle);
186 if(cret) abort();
188 ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_DECRYPT,
189 kSecCredentialTypeDefault, &creds);
190 if(ret) abort();
193 ret = CSSM_CSP_CreateAsymmetricContext (cspHandle,
194 CSSM_ALGID_RSA,
195 creds,
196 cssmKey,
197 CSSM_PADDING_PKCS1,
198 &handle);
199 if(ret) abort();
201 in.Data = (uint8 *)from;
202 in.Length = flen;
204 out.Data = (uint8 *)to;
205 out.Length = kc->keysize;
207 rem.Data = (uint8 *)remdata;
208 rem.Length = sizeof(remdata);
210 cret = CSSM_DecryptData(handle, &in, 1, &out, 1, &outlen, &rem);
211 if(cret) {
212 /* cssmErrorString(cret); */
213 fret = -1;
214 } else
215 fret = out.Length;
217 if(handle)
218 CSSM_DeleteContext(handle);
220 return fret;
223 static int
224 kc_rsa_init(RSA *rsa)
226 return 1;
229 static int
230 kc_rsa_finish(RSA *rsa)
232 struct kc_rsa *kc_rsa = RSA_get_app_data(rsa);
233 CFRelease(kc_rsa->item);
234 memset(kc_rsa, 0, sizeof(*kc_rsa));
235 free(kc_rsa);
236 return 1;
239 static const RSA_METHOD kc_rsa_pkcs1_method = {
240 "hx509 Keychain PKCS#1 RSA",
241 kc_rsa_public_encrypt,
242 kc_rsa_public_decrypt,
243 kc_rsa_private_encrypt,
244 kc_rsa_private_decrypt,
245 NULL,
246 NULL,
247 kc_rsa_init,
248 kc_rsa_finish,
250 NULL,
251 NULL,
252 NULL,
253 NULL
256 static int
257 set_private_key(hx509_context context,
258 SecKeychainItemRef itemRef,
259 hx509_cert cert)
261 struct kc_rsa *kc;
262 hx509_private_key key;
263 RSA *rsa;
264 int ret;
266 ret = hx509_private_key_init(&key, NULL, NULL);
267 if (ret)
268 return ret;
270 kc = calloc(1, sizeof(*kc));
271 if (kc == NULL)
272 _hx509_abort("out of memory");
274 kc->item = itemRef;
276 rsa = RSA_new();
277 if (rsa == NULL)
278 _hx509_abort("out of memory");
280 /* Argh, fake modulus since OpenSSL API is on crack */
282 SecKeychainAttributeList *attrs = NULL;
283 uint32_t size;
284 void *data;
286 rsa->n = BN_new();
287 if (rsa->n == NULL) abort();
289 ret = getAttribute(itemRef, kSecKeyKeySizeInBits, &attrs);
290 if (ret) abort();
292 size = *(uint32_t *)attrs->attr[0].data;
293 SecKeychainItemFreeAttributesAndData(attrs, NULL);
295 kc->keysize = (size + 7) / 8;
297 data = malloc(kc->keysize);
298 memset(data, 0xe0, kc->keysize);
299 BN_bin2bn(data, kc->keysize, rsa->n);
300 free(data);
302 rsa->e = NULL;
304 RSA_set_method(rsa, &kc_rsa_pkcs1_method);
305 ret = RSA_set_app_data(rsa, kc);
306 if (ret != 1)
307 _hx509_abort("RSA_set_app_data");
309 hx509_private_key_assign_rsa(key, rsa);
310 _hx509_cert_assign_key(cert, key);
312 return 0;
319 struct ks_keychain {
320 int anchors;
321 SecKeychainRef keychain;
324 static int
325 keychain_init(hx509_context context,
326 hx509_certs certs, void **data, int flags,
327 const char *residue, hx509_lock lock)
329 struct ks_keychain *ctx;
331 ctx = calloc(1, sizeof(*ctx));
332 if (ctx == NULL) {
333 hx509_clear_error_string(context);
334 return ENOMEM;
337 if (residue) {
338 if (strcasecmp(residue, "system-anchors") == 0) {
339 ctx->anchors = 1;
340 } else if (strncasecmp(residue, "FILE:", 5) == 0) {
341 OSStatus ret;
343 ret = SecKeychainOpen(residue + 5, &ctx->keychain);
344 if (ret != noErr) {
345 hx509_set_error_string(context, 0, ENOENT,
346 "Failed to open %s", residue);
347 free(ctx);
348 return ENOENT;
350 } else {
351 hx509_set_error_string(context, 0, ENOENT,
352 "Unknown subtype %s", residue);
353 free(ctx);
354 return ENOENT;
358 *data = ctx;
359 return 0;
366 static int
367 keychain_free(hx509_certs certs, void *data)
369 struct ks_keychain *ctx = data;
370 if (ctx->keychain)
371 CFRelease(ctx->keychain);
372 memset(ctx, 0, sizeof(*ctx));
373 free(ctx);
374 return 0;
381 struct iter {
382 hx509_certs certs;
383 void *cursor;
384 SecKeychainSearchRef searchRef;
387 static int
388 keychain_iter_start(hx509_context context,
389 hx509_certs certs, void *data, void **cursor)
391 struct ks_keychain *ctx = data;
392 struct iter *iter;
394 iter = calloc(1, sizeof(*iter));
395 if (iter == NULL) {
396 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
397 return ENOMEM;
400 if (ctx->anchors) {
401 CFArrayRef anchors;
402 int ret;
403 int i;
405 ret = hx509_certs_init(context, "MEMORY:ks-file-create",
406 0, NULL, &iter->certs);
407 if (ret) {
408 free(iter);
409 return ret;
412 ret = SecTrustCopyAnchorCertificates(&anchors);
413 if (ret != 0) {
414 hx509_certs_free(&iter->certs);
415 free(iter);
416 hx509_set_error_string(context, 0, ENOMEM,
417 "Can't get trust anchors from Keychain");
418 return ENOMEM;
420 for (i = 0; i < CFArrayGetCount(anchors); i++) {
421 SecCertificateRef cr;
422 hx509_cert cert;
423 CSSM_DATA cssm;
425 cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i);
427 SecCertificateGetData(cr, &cssm);
429 cert = hx509_cert_init_data(context, cssm.Data, cssm.Length, NULL);
430 if (cert == NULL)
431 continue;
433 ret = hx509_certs_add(context, iter->certs, cert);
434 hx509_cert_free(cert);
436 CFRelease(anchors);
439 if (iter->certs) {
440 int ret;
441 ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor);
442 if (ret) {
443 hx509_certs_free(&iter->certs);
444 free(iter);
445 return ret;
447 } else {
448 OSStatus ret;
450 ret = SecKeychainSearchCreateFromAttributes(ctx->keychain,
451 kSecCertificateItemClass,
452 NULL,
453 &iter->searchRef);
454 if (ret) {
455 free(iter);
456 hx509_set_error_string(context, 0, ret,
457 "Failed to start search for attributes");
458 return ENOMEM;
462 *cursor = iter;
463 return 0;
470 static int
471 keychain_iter(hx509_context context,
472 hx509_certs certs, void *data, void *cursor, hx509_cert *cert)
474 SecKeychainAttributeList *attrs = NULL;
475 SecKeychainAttributeInfo attrInfo;
476 UInt32 attrFormat[1] = { 0 };
477 SecKeychainItemRef itemRef;
478 SecItemAttr item[1];
479 heim_error_t error = NULL;
480 struct iter *iter = cursor;
481 OSStatus ret;
482 UInt32 len;
483 void *ptr = NULL;
485 if (iter->certs)
486 return hx509_certs_next_cert(context, iter->certs, iter->cursor, cert);
488 *cert = NULL;
490 ret = SecKeychainSearchCopyNext(iter->searchRef, &itemRef);
491 if (ret == errSecItemNotFound)
492 return 0;
493 else if (ret != 0)
494 return EINVAL;
497 * Pick out certificate and matching "keyid"
500 item[0] = kSecPublicKeyHashItemAttr;
502 attrInfo.count = 1;
503 attrInfo.tag = item;
504 attrInfo.format = attrFormat;
506 ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
507 &attrs, &len, &ptr);
508 if (ret)
509 return EINVAL;
511 *cert = hx509_cert_init_data(context, ptr, len, &error);
512 if (*cert == NULL) {
513 ret = heim_error_get_code(error);
514 heim_release(error);
515 goto out;
519 * Find related private key if there is one by looking at
520 * kSecPublicKeyHashItemAttr == kSecKeyLabel
523 SecKeychainSearchRef search;
524 SecKeychainAttribute attrKeyid;
525 SecKeychainAttributeList attrList;
527 attrKeyid.tag = kSecKeyLabel;
528 attrKeyid.length = attrs->attr[0].length;
529 attrKeyid.data = attrs->attr[0].data;
531 attrList.count = 1;
532 attrList.attr = &attrKeyid;
534 ret = SecKeychainSearchCreateFromAttributes(NULL,
535 CSSM_DL_DB_RECORD_PRIVATE_KEY,
536 &attrList,
537 &search);
538 if (ret) {
539 ret = 0;
540 goto out;
543 ret = SecKeychainSearchCopyNext(search, &itemRef);
544 CFRelease(search);
545 if (ret == errSecItemNotFound) {
546 ret = 0;
547 goto out;
548 } else if (ret) {
549 ret = EINVAL;
550 goto out;
552 set_private_key(context, itemRef, *cert);
555 out:
556 SecKeychainItemFreeAttributesAndData(attrs, ptr);
558 return ret;
565 static int
566 keychain_iter_end(hx509_context context,
567 hx509_certs certs,
568 void *data,
569 void *cursor)
571 struct iter *iter = cursor;
573 if (iter->certs) {
574 hx509_certs_end_seq(context, iter->certs, iter->cursor);
575 hx509_certs_free(&iter->certs);
576 } else {
577 CFRelease(iter->searchRef);
580 memset(iter, 0, sizeof(*iter));
581 free(iter);
582 return 0;
589 struct hx509_keyset_ops keyset_keychain = {
590 "KEYCHAIN",
592 keychain_init,
593 NULL,
594 keychain_free,
595 NULL,
596 NULL,
597 keychain_iter_start,
598 keychain_iter,
599 keychain_iter_end,
600 NULL,
601 NULL,
602 NULL
605 #pragma clang diagnostic pop
607 #endif /* HAVE_FRAMEWORK_SECURITY */
613 void
614 _hx509_ks_keychain_register(hx509_context context)
616 #ifdef HAVE_FRAMEWORK_SECURITY
617 _hx509_ks_register(context, &keyset_keychain);
618 #endif