summaryrefslogtreecommitdiffstats
path: root/crypto/apple_keychain_ios.mm
blob: 74cf129ce1fd02790f390f051347bb1d60d192d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "crypto/apple_keychain.h"

#import <Foundation/Foundation.h>

#include "base/mac/foundation_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/mac/scoped_nsobject.h"

namespace {

enum KeychainAction {
  kKeychainActionCreate,
  kKeychainActionUpdate
};

// Creates a dictionary that can be used to query the keystore.
// Ownership follows the Create rule.
CFDictionaryRef CreateGenericPasswordQuery(UInt32 serviceNameLength,
                                           const char* serviceName,
                                           UInt32 accountNameLength,
                                           const char* accountName) {
  CFMutableDictionaryRef query =
      CFDictionaryCreateMutable(NULL,
                                5,
                                &kCFTypeDictionaryKeyCallBacks,
                                &kCFTypeDictionaryValueCallBacks);
  // Type of element is generic password.
  CFDictionarySetValue(query, kSecClass, kSecClassGenericPassword);

  // Set the service name.
  base::scoped_nsobject<NSString> service_name_ns(
      [[NSString alloc] initWithBytes:serviceName
                               length:serviceNameLength
                             encoding:NSUTF8StringEncoding]);
  CFDictionarySetValue(query, kSecAttrService,
                       base::mac::NSToCFCast(service_name_ns));

  // Set the account name.
  base::scoped_nsobject<NSString> account_name_ns(
      [[NSString alloc] initWithBytes:accountName
                               length:accountNameLength
                             encoding:NSUTF8StringEncoding]);
  CFDictionarySetValue(query, kSecAttrAccount,
                       base::mac::NSToCFCast(account_name_ns));

  // Use the proper search constants, return only the data of the first match.
  CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitOne);
  CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
  return query;
}

// Creates a dictionary conatining the data to save into the keychain.
// Ownership follows the Create rule.
CFDictionaryRef CreateKeychainData(UInt32 serviceNameLength,
                                   const char* serviceName,
                                   UInt32 accountNameLength,
                                   const char* accountName,
                                   UInt32 passwordLength,
                                   const void* passwordData,
                                   KeychainAction action) {
  CFMutableDictionaryRef keychain_data =
      CFDictionaryCreateMutable(NULL,
                                0,
                                &kCFTypeDictionaryKeyCallBacks,
                                &kCFTypeDictionaryValueCallBacks);

  // Set the password.
  NSData* password = [NSData dataWithBytes:passwordData length:passwordLength];
  CFDictionarySetValue(keychain_data, kSecValueData,
                       base::mac::NSToCFCast(password));

  // If this is not a creation, no structural information is needed.
  if (action != kKeychainActionCreate)
    return keychain_data;

  // Set the type of the data.
  CFDictionarySetValue(keychain_data, kSecClass, kSecClassGenericPassword);

  // Only allow access when the device has been unlocked.
  CFDictionarySetValue(keychain_data,
                       kSecAttrAccessible,
                       kSecAttrAccessibleWhenUnlocked);

  // Set the service name.
  base::scoped_nsobject<NSString> service_name_ns(
      [[NSString alloc] initWithBytes:serviceName
                               length:serviceNameLength
                             encoding:NSUTF8StringEncoding]);
  CFDictionarySetValue(keychain_data, kSecAttrService,
                       base::mac::NSToCFCast(service_name_ns));

  // Set the account name.
  base::scoped_nsobject<NSString> account_name_ns(
      [[NSString alloc] initWithBytes:accountName
                               length:accountNameLength
                             encoding:NSUTF8StringEncoding]);
  CFDictionarySetValue(keychain_data, kSecAttrAccount,
                       base::mac::NSToCFCast(account_name_ns));

  return keychain_data;
}

}  // namespace

namespace crypto {

AppleKeychain::AppleKeychain() {}

AppleKeychain::~AppleKeychain() {}

OSStatus AppleKeychain::ItemFreeContent(SecKeychainAttributeList* attrList,
                                        void* data) const {
  free(data);
  return noErr;
}

OSStatus AppleKeychain::AddGenericPassword(SecKeychainRef keychain,
                                           UInt32 serviceNameLength,
                                           const char* serviceName,
                                           UInt32 accountNameLength,
                                           const char* accountName,
                                           UInt32 passwordLength,
                                           const void* passwordData,
                                           SecKeychainItemRef* itemRef) const {
  base::ScopedCFTypeRef<CFDictionaryRef> query(CreateGenericPasswordQuery(
      serviceNameLength, serviceName, accountNameLength, accountName));
  // Check that there is not already a password.
  OSStatus status = SecItemCopyMatching(query, NULL);
  if (status == errSecItemNotFound) {
    // A new entry must be created.
    base::ScopedCFTypeRef<CFDictionaryRef> keychain_data(
        CreateKeychainData(serviceNameLength,
                           serviceName,
                           accountNameLength,
                           accountName,
                           passwordLength,
                           passwordData,
                           kKeychainActionCreate));
    status = SecItemAdd(keychain_data, NULL);
  } else if (status == noErr) {
    // The entry must be updated.
    base::ScopedCFTypeRef<CFDictionaryRef> keychain_data(
        CreateKeychainData(serviceNameLength,
                           serviceName,
                           accountNameLength,
                           accountName,
                           passwordLength,
                           passwordData,
                           kKeychainActionUpdate));
    status = SecItemUpdate(query, keychain_data);
  }

  return status;
}

OSStatus AppleKeychain::FindGenericPassword(CFTypeRef keychainOrArray,
                                            UInt32 serviceNameLength,
                                            const char* serviceName,
                                            UInt32 accountNameLength,
                                            const char* accountName,
                                            UInt32* passwordLength,
                                            void** passwordData,
                                            SecKeychainItemRef* itemRef) const {
  DCHECK((passwordData && passwordLength) ||
         (!passwordData && !passwordLength));
  base::ScopedCFTypeRef<CFDictionaryRef> query(CreateGenericPasswordQuery(
      serviceNameLength, serviceName, accountNameLength, accountName));

  // Get the keychain item containing the password.
  CFTypeRef resultRef = NULL;
  OSStatus status = SecItemCopyMatching(query, &resultRef);
  base::ScopedCFTypeRef<CFTypeRef> result(resultRef);

  if (status != noErr) {
    if (passwordData) {
      *passwordData = NULL;
      *passwordLength = 0;
    }
    return status;
  }

  if (passwordData) {
    CFDataRef data = base::mac::CFCast<CFDataRef>(result);
    NSUInteger length = CFDataGetLength(data);
    *passwordData = malloc(length * sizeof(UInt8));
    CFDataGetBytes(data, CFRangeMake(0, length), (UInt8*)*passwordData);
    *passwordLength = length;
  }
  return status;
}

}  // namespace crypto