Strings simplification for translations
[vlc.git] / modules / keystore / keychain.m
blob9f4908cc8c1b4ab1d39f4326b46ca1a2ce7453e4
1 /*****************************************************************************
2  * keychain.m: Darwin Keychain keystore module
3  *****************************************************************************
4  * Copyright © 2016 VLC authors, VideoLAN and VideoLabs
5  *
6  * Author: Felix Paul Kühne <fkuehne # videolabs.io>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 2.1 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"
25 #endif
27 #include <vlc_common.h>
28 #include <vlc_plugin.h>
29 #include <vlc_keystore.h>
31 #import <Foundation/Foundation.h>
32 #import <Security/Security.h>
33 #import <Cocoa/Cocoa.h>
35 static int Open(vlc_object_t *);
37 static const int sync_list[] =
38 { 0, 1, 2 };
39 static const char *const sync_list_text[] = {
40     N_("Yes"), N_("No"), N_("Any")
43 static const int accessibility_list[] =
44 { 0, 1, 2, 3, 4, 5, 6, 7 };
45 static const char *const accessibility_list_text[] = {
46     N_("System default"),
47     N_("After first unlock"),
48     N_("After first unlock, on this device only"),
49     N_("Always"),
50     N_("When passcode set, on this device only"),
51     N_("Always, on this device only"),
52     N_("When unlocked"),
53     N_("When unlocked, on this device only")
56 #define SYNC_ITEMS_TEXT N_("Synchronize stored items")
57 #define SYNC_ITEMS_LONGTEXT N_("Synchronizes stored items via iCloud Keychain if enabled in the user domain.")
59 #define ACCESSIBILITY_TYPE_TEXT N_("Accessibility type for all future passwords saved to the Keychain")
61 #define ACCESS_GROUP_TEXT N_("Keychain access group")
62 #define ACCESS_GROUP_LONGTEXT N_("Keychain access group as defined by the app entitlements.")
64 /* VLC can be compiled against older SDKs (like before OS X 10.10)
65  * but newer features should still be available.
66  * Hence, re-define things as needed */
67 #ifndef kSecAttrSynchronizable
68 #define kSecAttrSynchronizable CFSTR("sync")
69 #endif
71 #ifndef kSecAttrSynchronizableAny
72 #define kSecAttrSynchronizableAny CFSTR("syna")
73 #endif
75 #ifndef kSecAttrAccessGroup
76 #define kSecAttrAccessGroup CFSTR("agrp")
77 #endif
79 #ifndef kSecAttrAccessibleAfterFirstUnlock
80 #define kSecAttrAccessibleAfterFirstUnlock CFSTR("ck")
81 #endif
83 #ifndef kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
84 #define kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly CFSTR("cku")
85 #endif
87 #ifndef kSecAttrAccessibleAlways
88 #define kSecAttrAccessibleAlways CFSTR("dk")
89 #endif
91 #ifndef kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
92 #define kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly CFSTR("akpu")
93 #endif
95 #ifndef kSecAttrAccessibleAlwaysThisDeviceOnly
96 #define kSecAttrAccessibleAlwaysThisDeviceOnly CFSTR("dku")
97 #endif
99 #ifndef kSecAttrAccessibleWhenUnlocked
100 #define kSecAttrAccessibleWhenUnlocked CFSTR("ak")
101 #endif
103 #ifndef kSecAttrAccessibleWhenUnlockedThisDeviceOnly
104 #define kSecAttrAccessibleWhenUnlockedThisDeviceOnly CFSTR("aku")
105 #endif
107 vlc_module_begin()
108     set_shortname(N_("Keychain keystore"))
109     set_description(N_("Keystore for iOS, Mac OS X and tvOS"))
110     set_category(CAT_ADVANCED)
111     set_subcategory(SUBCAT_ADVANCED_MISC)
112     add_integer("keychain-synchronize", 1, SYNC_ITEMS_TEXT, SYNC_ITEMS_LONGTEXT, true)
113     change_integer_list(sync_list, sync_list_text)
114     add_integer("keychain-accessibility-type", 0, ACCESSIBILITY_TYPE_TEXT, ACCESSIBILITY_TYPE_TEXT, true)
115     change_integer_list(accessibility_list, accessibility_list_text)
116     add_string("keychain-access-group", NULL, ACCESS_GROUP_TEXT, ACCESS_GROUP_LONGTEXT, true)
117     set_capability("keystore", 100)
118     set_callbacks(Open, NULL)
119 vlc_module_end ()
121 static NSMutableDictionary * CreateQuery(vlc_keystore *p_keystore)
123     NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:3];
124     [dictionary setObject:(__bridge id)kSecClassInternetPassword forKey:(__bridge id)kSecClass];
126     [dictionary setObject:@"VLC-Password-Service" forKey:(__bridge id)kSecAttrService];
128     const char * psz_access_group = var_InheritString(p_keystore, "keychain-access-group");
129     if (psz_access_group) {
130         [dictionary setObject:[NSString stringWithUTF8String:psz_access_group] forKey:(__bridge id)kSecAttrAccessGroup];
131     }
133     id syncValue;
134     int syncMode = var_InheritInteger(p_keystore, "keychain-synchronize");
136     if (syncMode == 2) {
137         syncValue = (__bridge id)kSecAttrSynchronizableAny;
138     } else if (syncMode == 0) {
139         syncValue = @(YES);
140     } else {
141         syncValue = @(NO);
142     }
144     [dictionary setObject:syncValue forKey:(__bridge id)(kSecAttrSynchronizable)];
146     return dictionary;
149 static NSString * ErrorForStatus(OSStatus status)
151     NSString *message = nil;
153     switch (status) {
154 #if TARGET_OS_IPHONE
155         case errSecUnimplemented: {
156             message = @"Query unimplemented";
157             break;
158         }
159         case errSecParam: {
160             message = @"Faulty parameter";
161             break;
162         }
163         case errSecAllocate: {
164             message = @"Allocation failure";
165             break;
166         }
167         case errSecNotAvailable: {
168             message = @"Query not available";
169             break;
170         }
171         case errSecDuplicateItem: {
172             message = @"Duplicated item";
173             break;
174         }
175         case errSecItemNotFound: {
176             message = @"Item not found";
177             break;
178         }
179         case errSecInteractionNotAllowed: {
180             message = @"Interaction not allowed";
181             break;
182         }
183         case errSecDecode: {
184             message = @"Decoding failure";
185             break;
186         }
187         case errSecAuthFailed: {
188             message = @"Authentication failure";
189             break;
190         }
191         case -34018: {
192             message = @"iCloud Keychain failure";
193             break;
194         }
195         default: {
196             message = @"Unknown generic error";
197         }
198 #else
199         default:
200             message = (__bridge_transfer NSString *)SecCopyErrorMessageString(status, NULL);
201 #endif
202     }
204     return message;
207 #define OSX_MAVERICKS (NSAppKitVersionNumber >= 1265)
208 extern const CFStringRef kSecAttrAccessible;
210 #pragma clang diagnostic push
211 #pragma clang diagnostic ignored "-Wpartial-availability"
212 static void SetAccessibilityForQuery(vlc_keystore *p_keystore,
213                                      NSMutableDictionary *query)
215     if (!OSX_MAVERICKS)
216         return;
218     int accessibilityType = var_InheritInteger(p_keystore, "keychain-accessibility-type");
219     switch (accessibilityType) {
220         case 1:
221             [query setObject:(__bridge id)kSecAttrAccessibleAfterFirstUnlock forKey:(__bridge id)kSecAttrAccessible];
222             break;
223         case 2:
224             [query setObject:(__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
225             break;
226         case 3:
227             [query setObject:(__bridge id)kSecAttrAccessibleAlways forKey:(__bridge id)kSecAttrAccessible];
228             break;
229         case 4:
230             [query setObject:(__bridge id)kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
231             break;
232         case 5:
233             [query setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
234             break;
235         case 6:
236             [query setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
237             break;
238         case 7:
239             [query setObject:(__bridge id)kSecAttrAccessibleWhenUnlockedThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
240             break;
241         default:
242             break;
243     }
245 #pragma clang diagnostic pop
247 static void SetAttributesForQuery(const char *const ppsz_values[KEY_MAX], NSMutableDictionary *query, const char *psz_label)
249     const char *psz_protocol = ppsz_values[KEY_PROTOCOL];
250     const char *psz_user = ppsz_values[KEY_USER];
251     const char *psz_server = ppsz_values[KEY_SERVER];
252     const char *psz_path = ppsz_values[KEY_PATH];
253     const char *psz_port = ppsz_values[KEY_PORT];
255     if (psz_label) {
256         [query setObject:[NSString stringWithUTF8String:psz_label] forKey:(__bridge id)kSecAttrLabel];
257     }
258     if (psz_protocol) {
259         [query setObject:[NSString stringWithUTF8String:psz_protocol] forKey:(__bridge id)kSecAttrProtocol];
260     }
261     if (psz_user) {
262         [query setObject:[NSString stringWithUTF8String:psz_user] forKey:(__bridge id)kSecAttrAccount];
263     }
264     if (psz_server) {
265         [query setObject:[NSString stringWithUTF8String:psz_server] forKey:(__bridge id)kSecAttrServer];
266     }
267     if (psz_path) {
268         [query setObject:[NSString stringWithUTF8String:psz_path] forKey:(__bridge id)kSecAttrPath];
269     }
270     if (psz_port) {
271         [query setObject:[NSString stringWithUTF8String:psz_port] forKey:(__bridge id)kSecAttrPort];
272     }
275 static int CopyEntryValues(const char * ppsz_dst[KEY_MAX], const char *const ppsz_src[KEY_MAX])
277     for (unsigned int i = 0; i < KEY_MAX; ++i)
278     {
279         if (ppsz_src[i])
280         {
281             ppsz_dst[i] = strdup(ppsz_src[i]);
282             if (!ppsz_dst[i])
283                 return VLC_EGENERIC;
284         }
285     }
286     return VLC_SUCCESS;
289 static int Store(vlc_keystore *p_keystore,
290                  const char *const ppsz_values[KEY_MAX],
291                  const uint8_t *p_secret,
292                  size_t i_secret_len,
293                  const char *psz_label)
295     OSStatus status;
297     if (!ppsz_values[KEY_PROTOCOL] || !p_secret) {
298         return VLC_EGENERIC;
299     }
301     NSMutableDictionary *query = nil;
302     NSMutableDictionary *searchQuery = CreateQuery(p_keystore);
304     /* set attributes */
305     SetAttributesForQuery(ppsz_values, searchQuery, psz_label);
307     /* search */
308     status = SecItemCopyMatching((__bridge CFDictionaryRef)searchQuery, nil);
310     /* create storage unit */
311     NSData *secretData = [[NSString stringWithFormat:@"%s", p_secret] dataUsingEncoding:NSUTF8StringEncoding];
313     if (status == errSecSuccess) {
314         /* item already existed in keychain, let's update */
315         query = [[NSMutableDictionary alloc] init];
317         /* just set the secret data */
318         [query setObject:secretData forKey:(__bridge id)kSecValueData];
320         status = SecItemUpdate((__bridge CFDictionaryRef)(searchQuery), (__bridge CFDictionaryRef)(query));
321     } else if (status == errSecItemNotFound) {
322         /* item not found, let's create! */
323         query = CreateQuery(p_keystore);
325         /* set attributes */
326         SetAttributesForQuery(ppsz_values, query, psz_label);
328         /* set accessibility */
329         SetAccessibilityForQuery(p_keystore, query);
331         /* set secret data */
332         [query setObject:secretData forKey:(__bridge id)kSecValueData];
334         status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
335     }
336     if (status != errSecSuccess) {
337         msg_Err(p_keystore, "Storage failed (%i: '%s')", status, [ErrorForStatus(status) UTF8String]);
338         return VLC_EGENERIC;
339     }
341     return VLC_SUCCESS;
344 static unsigned int Find(vlc_keystore *p_keystore,
345                          const char *const ppsz_values[KEY_MAX],
346                          vlc_keystore_entry **pp_entries)
348     CFTypeRef result = NULL;
350     NSMutableDictionary *query = CreateQuery(p_keystore);
351     [query setObject:@(YES) forKey:(__bridge id)kSecReturnRef];
352     [query setObject:(__bridge id)kSecMatchLimitAll forKey:(__bridge id)kSecMatchLimit];
354     /* set attributes */
355     SetAttributesForQuery(ppsz_values, query, NULL);
357     /* search */
358     OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
360     if (status != errSecSuccess) {
361         msg_Warn(p_keystore, "lookup failed (%i: '%s')", status, [ErrorForStatus(status) UTF8String]);
362         return 0;
363     }
365     NSArray *listOfResults = (__bridge_transfer NSArray *)result;
367     NSUInteger count = listOfResults.count;
369     vlc_keystore_entry *p_entries = calloc(count,
370                                            sizeof(vlc_keystore_entry));
371     if (!p_entries)
372         return 0;
374     for (NSUInteger i = 0; i < count; i++) {
375         vlc_keystore_entry *p_entry = &p_entries[i];
376         if (CopyEntryValues((const char **)p_entry->ppsz_values, (const char *const*)ppsz_values) != VLC_SUCCESS) {
377             vlc_keystore_release_entries(p_entries, 1);
378             return 0;
379         }
381         SecKeychainItemRef itemRef = (__bridge SecKeychainItemRef)([listOfResults objectAtIndex:i]);
383         SecKeychainAttributeInfo attrInfo;
385 #ifndef NDEBUG
386         attrInfo.count = 1;
387         UInt32 tags[1] = {kSecAccountItemAttr}; //, kSecAccountItemAttr, kSecServerItemAttr, kSecPortItemAttr, kSecProtocolItemAttr, kSecPathItemAttr};
388         attrInfo.tag = tags;
389         attrInfo.format = NULL;
390 #endif
392         SecKeychainAttributeList *attrList = NULL;
394         UInt32 dataLength;
395         void * data;
397         status = SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL, &attrList, &dataLength, &data);
399         if (status != noErr) {
400             msg_Err(p_keystore, "Lookup error: %i (%s)", status, [ErrorForStatus(status) UTF8String]);
401             vlc_keystore_release_entries(p_entries, count);
402             return 0;
403         }
405 #ifndef NDEBUG
406         for (unsigned x = 0; x < attrList->count; x++) {
407             SecKeychainAttribute *attr = &attrList->attr[i];
408             switch (attr->tag) {
409                 case kSecLabelItemAttr:
410                     NSLog(@"label %@", [[NSString alloc] initWithBytes:attr->data length:attr->length encoding:NSUTF8StringEncoding]);
411                     break;
412                 case kSecAccountItemAttr:
413                     NSLog(@"account %@", [[NSString alloc] initWithBytes:attr->data length:attr->length encoding:NSUTF8StringEncoding]);
414                     break;
415                 default:
416                     break;
417             }
418         }
419 #endif
421         /* we need to do some padding here, as string is expected to be 0 terminated */
422         uint8_t *retData = calloc(1, dataLength + 1);
423         memcpy(retData, data, dataLength);
425         vlc_keystore_entry_set_secret(p_entry, retData, dataLength + 1);
427         free(retData);
428         SecKeychainItemFreeAttributesAndData(attrList, data);
429     }
431     *pp_entries = p_entries;
433     return count;
436 static unsigned int Remove(vlc_keystore *p_keystore,
437                            const char *const ppsz_values[KEY_MAX])
439     OSStatus status;
441     NSMutableDictionary *query = CreateQuery(p_keystore);
443     SetAttributesForQuery(ppsz_values, query, NULL);
445     CFTypeRef result = NULL;
446     [query setObject:@(YES) forKey:(__bridge id)kSecReturnRef];
447     [query setObject:(__bridge id)kSecMatchLimitAll forKey:(__bridge id)kSecMatchLimit];
449     BOOL failed = NO;
450     status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
452     NSUInteger matchCount = 0;
454     if (status == errSecSuccess) {
455         NSArray *matches = (__bridge_transfer NSArray *)result;
456         matchCount = matches.count;
458         for (NSUInteger x = 0; x < matchCount; x++) {
459             status = SecKeychainItemDelete((__bridge SecKeychainItemRef _Nonnull)([matches objectAtIndex:x]));
460             if (status != noErr) {
461                 msg_Err(p_keystore, "Deletion error %i (%s)", status , [ErrorForStatus(status) UTF8String]);
462                 failed = YES;
463             }
464         }
465     } else {
466         msg_Err(p_keystore, "Lookup error for deletion %i (%s)", status, [ErrorForStatus(status) UTF8String]);
467         return VLC_EGENERIC;
468     }
470     if (failed)
471         return VLC_EGENERIC;
473     return matchCount;
476 static int Open(vlc_object_t *p_this)
478     vlc_keystore *p_keystore = (vlc_keystore *)p_this;
480     p_keystore->p_sys = NULL;
481     p_keystore->pf_store = Store;
482     p_keystore->pf_find = Find;
483     p_keystore->pf_remove = Remove;
485     return VLC_SUCCESS;