Coder Social home page Coder Social logo

square / valet Goto Github PK

View Code? Open in Web Editor NEW
4.0K 81.0 218.0 1.11 MB

Valet lets you securely store data in the iOS, tvOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy. We promise.

License: Apache License 2.0

Objective-C 31.40% Ruby 0.22% Swift 67.58% Shell 0.31% C 0.50%
keychain touch-id face-id security ios tvos watchos macos crypto

valet's Introduction

Valet

CI Status Swift Package Manager compatible Carthage Compatibility codecov Version License Platform

Valet lets you securely store data in the iOS, tvOS, watchOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy. We promise.

Getting Started

CocoaPods

Install with CocoaPods by adding the following to your Podfile:

on iOS:

platform :ios, '9.0'
use_frameworks!
pod 'Valet'

on tvOS:

platform :tvos, '9.0'
use_frameworks!
pod 'Valet'

on watchOS:

platform :watchos, '2.0'
use_frameworks!
pod 'Valet'

on macOS:

platform :osx, '10.11'
use_frameworks!
pod 'Valet'

Carthage

Install with Carthage by adding the following to your Cartfile:

github "Square/Valet"

Run carthage to build the framework and drag the built Valet.framework into your Xcode project.

Swift Package Manager

Install with Swift Package Manager by adding the following to your Package.swift:

dependencies: [
    .package(url: "https://github.com/Square/Valet", from: "4.0.0"),
],

Submodules

Or manually checkout the submodule with git submodule add [email protected]:Square/Valet.git, drag Valet.xcodeproj to your project, and add Valet as a build dependency.

Usage

Prefer to learn via watching a video? Check out this video tutorial.

Basic Initialization

let myValet = Valet.valet(with: Identifier(nonEmpty: "Druidia")!, accessibility: .whenUnlocked)
VALValet *const myValet = [VALValet valetWithIdentifier:@"Druidia" accessibility:VALAccessibilityWhenUnlocked];

To begin storing data securely using Valet, you need to create a Valet instance with:

  • An identifier – a non-empty string that is used to identify this Valet. The Swift API uses an Identifier wrapper class to enforce the non-empty constraint.
  • An accessibility value – an enum (Accessibility) that defines when you will be able to persist and retrieve data.

This myValet instance can be used to store and retrieve data securely on this device, but only when the device is unlocked.

Choosing the Best Identifier

The identifier you choose for your Valet is used to create a sandbox for the data your Valet writes to the keychain. Two Valets of the same type created via the same initializer, accessibility value, and identifier will be able to read and write the same key:value pairs; Valets with different identifiers each have their own sandbox. Choose an identifier that describes the kind of data your Valet will protect. You do not need to include your application name or bundle identifier in your Valet’s identifier.

Choosing a User-friendly Identifier on macOS

let myValet = Valet.valet(withExplicitlySet: Identifier(nonEmpty: "Druidia")!, accessibility: .whenUnlocked)
VALValet *const myValet = [VALValet valetWithExplicitlySetIdentifier:@"Druidia" accessibility:VALAccessibilityWhenUnlocked];

Mac apps signed with a developer ID may see their Valet’s identifier shown to their users. ⚠️⚠️ While it is possible to explicitly set a user-friendly identifier, note that doing so bypasses this project’s guarantee that one Valet type will not have access to one another type’s key:value pairs ⚠️⚠️. To maintain this guarantee, ensure that each Valet’s identifier is globally unique.

Choosing the Best Accessibility Value

The Accessibility enum is used to determine when your secrets can be accessed. It’s a good idea to use the strictest accessibility possible that will allow your app to function. For example, if your app does not run in the background you will want to ensure the secrets can only be read when the phone is unlocked by using .whenUnlocked or .whenUnlockedThisDeviceOnly.

Changing an Accessibility Value After Persisting Data

let myOldValet = Valet.valet(withExplicitlySet: Identifier(nonEmpty: "Druidia")!, accessibility: .whenUnlocked)
let myNewValet = Valet.valet(withExplicitlySet: Identifier(nonEmpty: "Druidia")!, accessibility: .afterFirstUnlock)
try? myNewValet.migrateObjects(from: myOldValet, removeOnCompletion: true)
VALValet *const myOldValet = [VALValet valetWithExplicitlySetIdentifier:@"Druidia" accessibility:VALAccessibilityWhenUnlocked];
VALValet *const myNewValet = [VALValet valetWithExplicitlySetIdentifier:@"Druidia" accessibility:VALAccessibilityAfterFirstUnlock];
[myNewValet migrateObjectsFrom:myOldValet removeOnCompletion:true error:nil];

