OSStatus error code -34018
Asked Answered
O

4

51

I am using SecItemCopyMatching to access the iOS keychain. About 1 in a hundred times I get a -34018 result code right after relaunching the app from the background. The documentation states:

The assigned error space for Keychain Services is discontinuous: –25240 through –25279 and –25290 through –25329. Keychain Item Services may also return noErr (0) or paramErr (–50), or CSSM result codes

So it seems that -34018 is a 'CSSM result code'. I have followed the suggested link but could not find result codes.

What it the -34018 result code? How can I get more reliable keychain access?

- (NSData *)getKeychainData:(NSString *)key
{
    NSDictionary *query = @{
        (__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService:SEC_ATTR_SERVICE,
        (__bridge id)kSecAttrAccount:key,
        (__bridge id)kSecReturnData:@YES
    };

    CFDataRef result = nil;

    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&result);

    if(status == errSecItemNotFound) {
        return nil;
    }

    if(status == noErr) {
        return CFBridgingRelease(result);
    } else {
        [self logError:[NSString stringWithFormat:@"SecItemCopyMatching status %d", (int)status] :nil];
        return nil;
    }
}
Olympian answered 20/4, 2015 at 6:47 Comment(6)
Here's a thread on Apple's Dev Forums: devforums.apple.com/message/1123824. Seems to be a long-standing issue with unclear root cause or solutions. You may want to subscribe to the message thread.Indention
Is protected data available when this occurs?Unemployed
No protected data is available. For what it's worth, I protect my data with kSecAttrAccessibleWhenUnlockedThisDeviceOnly.Olympian
There is a thread discussing this here.Olympian
Keychain access could be locked before your app becomes active. Between applicaitonWillEnterForeground and applicationDidBecomeActive states there is some time lag. Are you sure you are talking to keychain after app becomes active?Lacy
https://mcmap.net/q/181730/-secitemadd-and-secitemcopymatching-returns-error-code-34018-errsecmissingentitlementSverige
T
21

I've been just researching the same error.

The gist of it is that the security service apple uses in order to communicate with the key chain, in rare cases, when the user's device is low on memory, crashes and taking away the app ability to talk to the keychain which results the dreadful -34018.

This is not happening only while running through Xcode like some may claim.

This is the most recent data regarding the issue taken from the Apple developer forums by one of the Apple staff:

UPDATE: We have finally been able to reproduce the -34018 error on iOS 8.3. This is the first step in identifying the root cause and then coming up with a fix.

As usual, we can't commit to a release timeframe, but this has affected many developers and we really want to get this resolved.

Earlier I suggested adding a small delay in application:didFinishLaunchingWithOptions and applicationDidBecomeActive: before accessing the keychain as a workaround. However, that doesn't actually appear to help. That means that there's no known workaround at this time other than relaunching the app.

The issue appears to be related to memory pressure, so perhaps being more aggressive in handling memory warnings may alleviate the problem.

From Another Apple staff member:

  • Keychain engineering is well aware of how important this issue is.
  • The primary problem has been reproducing the failure here at Apple.
  • We're now able to do that (largely thanks to the work you guys have put in filing and following up on your bug reports).

From Another Apple staff member on Mar 22, 2016:

OK, here’s the latest. This is a complex problem with multiple possible causes: Some instances of the problem are caused by incorrect app signing. You can easily distinguish this case because the problem is 100% reproducible. Some instances of the problem are caused by a bug in how iOS supports app development (r. 23,991,853). Debugging this was complicated by the fact that another bug in the OS (r. 23,770,418) masked its effect, meaning the problem only cropped up when the device was under memory pressure. We believe these problems were resolved in iOS 9.3. We suspect that there may be yet more causes of this problem. So, if you see this problem on a user device (one that hasn’t been talked to by Xcode) that’s running iOS 9.3 or later, please do file a bug report about it. Try to include the device system log in your bug report (I realise that can be tricky when dealing with customer devices; one option is to ask the customer to install Apple Configurator, which lets them view the system log). And if you do file a bug, please post your bug number, just for the record. On behalf of Apple I’d like to thank everyone for their efforts in helping to track down this rather horrid issue. Share and Enjoy

