2 * Copyright (c) 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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
36 #ifdef HAVE_FRAMEWORK_SECURITY
38 #include <Security/Security.h>
40 /* Missing function decls in pre Leopard */
41 #ifdef NEED_SECKEYGETCSPHANDLE_PROTO
42 OSStatus SecKeyGetCSPHandle(SecKeyRef, CSSM_CSP_HANDLE *);
43 OSStatus SecKeyGetCredentials(SecKeyRef, CSSM_ACL_AUTHORIZATION_TAG,
44 int, const CSSM_ACCESS_CREDENTIALS **);
45 #define kSecCredentialTypeDefault 0
46 #define CSSM_SIZE uint32_t
51 getAttribute(SecKeychainItemRef itemRef, SecItemAttr item,
52 SecKeychainAttributeList **attrs)
54 SecKeychainAttributeInfo attrInfo;
55 UInt32 attrFormat = 0;
62 attrInfo.format = &attrFormat;
64 ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
77 SecKeychainItemRef item;
83 kc_rsa_public_encrypt(int flen,
84 const unsigned char *from,
93 kc_rsa_public_decrypt(int flen,
94 const unsigned char *from,
104 kc_rsa_private_encrypt(int flen,
105 const unsigned char *from,
110 struct kc_rsa *kc = RSA_get_app_data(rsa);
114 const CSSM_ACCESS_CREDENTIALS *creds;
115 SecKeyRef privKeyRef = (SecKeyRef)kc->item;
116 CSSM_CSP_HANDLE cspHandle;
117 const CSSM_KEY *cssmKey;
118 CSSM_CC_HANDLE sigHandle = 0;
122 if (padding != RSA_PKCS1_PADDING)
125 cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey);
128 cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle);
131 ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_SIGN,
132 kSecCredentialTypeDefault, &creds);
135 ret = CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_RSA,
136 creds, cssmKey, &sigHandle);
139 in.Data = (uint8 *)from;
142 sig.Data = (uint8 *)to;
143 sig.Length = kc->keysize;
145 cret = CSSM_SignData(sigHandle, &in, 1, CSSM_ALGID_NONE, &sig);
147 /* cssmErrorString(cret); */
153 CSSM_DeleteContext(sigHandle);
159 kc_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
160 RSA * rsa, int padding)
162 struct kc_rsa *kc = RSA_get_app_data(rsa);
166 const CSSM_ACCESS_CREDENTIALS *creds;
167 SecKeyRef privKeyRef = (SecKeyRef)kc->item;
168 CSSM_CSP_HANDLE cspHandle;
169 const CSSM_KEY *cssmKey;
170 CSSM_CC_HANDLE handle = 0;
171 CSSM_DATA out, in, rem;
173 CSSM_SIZE outlen = 0;
176 if (padding != RSA_PKCS1_PADDING)
179 cret = SecKeyGetCSSMKey(privKeyRef, &cssmKey);
182 cret = SecKeyGetCSPHandle(privKeyRef, &cspHandle);
185 ret = SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_DECRYPT,
186 kSecCredentialTypeDefault, &creds);
190 ret = CSSM_CSP_CreateAsymmetricContext (cspHandle,
198 in.Data = (uint8 *)from;
201 out.Data = (uint8 *)to;
202 out.Length = kc->keysize;
204 rem.Data = (uint8 *)remdata;
205 rem.Length = sizeof(remdata);
207 cret = CSSM_DecryptData(handle, &in, 1, &out, 1, &outlen, &rem);
209 /* cssmErrorString(cret); */
215 CSSM_DeleteContext(handle);
221 kc_rsa_init(RSA *rsa)
227 kc_rsa_finish(RSA *rsa)
229 struct kc_rsa *kc_rsa = RSA_get_app_data(rsa);
230 CFRelease(kc_rsa->item);
231 memset(kc_rsa, 0, sizeof(*kc_rsa));
236 static const RSA_METHOD kc_rsa_pkcs1_method = {
237 "hx509 Keychain PKCS#1 RSA",
238 kc_rsa_public_encrypt,
239 kc_rsa_public_decrypt,
240 kc_rsa_private_encrypt,
241 kc_rsa_private_decrypt,
253 set_private_key(hx509_context context,
254 SecKeychainItemRef itemRef,
258 hx509_private_key key;
262 ret = hx509_private_key_init(&key, NULL, NULL);
266 kc = calloc(1, sizeof(*kc));
268 _hx509_abort("out of memory");
274 _hx509_abort("out of memory");
276 /* Argh, fake modulus since OpenSSL API is on crack */
278 SecKeychainAttributeList *attrs = NULL;
283 if (rsa->n == NULL) abort();
285 ret = getAttribute(itemRef, kSecKeyKeySizeInBits, &attrs);
288 size = *(uint32_t *)attrs->attr[0].data;
289 SecKeychainItemFreeAttributesAndData(attrs, NULL);
291 kc->keysize = (size + 7) / 8;
293 data = malloc(kc->keysize);
294 memset(data, 0xe0, kc->keysize);
295 BN_bin2bn(data, kc->keysize, rsa->n);
300 RSA_set_method(rsa, &kc_rsa_pkcs1_method);
301 ret = RSA_set_app_data(rsa, kc);
303 _hx509_abort("RSA_set_app_data");
305 hx509_private_key_assign_rsa(key, rsa);
306 _hx509_cert_assign_key(cert, key);
317 SecKeychainRef keychain;
321 keychain_init(hx509_context context,
322 hx509_certs certs, void **data, int flags,
323 const char *residue, hx509_lock lock)
325 struct ks_keychain *ctx;
327 ctx = calloc(1, sizeof(*ctx));
329 hx509_clear_error_string(context);
334 if (strcasecmp(residue, "system-anchors") == 0) {
336 } else if (strncasecmp(residue, "FILE:", 5) == 0) {
339 ret = SecKeychainOpen(residue + 5, &ctx->keychain);
341 hx509_set_error_string(context, 0, ENOENT,
342 "Failed to open %s", residue);
346 hx509_set_error_string(context, 0, ENOENT,
347 "Unknown subtype %s", residue);
361 keychain_free(hx509_certs certs, void *data)
363 struct ks_keychain *ctx = data;
365 CFRelease(ctx->keychain);
366 memset(ctx, 0, sizeof(*ctx));
378 SecKeychainSearchRef searchRef;
382 keychain_iter_start(hx509_context context,
383 hx509_certs certs, void *data, void **cursor)
385 struct ks_keychain *ctx = data;
388 iter = calloc(1, sizeof(*iter));
390 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
399 ret = hx509_certs_init(context, "MEMORY:ks-file-create",
400 0, NULL, &iter->certs);
406 ret = SecTrustCopyAnchorCertificates(&anchors);
408 hx509_certs_free(&iter->certs);
410 hx509_set_error_string(context, 0, ENOMEM,
411 "Can't get trust anchors from Keychain");
414 for (i = 0; i < CFArrayGetCount(anchors); i++) {
415 SecCertificateRef cr;
419 cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, i);
421 SecCertificateGetData(cr, &cssm);
423 ret = hx509_cert_init_data(context, cssm.Data, cssm.Length, &cert);
427 ret = hx509_certs_add(context, iter->certs, cert);
428 hx509_cert_free(cert);
435 ret = hx509_certs_start_seq(context, iter->certs, &iter->cursor);
437 hx509_certs_free(&iter->certs);
444 ret = SecKeychainSearchCreateFromAttributes(ctx->keychain,
445 kSecCertificateItemClass,
450 hx509_set_error_string(context, 0, ret,
451 "Failed to start search for attributes");
465 keychain_iter(hx509_context context,
466 hx509_certs certs, void *data, void *cursor, hx509_cert *cert)
468 SecKeychainAttributeList *attrs = NULL;
469 SecKeychainAttributeInfo attrInfo;
470 UInt32 attrFormat[1] = { 0 };
471 SecKeychainItemRef itemRef;
473 struct iter *iter = cursor;
479 return hx509_certs_next_cert(context, iter->certs, iter->cursor, cert);
483 ret = SecKeychainSearchCopyNext(iter->searchRef, &itemRef);
484 if (ret == errSecItemNotFound)
490 * Pick out certificate and matching "keyid"
493 item[0] = kSecPublicKeyHashItemAttr;
497 attrInfo.format = attrFormat;
499 ret = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
504 ret = hx509_cert_init_data(context, ptr, len, cert);
509 * Find related private key if there is one by looking at
510 * kSecPublicKeyHashItemAttr == kSecKeyLabel
513 SecKeychainSearchRef search;
514 SecKeychainAttribute attrKeyid;
515 SecKeychainAttributeList attrList;
517 attrKeyid.tag = kSecKeyLabel;
518 attrKeyid.length = attrs->attr[0].length;
519 attrKeyid.data = attrs->attr[0].data;
522 attrList.attr = &attrKeyid;
524 ret = SecKeychainSearchCreateFromAttributes(NULL,
525 CSSM_DL_DB_RECORD_PRIVATE_KEY,
533 ret = SecKeychainSearchCopyNext(search, &itemRef);
535 if (ret == errSecItemNotFound) {
542 set_private_key(context, itemRef, *cert);
546 SecKeychainItemFreeAttributesAndData(attrs, ptr);
556 keychain_iter_end(hx509_context context,
561 struct iter *iter = cursor;
564 hx509_certs_end_seq(context, iter->certs, iter->cursor);
565 hx509_certs_free(&iter->certs);
567 CFRelease(iter->searchRef);
570 memset(iter, 0, sizeof(*iter));
579 struct hx509_keyset_ops keyset_keychain = {
592 #endif /* HAVE_FRAMEWORK_SECURITY */
599 _hx509_ks_keychain_register(hx509_context context)
601 #ifdef HAVE_FRAMEWORK_SECURITY
602 _hx509_ks_register(context, &keyset_keychain);