The Valet type, identifier, accessibility value, and initializer chosen to create a Valet are combined to create a sandbox within the keychain. This behavior ensures that different Valets can not read or write one another's key:value pairs. If you change a Valet's accessibility after persisting key:value pairs, you must migrate the key:value pairs from the Valet with the no-longer-desired accessibility to the Valet with the desired accessibility to avoid data loss.

Reading and Writing

let username = "Skroob"
try? myValet.setString("12345", forKey: username)
let myLuggageCombination = myValet.string(forKey: username)
NSString *const username = @"Skroob";
[myValet setString:@"12345" forKey:username error:nil];
NSString *const myLuggageCombination = [myValet stringForKey:username error:nil];

In addition to allowing the storage of strings, Valet allows the storage of Data objects via setObject(_ object: Data, forKey key: Key) and object(forKey key: String). Valets created with a different class type, via a different initializer, or with a different accessibility attribute will not be able to read or modify values in myValet.

Sharing Secrets Among Multiple Applications Using a Keychain Sharing Entitlement

let mySharedValet = Valet.sharedGroupValet(with: SharedGroupIdentifier(appIDPrefix: "AppID12345", nonEmptyGroup: "Druidia")!, accessibility: .whenUnlocked)
VALValet *const mySharedValet = [VALValet sharedGroupValetWithAppIDPrefix:@"AppID12345" sharedGroupIdentifier:@"Druidia" accessibility:VALAccessibilityWhenUnlocked];

This instance can be used to store and retrieve data securely across any app written by the same developer that has AppID12345.Druidia (or $(AppIdentifierPrefix)Druidia) set as a value for the keychain-access-groups key in the app’s Entitlements, where AppID12345 is the application’s App ID prefix. This Valet is accessible when the device is unlocked. Note that myValet and mySharedValet can not read or modify one another’s values because the two Valets were created with different initializers. All Valet types can share secrets across applications written by the same developer by using the sharedGroupValet initializer.

Sharing Secrets Among Multiple Applications Using an App Groups Entitlement

let mySharedValet = Valet.sharedGroupValet(with: SharedGroupIdentifier(groupPrefix: "group", nonEmptyGroup: "Druidia")!, accessibility: .whenUnlocked)
VALValet *const mySharedValet = [VALValet sharedGroupValetWithGroupPrefix:@"group" sharedGroupIdentifier:@"Druidia" accessibility:VALAccessibilityWhenUnlocked];

This instance can be used to store and retrieve data securely across any app written by the same developer that has group.Druidia set as a value for the com.apple.security.application-groups key in the app’s Entitlements. This Valet is accessible when the device is unlocked. Note that myValet and mySharedValet cannot read or modify one another’s values because the two Valets were created with different initializers. All Valet types can share secrets across applications written by the same developer by using the sharedGroupValet initializer. Note that on macOS, the groupPrefix must be the App ID prefix.

As with Valets, shared iCloud Valets can be created with an additional identifier, allowing multiple independently sandboxed keychains to exist within the same shared group.

Sharing Secrets Across Devices with iCloud

let myCloudValet = Valet.iCloudValet(with: Identifier(nonEmpty: "Druidia")!, accessibility: .whenUnlocked)
VALValet *const myCloudValet = [VALValet iCloudValetWithIdentifier:@"Druidia" accessibility:VALAccessibilityWhenUnlocked];

This instance can be used to store and retrieve data that can be retrieved by this app on other devices logged into the same iCloud account with iCloud Keychain enabled. If iCloud Keychain is not enabled on this device, secrets can still be read and written, but will not sync to other devices. Note that myCloudValet can not read or modify values in either myValet or mySharedValet because myCloudValet was created a different initializer.

Shared iCloud Valets can be created with an additional identifier, allowing multiple independently sandboxed keychains to exist within the same iCloud shared group.

Protecting Secrets with Face ID, Touch ID, or device Passcode