Unfortunately there are no known workarounds and the issue is still not fixed in 9.3.2 Beta 1 (13F51a)

Telluride answered 19/11, 2015 at 18:28 Comment(7)
"low on memory" -> What memory are we talking about, specifically?Olympian
"This is not happening only while running through Xcode like some may claim." -> Do you have a source for this?Olympian
We're talking about the device memory in general. Your app memory management can be great but there's still a chance you'd be effected by this. So if the user has a few apps open (chrome with a few tabs, Mail with a large inbox etc') that may cause that service to crash. Regarding your second comment, the source for that is 5% of our users that use the app from the Appstore. A lot of other testimonies in the apple forums of the 34018 happening in production.Telluride
Out of curiosity, what is your app?Olympian
As I said in another comment below, I'm getting the error in a non debug release in iOS 9.2. What I don't understand is what other big applications do when that occurs? Without the access to the secrets it shouldn't be possible to authenticate with the backend and therefore the app wouldn't work well. However I haven't seen that behaviour in other apps, am I missing anything? Big apps does not use KeyChain??!?!Vespine
Using the KeyChain? Yes. Depending on it heavily? Defiantly not. It will always have an encrypted fallback. (NSUserDefualts, NSFileManager etc') It's really sad to be honest, this major bug is around for ages (years). A quick look on the apple dev forums will reveal at least 4 discussions about it on the front page at all times yet this is still an issue.Telluride
Still no luck on iOS 9.2.1, it still has the bug alive.Vespine
O
24

After some research, I found this: http://opensource.apple.com/source/Security/Security-55471/sec/Security/SecBasePriv.h

So -34018 is errSecMissingEntitlement and the comment says

Internal error when a required entitlement isn't present.

Do you experience this error while running your unit tests? If so, this might help: https://mcmap.net/q/181730/-secitemadd-and-secitemcopymatching-returns-error-code-34018-errsecmissingentitlement

This issue on github says that it only seems to happen while debugging from Xcode: https://github.com/soffes/sskeychain/issues/97 (also see https://mcmap.net/q/355158/-ios-keychain-writing-value-results-in-error-code-34018)

Hopefully some of this will help!

Organon answered 1/5, 2015 at 13:20 Comment(3)
I don't get this error while running unit tests, and the bug also happens (rarely) when I don't launch the app from Xcode.Olympian
@Olympian That's interesting.Organon
I get the error even in a TestFlight release running iOS 9.2 on an iPhone 5s.Vespine
T
21

I've been just researching the same error.

The gist of it is that the security service apple uses in order to communicate with the key chain, in rare cases, when the user's device is low on memory, crashes and taking away the app ability to talk to the keychain which results the dreadful -34018.

This is not happening only while running through Xcode like some may claim.

This is the most recent data regarding the issue taken from the Apple developer forums by one of the Apple staff:

UPDATE: We have finally been able to reproduce the -34018 error on iOS 8.3. This is the first step in identifying the root cause and then coming up with a fix.

As usual, we can't commit to a release timeframe, but this has affected many developers and we really want to get this resolved.

Earlier I suggested adding a small delay in application:didFinishLaunchingWithOptions and applicationDidBecomeActive: before accessing the keychain as a workaround. However, that doesn't actually appear to help. That means that there's no known workaround at this time other than relaunching the app.

The issue appears to be related to memory pressure, so perhaps being more aggressive in handling memory warnings may alleviate the problem.

From Another Apple staff member:

  • Keychain engineering is well aware of how important this issue is.
  • The primary problem has been reproducing the failure here at Apple.
  • We're now able to do that (largely thanks to the work you guys have put in filing and following up on your bug reports).

From Another Apple staff member on Mar 22, 2016:

OK, here’s the latest. This is a complex problem with multiple possible causes: Some instances of the problem are caused by incorrect app signing. You can easily distinguish this case because the problem is 100% reproducible. Some instances of the problem are caused by a bug in how iOS supports app development (r. 23,991,853). Debugging this was complicated by the fact that another bug in the OS (r. 23,770,418) masked its effect, meaning the problem only cropped up when the device was under memory pressure. We believe these problems were resolved in iOS 9.3. We suspect that there may be yet more causes of this problem. So, if you see this problem on a user device (one that hasn’t been talked to by Xcode) that’s running iOS 9.3 or later, please do file a bug report about it. Try to include the device system log in your bug report (I realise that can be tricky when dealing with customer devices; one option is to ask the customer to install Apple Configurator, which lets them view the system log). And if you do file a bug, please post your bug number, just for the record. On behalf of Apple I’d like to thank everyone for their efforts in helping to track down this rather horrid issue. Share and Enjoy

Unfortunately there are no known workarounds and the issue is still not fixed in 9.3.2 Beta 1 (13F51a)

Telluride answered 19/11, 2015 at 18:28 Comment(7)
"low on memory" -> What memory are we talking about, specifically?Olympian
"This is not happening only while running through Xcode like some may claim." -> Do you have a source for this?Olympian
We're talking about the device memory in general. Your app memory management can be great but there's still a chance you'd be effected by this. So if the user has a few apps open (chrome with a few tabs, Mail with a large inbox etc') that may cause that service to crash. Regarding your second comment, the source for that is 5% of our users that use the app from the Appstore. A lot of other testimonies in the apple forums of the 34018 happening in production.Telluride
Out of curiosity, what is your app?Olympian
As I said in another comment below, I'm getting the error in a non debug release in iOS 9.2. What I don't understand is what other big applications do when that occurs? Without the access to the secrets it shouldn't be possible to authenticate with the backend and therefore the app wouldn't work well. However I haven't seen that behaviour in other apps, am I missing anything? Big apps does not use KeyChain??!?!Vespine
Using the KeyChain? Yes. Depending on it heavily? Defiantly not. It will always have an encrypted fallback. (NSUserDefualts, NSFileManager etc') It's really sad to be honest, this major bug is around for ages (years). A quick look on the apple dev forums will reveal at least 4 discussions about it on the front page at all times yet this is still an issue.Telluride
Still no luck on iOS 9.2.1, it still has the bug alive.Vespine
L
4

This code works for me:

static const UInt8 kKeychainItemIdentifier[] = "com.apple.dts.KeychainUI\0";

- (NSData *)getKeychainData:(NSString *)key
{
    NSData *keychainItemID = [NSData dataWithBytes:kKeychainItemIdentifier length:strlen((const char *)kKeychainItemIdentifier)];

    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: SEC_ATTR_SERVICE,
        (__bridge id)kSecAttrAccount: key,
        (__bridge id)kSecReturnData: (__bridge id)kCFBooleanTrue,
        (__bridge id)kSecAttrGeneric: keychainItemID
    };

    CFDataRef result = NULL;

    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&result);

    if(status == errSecItemNotFound) {
        return nil;
    }

    if(status == noErr) {
        return CFBridgingRelease(result);
    } else {
        [self logError:[NSString stringWithFormat:@"SecItemCopyMatching status %d", (int)status] :nil];
        return nil;
    }
}

The main difference with OP's code is the addition of a Generic Attribute to the query. The Keychain Item Identifier is the default from apple. The reason behind this comes to differentiate possible different keychain items from each other. This is one way to make a more the keychain items access more reliable. Basically, in other words, this makes sure you access apple's default keychain.

Lilias answered 8/5, 2015 at 3:31 Comment(3)
While this code snippet may answer the question, including an explanation out of the code really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Undersecretary
@Undersecretary I've edited the answer. I hope you find this useful.Lilias
Need someone to merge into Apple wrapper. Any body? gist.github.com/kristopherjohnson/5212625Uptotheminute
N
1

After trying many of the fixes in stack overflow, things still didn't work for me.

What worked was switching the Keychain Sharing Capability in Xcode. Built and run and it worked right away.

enter image description here

Neoptolemus answered 6/10, 2016 at 2:9 Comment(1)
thanks, a good reminder, I also forgot it 🤦🏻‍♀️Milkwort

© 2022 - 2024 — McMap. All rights reserved.