MYKeychainItem.m
author snej@snej.local
Sun Apr 12 22:16:14 2009 -0700 (2009-04-12)
changeset 9 aa5eb3fd6ebf
parent 2 8982b8fada63
child 12 e4c971be4079
permissions -rw-r--r--
Doc touch-up
     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     return (obj == self) ||
    54            ([obj isKindOfClass: [MYKeychainItem class]] && CFEqual(_itemRef, [obj keychainItemRef]));
    55 }
    56 
    57 - (NSUInteger) hash {
    58     return CFHash(_itemRef);
    59 }
    60 
    61 - (NSString*) description {
    62     return $sprintf(@"%@[%p]", [self class], _itemRef);     //FIX: Can we do anything better?
    63 }
    64 
    65 
    66 - (NSArray*) _itemList {
    67     return $array((id)_itemRef);
    68 }
    69 
    70 #if MYCRYPTO_USE_IPHONE_API
    71 - (CFDictionaryRef) asQuery {
    72     return (CFDictionaryRef) $dict( {(id)kSecClass, (id)kSecClassKey},//FIX
    73                                     {(id)kSecMatchItemList, self._itemList} );
    74 }
    75 #endif
    76 
    77 
    78 - (MYKeychain*) keychain {
    79 #if MYCRYPTO_USE_IPHONE_API
    80     return [MYKeychain defaultKeychain];
    81 #else
    82     MYKeychain *keychain = nil;
    83     SecKeychainRef keychainRef = NULL;
    84     if (check(SecKeychainItemCopyKeychain((SecKeychainItemRef)_itemRef, &keychainRef), @"SecKeychainItemCopyKeychain")) {
    85         if (keychainRef) {
    86             keychain = [[[MYKeychain alloc] initWithKeychainRef: keychainRef] autorelease];
    87             CFRelease(keychainRef);
    88         }
    89     }
    90     return keychain;
    91 #endif
    92 }
    93 
    94 - (BOOL) removeFromKeychain {
    95 #if MYCRYPTO_USE_IPHONE_API
    96     return check(SecItemDelete(self.asQuery), @"SecItemDelete");
    97 #else
    98     return check(SecKeychainItemDelete((SecKeychainItemRef)_itemRef), @"SecKeychainItemDelete");
    99 #endif
   100 }
   101 
   102 
   103 #pragma mark -
   104 #pragma mark DATA / METADATA ACCESSORS:
   105 
   106 
   107 - (NSData*) _getContents: (OSStatus*)outError {
   108     NSData *contents = nil;
   109 #if MYCRYPTO_USE_IPHONE_API
   110 #else
   111 	UInt32 length = 0;
   112     void *bytes = NULL;
   113     *outError = SecKeychainItemCopyAttributesAndData(_itemRef, NULL, NULL, NULL, &length, &bytes);
   114     if (!*outError && bytes) {
   115         contents = [NSData dataWithBytes: bytes length: length];
   116         SecKeychainItemFreeAttributesAndData(NULL, bytes);
   117     }
   118 #endif
   119     return contents;
   120 }
   121 
   122 + (NSData*) _getAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item {
   123     NSData *value = nil;
   124 #if MYCRYPTO_USE_IPHONE_API
   125     NSDictionary *info = $dict( {(id)kSecClass, (id)kSecClassKey},
   126                                 {(id)kSecMatchItemList, $array((id)item)},
   127                                 {(id)kSecReturnAttributes, $true} );
   128     CFDictionaryRef attrs;
   129     if (!check(SecItemCopyMatching((CFDictionaryRef)info, (CFTypeRef*)&attrs), @"SecItemCopyMatching"))
   130         return nil;
   131     CFTypeRef rawValue = CFDictionaryGetValue(attrs,attr);
   132     value = rawValue ?[[(id)CFMakeCollectable(rawValue) retain] autorelease] :nil;
   133     CFRelease(attrs);
   134     
   135 #else
   136 	UInt32 format = kSecFormatUnknown;
   137 	SecKeychainAttributeInfo info = {.count=1, .tag=(UInt32*)&attr, .format=&format};
   138     SecKeychainAttributeList *list = NULL;
   139 	
   140     if (check(SecKeychainItemCopyAttributesAndData((SecKeychainItemRef)item, &info,
   141                                                    NULL, &list, NULL, NULL),
   142               @"SecKeychainItemCopyAttributesAndData")) {
   143         if (list) {
   144             if (list->count == 1)
   145                 value = [NSData dataWithBytes: list->attr->data
   146                                        length: list->attr->length];
   147             else if (list->count > 1)
   148                 Warn(@"Multiple values for keychain item attribute");
   149             SecKeychainItemFreeAttributesAndData(list, NULL);
   150         }
   151     }
   152 #endif
   153     return value;
   154 }
   155 
   156 + (NSString*) _getStringAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item {
   157     NSData *value = [self _getAttribute: attr ofItem: item];
   158     if (!value) return nil;
   159     const char *bytes = value.bytes;
   160     size_t length = value.length;
   161     if (length>0 && bytes[length-1] == 0)
   162         length--;           // Some values are null-terminated!?
   163     NSString *str = [[NSString alloc] initWithBytes: bytes length: length
   164                                            encoding: NSUTF8StringEncoding];
   165     if (!str)
   166         Warn(@"MYKeychainItem: Couldn't decode attr value as string");
   167     return [str autorelease];
   168 }
   169 
   170 - (NSString*) stringValueOfAttribute: (SecKeychainAttrType)attr {
   171     return [[self class] _getStringAttribute: attr ofItem: _itemRef];
   172 }
   173 
   174 
   175 + (BOOL) _setAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item
   176            stringValue: (NSString*)stringValue
   177 {
   178 #if MYCRYPTO_USE_IPHONE_API
   179     id value = stringValue ?(id)stringValue :(id)[NSNull null];
   180     NSDictionary *query = $dict({(id)kSecClass, (id)kSecClassKey},
   181                                 {(id)kSecAttrKeyType, (id)attr},
   182                                 {(id)kSecMatchItemList, $array((id)item)});
   183     NSDictionary *attrs = $dict({(id)attr, value});
   184     return check(SecItemUpdate((CFDictionaryRef)query, (CFDictionaryRef)attrs), @"SecItemUpdate");
   185     
   186 #else
   187     NSData *data = [stringValue dataUsingEncoding: NSUTF8StringEncoding];
   188     SecKeychainAttribute attribute = {.tag=attr, .length=data.length, .data=(void*)data.bytes};
   189 	SecKeychainAttributeList list = {.count=1, .attr=&attribute};
   190     return check(SecKeychainItemModifyAttributesAndData((SecKeychainItemRef)item, &list, 0, NULL),
   191                  @"SecKeychainItemModifyAttributesAndData");
   192 #endif
   193 }
   194 
   195 - (BOOL) setValue: (NSString*)valueStr ofAttribute: (SecKeychainAttrType)attr {
   196     return [[self class] _setAttribute: attr ofItem: _itemRef stringValue: valueStr];
   197 }
   198 
   199 
   200 @end
   201 
   202 
   203 
   204 
   205 BOOL check(OSStatus err, NSString *what) {
   206     if (err) {
   207 #if !MYCRYPTO_USE_IPHONE_API
   208         if (err < -2000000000)
   209             return checkcssm(err,what);
   210 #endif
   211         Warn(@"MYCrypto error, %@: %@", what, MYErrorName(NSOSStatusErrorDomain,err));
   212         return NO;
   213     } else
   214         return YES;
   215 }
   216 
   217 #if !MYCRYPTO_USE_IPHONE_API
   218 BOOL checkcssm(CSSM_RETURN err, NSString *what) {
   219     if (err != CSSM_OK) {
   220         Warn(@"MYCrypto error, %@: %@", what, MYErrorName(MYCSSMErrorDomain,err));
   221         return NO;
   222     } else
   223         return YES;
   224 }
   225 #endif