let mySecureEnclaveValet = SecureEnclaveValet.valet(with: Identifier(nonEmpty: "Druidia")!, accessControl: .userPresence)
VALSecureEnclaveValet *const mySecureEnclaveValet = [VALSecureEnclaveValet valetWithIdentifier:@"Druidia" accessControl:VALAccessControlUserPresence];

This instance can be used to store and retrieve data in the Secure Enclave. Each time data is retrieved from this Valet, the user will be prompted to confirm their presence via Face ID, Touch ID, or by entering their device passcode. If no passcode is set on the device, this instance will be unable to access or store data. Data is removed from the Secure Enclave when the user removes a passcode from the device. Storing data using SecureEnclaveValet is the most secure way to store data on iOS, tvOS, watchOS, and macOS.

let mySecureEnclaveValet = SinglePromptSecureEnclaveValet.valet(with: Identifier(nonEmpty: "Druidia")!, accessControl: .userPresence)
VALSinglePromptSecureEnclaveValet *const mySecureEnclaveValet = [VALSinglePromptSecureEnclaveValet valetWithIdentifier:@"Druidia" accessControl:VALAccessControlUserPresence];

This instance also stores and retrieves data in the Secure Enclave, but does not require the user to confirm their presence each time data is retrieved. Instead, the user will be prompted to confirm their presence only on the first data retrieval. A SinglePromptSecureEnclaveValet instance can be forced to prompt the user on the next data retrieval by calling the instance method requirePromptOnNextAccess().

In order for your customers not to receive a prompt that your app does not yet support Face ID, you must set a value for the Privacy - Face ID Usage Description (NSFaceIDUsageDescription) key in your app’s Info.plist.

Thread Safety

Valet is built to be thread safe: it is possible to use a Valet instance on any queue or thread. Valet instances ensure that code that talks to the Keychain is atomic – it is impossible to corrupt data in Valet by reading and writing on multiple queues simultaneously.

However, because the Keychain is effectively disk storage, there is no guarantee that reading and writing items is fast - accessing a Valet instance from the main queue can result in choppy animations or blocked UI. As a result, we recommend utilizing your Valet instance on a background queue; treat Valet like you treat other code that reads from and writes to disk.

Migrating Existing Keychain Values into Valet

Already using the Keychain and no longer want to maintain your own Keychain code? We feel you. That’s why we wrote migrateObjects(matching query: [String : AnyHashable], removeOnCompletion: Bool). This method allows you to migrate all your existing Keychain entries to a Valet instance in one line. Just pass in a Dictionary with the kSecClass, kSecAttrService, and any other kSecAttr* attributes you use – we’ll migrate the data for you. If you need more control over how your data is migrated, use migrateObjects(matching query: [String : AnyHashable], compactMap: (MigratableKeyValuePair<AnyHashable>) throws -> MigratableKeyValuePair<String>?) to filter or remap key:value pairs as part of your migration.

Integrating Valet into a macOS application

Your macOS application must have the Keychain Sharing entitlement in order to use Valet, even if your application does not intend to share keychain data between applications. For instructions on how to add a Keychain Sharing entitlement to your application, read Apple's documentation on the subject. For more information on why this requirement exists, see issue #213.

If your macOS application supports macOS 10.14 or prior, you must run myValet.migrateObjectsFromPreCatalina() before reading values from a Valet. macOS Catalina introduced a breaking change to the macOS keychain, requiring that macOS keychain items that utilize kSecAttrAccessible or kSecAttrAccessGroup set kSecUseDataProtectionKeychain to true when writing or accessing these items. Valet’s migrateObjectsFromPreCatalina() upgrades items entered into the keychain on older macOS devices or other operating systems to include the key:value pair kSecUseDataProtectionKeychain:true. Note that Valets that share keychain items between devices with iCloud are exempt from this requirement. Similarly, SecureEnclaveValet and SinglePromptSecureEnclaveValet are exempt from this requirement.

Debugging

