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