MYKeychainItem.m
author snej@snej-mbp.mtv.corp.google.com
Tue Apr 07 10:56:58 2009 -0700 (2009-04-07)
changeset 2 8982b8fada63
parent 1 60e4cbbb5128
child 3 1dfe820d7ebe
permissions -rw-r--r--
More work, mostly on documentation.
     1 //
     2 //  MYKeychainItem.m
     3 //  MYCrypto
     4 //
     5 //  Created by Jens Alfke on 3/26/09.
     6 //  Copyright 2009 Jens Alfke. All rights reserved.
     7 //
     8 
     9 #import "MYKeychainItem.h"
    10 #import "MYCrypto_Private.h"
    11 #import "MYErrorUtils.h"
    12 
    13 
    14 NSString* const MYCSSMErrorDomain = @"CSSMErrorDomain";
    15 
    16 
    17 @implementation MYKeychainItem
    18 
    19 
    20 - (id) initWithKeychainItemRef: (MYKeychainItemRef)itemRef;
    21 {
    22     Assert(itemRef!=NULL);
    23     self = [super init];
    24     if (self != nil) {
    25         _itemRef = itemRef;
    26         CFRetain(_itemRef);
    27     }
    28     return self;
    29 }
    30 
    31 
    32 @synthesize keychainItemRef=_itemRef;
    33 
    34 - (void) dealloc
    35 {
    36     if (_itemRef) CFRelease(_itemRef);
    37     [super dealloc];
    38 }
    39 
    40 - (void) finalize
    41 {
    42     if (_itemRef) CFRelease(_itemRef);
    43     [super finalize];
    44 }
    45 
    46 - (id) copyWithZone: (NSZone*)zone {
    47     // As keys are immutable, it's not necessary to make copies of them. This makes it more efficient
    48     // to use instances as NSDictionary keys or store them in NSSets.
    49     return [self retain];
    50 }
    51 
    52 - (BOOL) isEqual: (id)obj {
    53     // Require the objects to be of the same class, so that a MYPublicKey will not be equal to a
    54     // MYKeyPair with the same public key.
    55     return (obj == self) || 
    56            ([obj class] == [self class] && CFEqual(_itemRef, [obj keychainItemRef]));
    57 }
    58 
    59 - (NSUInteger) hash {
    60     return CFHash(_itemRef);
    61 }
    62 
    63 - (NSString*) description {
    64     return $sprintf(@"%@[%p]", [self class], _itemRef);     //FIX: Can we do anything better?
    65 }
    66 
    67 
    68 - (NSArray*) _itemList {
    69     return $array((id)_itemRef);
    70 }
    71 
    72 #if MYCRYPTO_USE_IPHONE_API
    73 - (CFDictionaryRef) asQuery {
    74     return (CFDictionaryRef) $dict( {(id)kSecClass, (id)kSecClassKey},//FIX
    75                                     {(id)kSecMatchItemList, self._itemList} );
    76 }
    77 #endif
    78 
    79 
    80 - (MYKeychain*) keychain {
    81 #if MYCRYPTO_USE_IPHONE_API
    82     return [MYKeychain defaultKeychain];
    83 #else
    84     MYKeychain *keychain = nil;
    85     SecKeychainRef keychainRef = NULL;
    86     if (check(SecKeychainItemCopyKeychain((SecKeychainItemRef)_itemRef, &keychainRef), @"SecKeychainItemCopyKeychain")) {
    87         if (keychainRef) {
    88             keychain = [[[MYKeychain alloc] initWithKeychainRef: keychainRef] autorelease];
    89             CFRelease(keychainRef);
    90         }
    91     }
    92     return keychain;
    93 #endif
    94 }
    95 
    96 - (BOOL) removeFromKeychain {
    97 #if MYCRYPTO_USE_IPHONE_API
    98     return check(SecItemDelete(self.asQuery), @"SecItemDelete");
    99 #else
   100     return check(SecKeychainItemDelete((SecKeychainItemRef)_itemRef), @"SecKeychainItemDelete");
   101 #endif
   102 }
   103 
   104 
   105 #pragma mark -
   106 #pragma mark DATA / METADATA ACCESSORS:
   107 
   108 
   109 - (NSData*) _getContents: (OSStatus*)outError {
   110     NSData *contents = nil;
   111 #if MYCRYPTO_USE_IPHONE_API
   112 #else
   113 	UInt32 length = 0;
   114     void *bytes = NULL;
   115     *outError = SecKeychainItemCopyAttributesAndData(_itemRef, NULL, NULL, NULL, &length, &bytes);
   116     if (!*outError && bytes) {
   117         contents = [NSData dataWithBytes: bytes length: length];
   118         SecKeychainItemFreeAttributesAndData(NULL, bytes);
   119     }
   120 #endif
   121     return contents;
   122 }
   123 
   124 + (NSData*) _getAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item {
   125     NSData *value = nil;
   126 #if MYCRYPTO_USE_IPHONE_API
   127     NSDictionary *info = $dict( {(id)kSecClass, (id)kSecClassKey},
   128                                 {(id)kSecMatchItemList, $array((id)item)},
   129                                 {(id)kSecReturnAttributes, $true} );
   130     CFDictionaryRef attrs;
   131     if (!check(SecItemCopyMatching((CFDictionaryRef)info, (CFTypeRef*)&attrs), @"SecItemCopyMatching"))
   132         return nil;
   133     CFTypeRef rawValue = CFDictionaryGetValue(attrs,attr);
   134     value = rawValue ?[[(id)CFMakeCollectable(rawValue) retain] autorelease] :nil;
   135     CFRelease(attrs);
   136     
   137 #else
   138 	UInt32 format = kSecFormatUnknown;
   139 	SecKeychainAttributeInfo info = {.count=1, .tag=(UInt32*)&attr, .format=&format};
   140     SecKeychainAttributeList *list = NULL;
   141 	
   142     if (check(SecKeychainItemCopyAttributesAndData((SecKeychainItemRef)item, &info,
   143                                                    NULL, &list, NULL, NULL),
   144               @"SecKeychainItemCopyAttributesAndData")) {
   145         if (list) {
   146             if (list->count == 1)
   147                 value = [NSData dataWithBytes: list->attr->data
   148                                        length: list->attr->length];
   149             else if (list->count > 1)
   150                 Warn(@"Multiple values for keychain item attribute");
   151             SecKeychainItemFreeAttributesAndData(list, NULL);
   152         }
   153     }
   154 #endif
   155     return value;
   156 }
   157 
   158 + (NSString*) _getStringAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item {
   159     NSData *value = [self _getAttribute: attr ofItem: item];
   160     if (!value) return nil;
   161     const char *bytes = value.bytes;
   162     size_t length = value.length;
   163     if (length>0 && bytes[length-1] == 0)
   164         length--;           // Some values are null-terminated!?
   165     NSString *str = [[NSString alloc] initWithBytes: bytes length: length
   166                                            encoding: NSUTF8StringEncoding];
   167     if (!str)
   168         Warn(@"MYKeychainItem: Couldn't decode attr value as string");
   169     return [str autorelease];
   170 }
   171 
   172 - (NSString*) stringValueOfAttribute: (SecKeychainAttrType)attr {
   173     return [[self class] _getStringAttribute: attr ofItem: _itemRef];
   174 }
   175 
   176 
   177 + (BOOL) _setAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item
   178            stringValue: (NSString*)stringValue
   179 {
   180 #if MYCRYPTO_USE_IPHONE_API
   181     id value = stringValue ?(id)stringValue :(id)[NSNull null];
   182     NSDictionary *query = $dict({(id)kSecClass, (id)kSecClassKey},
   183                                 {(id)kSecAttrKeyType, (id)attr},
   184                                 {(id)kSecMatchItemList, $array((id)item)});
   185     NSDictionary *attrs = $dict({(id)attr, value});
   186     return check(SecItemUpdate((CFDictionaryRef)query, (CFDictionaryRef)attrs), @"SecItemUpdate");
   187     
   188 #else
   189     NSData *data = [stringValue dataUsingEncoding: NSUTF8StringEncoding];
   190     SecKeychainAttribute attribute = {.tag=attr, .length=data.length, .data=(void*)data.bytes};
   191 	SecKeychainAttributeList list = {.count=1, .attr=&attribute};
   192     return check(SecKeychainItemModifyAttributesAndData((SecKeychainItemRef)item, &list, 0, NULL),
   193                  @"SecKeychainItemModifyAttributesAndData");
   194 #endif
   195 }
   196 
   197 - (BOOL) setValue: (NSString*)valueStr ofAttribute: (SecKeychainAttrType)attr {
   198     return [[self class] _setAttribute: attr ofItem: _itemRef stringValue: valueStr];
   199 }
   200 
   201 
   202 @end
   203 
   204 
   205 
   206 
   207 BOOL check(OSStatus err, NSString *what) {
   208     if (err) {
   209 #if !MYCRYPTO_USE_IPHONE_API
   210         if (err < -2000000000)
   211             return checkcssm(err,what);
   212 #endif
   213         Warn(@"MYCrypto error, %@: %@", what, MYErrorName(NSOSStatusErrorDomain,err));
   214         return NO;
   215     } else
   216         return YES;
   217 }
   218 
   219 #if !MYCRYPTO_USE_IPHONE_API
   220 BOOL checkcssm(CSSM_RETURN err, NSString *what) {
   221     if (err != CSSM_OK) {
   222         Warn(@"MYCrypto error, %@: %@", what, MYErrorName(MYCSSMErrorDomain,err));
   223         return NO;
   224     } else
   225         return YES;
   226 }
   227 #endif