Valet guarantees that reading and writing operations will succeed as long as written data is valid and canAccessKeychain() returns true. There are only a few cases that can lead to the keychain being inaccessible:

  1. Using the wrong Accessibility for your use case. Examples of improper use include using .whenPasscodeSetThisDeviceOnly when there is no passcode set on the device, or using .whenUnlocked when running in the background.
  2. Initializing a Valet with shared access group Valet when the shared access group identifier is not in your entitlements file.
  3. Using SecureEnclaveValet on an iOS device that doesn’t have a Secure Enclave. The Secure Enclave was introduced with the A7 chip, which first appeared in the iPhone 5S, iPad Air, and iPad Mini 2.
  4. Running your app in DEBUG from Xcode. Xcode sometimes does not properly sign your app, which causes a failure to access keychain due to entitlements. If you run into this issue, just hit Run in Xcode again. This signing issue will not occur in properly signed (not DEBUG) builds.
  5. Running your app on device or in the simulator with a debugger attached may also cause an entitlements error to be returned when reading from or writing to the keychain. To work around this issue on device, run the app without the debugger attached. After running once without the debugger attached the keychain will usually behave properly for a few runs with the debugger attached before the process needs to be repeated.
  6. Running your app or unit tests without the application-identifier entitlement. Xcode 8 introduced a requirement that all schemes must be signed with the application-identifier entitlement to access the keychain. To satisfy this requirement when running unit tests, your unit tests must be run inside of a host application.
  7. Attempting to write data larger than 4kb. The Keychain is built to securely store small secrets – writing large blobs is not supported by Apple's Security daemon.

Requirements

  • Xcode 13.0 or later.
  • iOS 9 or later.
  • tvOS 9 or later.
  • watchOS 2 or later.
  • macOS 10.11 or later.

Migrating from prior Valet versions

The good news: most Valet configurations do not have to migrate keychain data when upgrading from an older version of Valet. All Valet objects are backwards compatible with their counterparts from prior versions. We have exhaustive unit tests to prove it (search for test_backwardsCompatibility). Valets that have had their configurations deprecated by Apple will need to migrate stored data.

The bad news: there are multiple source-breaking API changes from prior versions.

Both guides below explain the changes required to upgrade to Valet 4.

Migrating from Valet 2

  1. Initializers have changed in both Swift and Objective-C - both languages use class methods now, which felt more semantically honest (a lot of the time you’re not instantiating a new Valet, you’re re-accessing one you’ve already created). See example usage above.
  2. VALSynchronizableValet (which allowed keychains to be synced to iCloud) has been replaced by a Valet.iCloudValet(with:accessibility:) (or +[VALValet iCloudValetWithIdentifier:accessibility:] in Objective-C). See examples above.
  3. VALAccessControl has been renamed to SecureEnclaveAccessControl (VALSecureEnclaveAccessControl in Objective-C). This enum no longer references TouchID; instead it refers to unlocking with biometric due to the introduction of Face ID.
  4. Valet, SecureEnclaveValet, and SinglePromptSecureEnclaveValet are no longer in the same inheritance tree. All three now inherit directly from NSObject and use composition to share code. If you were relying on the subclass hierarchy before, 1) that might be a code smell 2) consider declaring a protocol for the shared behavior you were expecting to make your migration to Valet 3 easier.

You'll also need to continue reading through the migration from Valet 3 section below.

Migrating from Valet 3

  1. The accessibility values always and alwaysThisDeviceOnly have been removed from Valet, because Apple has deprecated their counterparts (see the documentation for kSecAttrAccessibleAlways and kSecAttrAccessibleAlwaysThisDeviceOnly). To migrate values stored with always accessibility, use the method migrateObjectsFromAlwaysAccessibleValet(removeOnCompletion:) on a Valet with your new preferred accessibility. To migrate values stored with alwaysThisDeviceOnly accessibility, use the method migrateObjectsFromAlwaysAccessibleThisDeviceOnlyValet(removeOnCompletion:) on a Valet with your new preferred accessibility.
  2. Most APIs that returned optionals or Bool values have been migrated to returning a nonoptional and throwing if an error is encountered. Ignoring the error that can be thrown by each API will keep your code flow behaving the same as it did before. Walking through one example: in Swift, let secret: String? = myValet.string(forKey: myKey) becomes let secret: String? = try? myValet.string(forKey: myKey). In Objective-C, NSString *const secret = [myValet stringForKey:myKey]; becomes NSString *const secret = [myValet stringForKey:myKey error:nil];. If you're interested in the reason data wasn't returned, use a do-catch statement in Swift, or pass in an NSError to each API call and inspect the output in Objective-C. Each method clearly documents the Error type it can throw. See examples above.
  3. The class method used to create a Valet that can share secrets between applications using keychain shared access groups has changed. In order to prevent the incorrect detection of the App ID prefix in rare circumstances, the App ID prefix must now be explicitly passed into these methods. To create a shared access groups Valet, you'll need to create a SharedGroupIdentifier(appIDPrefix:nonEmptyGroup:). See examples above.

Contributing

We’re glad you’re interested in Valet, and we’d love to see where you take it. Please read our contributing guidelines prior to submitting a Pull Request.

Thanks, and please do take it for a joyride!

valet's People

Contributors

allisonmoyer avatar autoc0diq avatar brianpartridge avatar brockboland avatar danielribeiro avatar davidjb avatar dependabot[bot] avatar dfed avatar diogot avatar dnkoutso avatar efirestone avatar eliperkins avatar erichoracek avatar ericmuller22 avatar gfontenot avatar ianyh avatar idrougge avatar jakeholland avatar jamiewhite avatar jshier avatar juantrias avatar kgleong avatar linusu avatar mthole avatar natan avatar nickentin avatar pwesten avatar slaunchaman avatar vfuc avatar wjmelements avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

valet's Issues

Could not find shared access group prefix

Started seeing the Could not find shared access group prefix error right after upgrading to OS X El Capitan. This is while running the app from Xcode 7.0.1 on a real device (iOS 9.0.2 on iPhone 6).

It happened one time when running the app itself. Removing and rerunning the app made it go away.

Happened a second time when running my app's share extension (which accesses the shared keychain group).

Happens when Valet is calling _sharedAccessGroupPrefix in VALValet.m. Valet asserts on:

VALCheckCondition(status == errSecSuccess, nil, @"Could not find shared access group prefix.");

Any ideas?

Valet breaks builds

Valet has two methods which match the name, but not the return type of two common methods in Cocoa.

- (BOOL)removeObjectForKey:(NSString *)key;
- (BOOL)removeAllObjects;

Foundation has 5 classes with these methods, and all of them share void return type. The difference breaks build in projects which invoke these methods on id. Xcode shows a compiler error: “Multiple methods named ‘removeObjectForKey:’ found with mismatched result, parameter type, or attributes”.

Objective-C generics help avoid the problem, and it’s trivial to modify Valet when using it in a project with conflicts. I do, however, think that Valet should avoid conflicts with established method signatures from Foundation. I understand that may not want to change this, and I just wanted to get this on your radar and find out what you think.

Thank you for the work on Valet.

Keychain not accessible in setString

This method suddenly started returning false while it working just a moment ago and I didn't make any changes. Testing with a device. The documentation says "@return NO if the keychain is not accessible." but why is it not accessible? Thanks.

Xcode complains about missing keychain-access-groups entitlement

Hi,

I'm having some issues exporting an app that has a framework included that uses Valet. It only uses VALValet, so it shouldn't require shared keychain as far as I'm concerned. Is there anything I'm missing? Xcode says:

No matching provisioning profiles found for "App"
None of the valid provisioning profiles allowed the specified entitlements: application-identifier, keychain-access-groups.

2.2.3 prebuilt binary is missing simulator architectures

$ dwarfdump --uuid Valet.framework/Valet 
UUID: 72092919-8C2C-37A4-9F37-79B65A8FE149 (armv7) Valet.framework/Valet
UUID: A212FAB9-F4F3-3BD7-B969-906EB663C99E (arm64) Valet.framework/Valet

It would appear that the simulator slices (x86-64 and i386) are missing. On a normal framework built by Carthage, all are present.

Valet 3.0 (the one where we get Swifty)

  • Rewrite Touch ID test app in Swift (to feel out pain points in the current Objective-C API)
  • Migrate unit tests to Swift
  • Move to Framework only builds and bump minimum iOS version to 8.0
  • Use .modulemaps to move to a mixed Swift/Objective-C framework
  • Swift API shim (using Objective-C implementation under the hood)
  • Objective-C interop test
  • Swift implementation

Carthage support

So as some of you may know Carthage is becoming a popular tool for handling dependencies. Carthage is currently iOS 8+ exclusive due to it using frameworks.

What are your thoughts on supporting this?

My basic understanding of how this would work is by duplicating the current static library targets.

[VALValet canAccessKeychain] spams the device log

Hey there,

Calling canAccessKeychain causes securityd and the calling process to spam the device log with messages about adding duplicates.

Every time it's called it prints about 4 messages to the log.

I see that this is some sort of "optimization":

https://github.com/square/Valet/blob/master/Valet/VALValet.m#L251

But IMHO I'm not seeing the real issue in calling containsObjectForKey. It probably spends more time logging the error than it would take to check the keychain.

IMHO2: canAccessKeychain isn't really something you call often since you know after launching/being unsuspended whether you're going to have access for that entire runloop (and can take out a background task assertion if you want to stay awake).

Is there something I'm missing? :)

Valet error when kSecAttAccount is not a String during keychain migration

kSecAttrAccount should be a String, but a developer can choose to store an NSData object there instead.

Exception:

2017-08-09 16:17:20.566 PaySDKDemo[9913:612370] -[__NSCFData isEqualToString:]: unrecognized selector sent to instance 0x6080002a0df0

Crash occurs here: https://github.com/square/Valet/blob/2.2.3/Valet/VALValet.m#L426

Code used to reproduce crash:

// Add an NSData object as the kSecAttrAccount entry
NSDictionary *keychainData = @{(id)kSecAttrService: [NSBundle mainBundle].bundleIdentifier, (id)kSecClass: (id)kSecClassGenericPassword, (id)kSecAttrAccount:[@"bar" dataUsingEncoding:NSUTF8StringEncoding], (id)kSecValueData:[@"foo" dataUsingEncoding:NSUTF8StringEncoding]};

// Manually add the entry above to the keychain
__unused OSStatus status = SecItemAdd((__bridge CFDictionaryRef)keychainData, NULL);

VALValet *keychain = // initialize a Valet keychain

// ** Crash **
[keychain migrateObjectsMatchingQuery:[SQLegacyKeychain migrationQueryWithService:[NSBundle mainBundle].bundleIdentifier] removeOnCompletion:YES];

@EricMuller22 @dfed

removeObjectForKey:options: returns YES when it fails with -34018

I have been chasing an issue when even after I log out successfully, it logs me back in the next time.
(Disclaimer this is with Xcode debugger attached)

  • call removeObjectForKey which returns YES, even though VALAtomicSecItemDelete returned -34018
  • immediately call object:forKey to check which as expected returns nil, even though VALAtomicSecItemCopyMatching returned -34018
    => I am assuming that the sequence properly removed the key. However it did not.

So how am I supposed to call canAccessKeychain() after each call to make sure that they actually succeeded?

Change a VALValet's accessibility level

Is it possible to change a specific VALValet's accessibility level?

For instance, let's say a VALValet had .always accessibility and now I want to make it .afterFirstUnlock.

The Apple docs say that it's possible, and there's even some sample code on StackOverflow, but is there a way to do this with Valet without having to migrate to a new VALValet with different accessibility?

Thanks.

kSecUseAuthenticationContext Support

We are developing an application that stores an encryption key on a VALSecureEnclaveValet protected by VALAccessControlTouchIDCurrentFingerprintSet. We want to protect the key with TouchID but we do not want to request the TouchID everytime we need the key because we use it at almost every screen of our app to decrypt the data displayed on screen. We want to request TouchID once and keep access to the key "authenticated" while our session is alive. Keeping the key in memory for a long time is not an option for us.

We have achieved the behavior we want passing a LAContext object at kSecUseAuthenticationContext at the [VALValet stringForKey:options:] options dictionary. But this is a protected method and we cannot call it without modifying your library code. Do you plan to add the possibility to pass a LAContext to [VALSecureEnclaveValet stringForKey]? Or could you suggest me a better way to implement this functionality?

Thanks

Face ID defaulting?

Hi There,

The iPhoneX warns that TouchID is being used and asks the user if they would rather use Face ID. Are there any plans to default to FaceID on the iPhoneX to prevent this message?

Thanks,
Steve

data stored in valet not cleared on app delete?

I'm using Valet component with Xamarin;
it works well and is easy to use But ...

But - it seems that data stored in Valet persists even after the application has
been deleted from the device. I have 2 apps and use the shared data feature
so each app can know the other is on the device, but that data persists even
when the app has been deleted.

Is this a bug or feature? Is there some way to have the data removed
when the application is removed?

Intermittent Read Failures

So I have a VALValet as such:

static let sharedValet = VALValet(identifier: Key.identifier.rawValue, accessibility: .afterFirstUnlockThisDeviceOnly)!

Most of the time it works fine. However, I'm running into rare, non-repeatable read failures for values which were stored in it (which I'm sure succeed). Are there any read failure scenarios I should be aware of? There isn't really a lot of insight into why a read failed as Valet just assumes it was because the value was never there to begin with. So what are my options here?

Valet for Android

Not an issue, but rather a suggestion:

It'd be awesome if you guys (Square) made something like this for Android. It is desperately needed (SharedPreferences is not encrypted, and the "Keychain" on Android is not meant for simple key-value pairs)

Love your guys's Open Source work!

Enable `allKeys` and `removeAllObjects` methods on `VALSinglePromptSecureEnclaveValet`

We're currently blocked from allowing this because we're using a tight inheritance tree, and VALSinglePromptSecureEnclaveValet's superclass rightly disallows use of allKeys and removeAllObjects.

To get around this limitation, we'll likely need to break apart the class hierarchy and use composition internally. The best time for this kind of change is likely during our transition to Swift.

For additional context, see #104 and #105.

dSYM not included in Framework zip

I noticed that the dSYM is not included in the framework zip that Carthage downloads. We like to include those in the Build Products folder, so we get full backtraces. Is it possible to include it?

Queue behavior of TouchID prompts?

Prompting for TouchID using LAContext uses a completion handler on another queue. However, the direct prompt through the keychain (and Valet obviously), just seems to be a direct, synchronous call. Is that correct? Is there anything we need to be aware of here in regards to proper queue usage? What happens if the user doesn't confirm for 30 seconds? Is this blocking the main queue or not? Should I be wrapping these calls in my own asynchronous solution?

Store data = nil

Hello,

I am using Valet to store sensible credential, like access token for authenticate the user in my app.
When I store it, I can't retrieve it, it's always nil.

class KeychainAccessManager {
    private var valetManager: VALValet?
    private static var sharedInstance = KeychainAccessManager()

    init() {
        self.valetManager = VALValet(identifier: "app.id", accessibility: .WhenUnlocked)
    }

    static func stringForKey(key: String) -> String? {
        print("[🔐] Keychain storage get {\(key)} manager : [\(self.sharedInstance.valetManager)]")

        return self.sharedInstance.valetManager?.stringForKey(key)
    }

    static func setString(string: String, key: String) {
        print("[🔐] Keychain storage set {\(string)} {\(key)} manager : [\(self.sharedInstance.valetManager)]")
        self.sharedInstance.valetManager?.setString(string, forKey: key)
    }

    static func removeString(key: String) {
        print("[🔐] Keychain storage remove {\(key)} manager : [\(self.sharedInstance.valetManager)]")
        self.sharedInstance.valetManager?.removeObjectForKey(key)
    }
}

I use this class to wrap the storage, but when I restart the app, I check if there is a token stored on it, it's always nil, so the user currently has to log every time.

Thanks in advance.

No Touch ID prompt when retrieving stored use Touch ID access control

I am storing & retrieving data using a VALSecureEnclaveValet with a Touch ID access control policy. But when I read the data out of the keychain via Valet, the user is not prompted for their fingerprint but the data is read, anyway.

Here is my implementation:

let valet = VALSecureEnclaveValet(identifier: Constants.valetIdentifier, accessControl: .touchIDAnyFingerprint)

let secretStringKey = "secret"

secureEnclaveValet.setString(secretString, forKey: "secret") 

// Expected: Touch ID prompt should be presented to user in order to read secret string
// Actual: No prompt appears, string is still read w/o any fingerprint verification
let secretString = secureEnclaveValet.string(
    forKey: "secret",  
    userPrompt: "Fingerprint required to read secret", 
    userCancelled: nil)

Am I implementing this incorrectly, or misunderstanding how this is supposed to work?

Any help is appreciated. Thank you.

AppleDoc

I'm going to go through and get -real- OCD on AppleDoc style comments (@param, @return, @warning, etc. for our headers) here pretty soon.

Friendlier NS_ENUM names?

This might be a wont fix, but VALAccessibility and VALMigrationError, e.g., don't follow the standard of prefixing all enum values with the enum type itself.

That is, rather than VALAccessibleWhenUnlocked, it would be VALAccessibilityWhenUnlocked.

I can understand that the former is more readable when typed out, but it breaks the Cocoa convention and creates slightly more verbose Swift code.

Synchronizing data between a macOS and iOS app?

I've added the following entitlement to both applications:

<key>keychain-access-groups</key>
<array>
	<string>$(AppIdentifierPrefix)sharedKeychain</string>
</array>

And I've tried the following:

iOS/app launched:

    valet = [[VALSynchronizableValet alloc] initWithSharedAccessGroupIdentifier: @"sharedKeychain"
                                                                           accessibility: VALAccessibilityWhenUnlocked];

    NSString * data = [valet stringForKey: @"key"];
    if(nil == data)
    {
        [valet setString: @"hello world" forKey: @"key"];
    }

macOS/app:

    valet = [[VALSynchronizableValet alloc] initWithSharedAccessGroupIdentifier: @"sharedKeychain"
                                                                           accessibility: VALAccessibilityWhenUnlocked];

    NSString * data = [valet stringForKey: @"key"];

    // Data is always nil?

I'm not sure why the data is coming out nil. Ive tried manually saving data on the macOS version and loading and that works fine, but I cannot seem to get the two apps to synchronize with each other. Any thoughts on what I'm doing wrong?

macOS Secure Enclave Support

With touch ID now available on macOS 10.12.1 we should confirm that Valet works with it. This line indicates that we have some macOS support already, but we should verify. (I would but I'm not running 10.12 yet.)

Make Unit Test suite work on Xcode 8

Currently unit tests are broken in Xcode 8 due to a change in how Xcode simulates the keychain in the unit test environment. In Xcode 8, both iOS and Mac unit test targets must both be hosted in a signed app that has permissions to access the keychain.

Here's the total to-do list:

  • Host iOS and Mac unit test targets in a host app
  • Sign the host app with a cert that is checked into the repository
  • Amend README to mention the cert and how to use it
  • Figure out how to add that cert to the keychain in Travis CI using the command line
  • Change Travis CI Xcode version to Xcode 8

I'll tackle this in multiple PRs

Swift package manager support

Would be awesome to use Valet with swift package manager!

It's waiting on Swift 3 support, so it's probably something to implement after v3.0, and after support for Swift 3 is fleshed out? Not sure if that's targeted as part of v3.0

Use `@available(iOS 9.0, *)`

There are a lot of warnings in code around iOS 9.0 availabilities. e.g.:

#if ((TARGET_OS_IPHONE && __IPHONE_9_0) || (TARGET_OS_MAC && __MAC_10_11))
    if ([[self class] _iOS9OrLater] || [[self class] _macOSElCapitanOrLater]) {
        baseOptions = @{ (__bridge id)kSecUseAuthenticationUI : (__bridge id)kSecUseAuthenticationUIFail };
    } else {

Any plans on fixing those at all? Seems like can fix them easily by wrapping code inside:

if (@available(iOS 9.0, *)) {
    // ... 
}

watchOS Support

If it does not currently, it would be nice to use this library on watchOS 2 (and update the Podspec file to declare this support). I’m happy to help do this, just putting this here to see if anyone else is already working on this.

Is standard VALValet backed up to iCloud?

Hi,

I'm currently working on a project, where I need to store some strings securely, but they cannot be backed up to iCloud. I know the synchronizable valet works across devices, but I couldn't find anywhere in the README about whether the valet is actually backed up to iCloud. So my question is basically as the subject: Is the standard VALValet backed up to iCloud?

Keychain error -34018 (errSecMissingEntitlement)

Always getting this issue, I have implemented Valet in 2 of my apps for one app it works like charm as promised. But for the 2nd app every time I get the above Keychain error. I am using xcode 8. Please guide as if not worked i will have to do a lot of rework.

I even tried creating a sample also for simple reading and writing operation on Keychain, but still getting the same error.
Thanks in advance.

Missing Entitlements in debugger?

A 'Missing Entitlements' error occurred. This is likely due to an Apple Keychain bug. As a workaround try running on a device that is not attached to a debugger.

More information: https://forums.developer.apple.com/thread/4743

Guy, I got this issue in log when saving a string token to keychain on iOS 9

valet = VALValet(identifier:"com.abc.xyz", accessibility: .WhenUnlockedThisDeviceOnly)
valet!.setString(token, forKey: "token")

Any help?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.