IT박스

SecItemAdd 및 SecItemCopyMatching은 오류 코드 -34018 (errSecMissingEntitlement)을 반환합니다.

itboxs 2020. 7. 20. 07:52
반응형

SecItemAdd 및 SecItemCopyMatching은 오류 코드 -34018 (errSecMissingEntitlement)을 반환합니다.


때로는 Xcode에서 장치에서 응용 프로그램을 실행할 때 키 체인에 액세스하려고하지만 오류 -34018로 인해 실패합니다. 이것은 문서화 된 키 체인 오류 코드와 일치하지 않으며 일관되게 재현 할 수 없습니다. (어쩌면 시간의 30 %가 발생할 수 있으며 왜 그런지 분명하지 않습니다). 이 문제를 디버깅하는 것을 매우 어렵게 만드는 것은 문서가 부족하다는 것입니다. 이 문제의 원인과 해결 방법을 알고 있습니까? Xcode 5를 사용하고 장치에서 iOS 7.0.4를 실행하고 있습니다.

https://github.com/soffes/sskeychain/issues/52 여기에 공개 문제가 있습니다.

편집 : 요청 당 키 체인 액세스 코드 추가

SSKeychain키 체인과 인터페이스하기 위해 라이브러리를 사용하고 있습니다. 다음은 스 니펫입니다.

#define SERVICE @"default"

@implementation SSKeychain (EXT)

+ (void)setValue:(NSString *)value forKey:(NSString *)key {
    NSError *error = nil;
    BOOL success = NO;
    if (value) {
        success = [self setPassword:value forService:SERVICE account:key error:&error];
    } else {
        success = [self deletePasswordForService:SERVICE account:key error:&error];
    }
    NSAssert(success, @"Unable to set keychain value %@ for key %@ error %@", value, key, error);
    if (!success) {
        LogError(@"Unable to set value to keychain %@", error);
    }
    LogTrace(@"Will set keychain account %@. is to nil? %d", key, value == nil);
    if (value == nil)
        LogWarn(@"Setting keychain %@ to nil!!!", key);
}

+ (NSString *)valueForKey:(NSString *)key {
    NSError *error = nil;
    NSString *value = [self passwordForService:SERVICE account:key error:&error];
    if (error && error.code != errSecItemNotFound) {
        NSAssert(!error, @"Unable to retrieve keychain value for key %@ error %@", key, error);
        LogError(@"Unable to retrieve keychain value for key %@ error %@", key, error);
    }
    return value;
}

+ (BOOL)removeAllValues {
    LogInfo(@"Completely Reseting Keychain");
    return [[self accountsForService:SERVICE] all:^BOOL(NSDictionary *accountInfo) {
        return [self deletePasswordForService:SERVICE account:accountInfo[@"acct"]];
    }];
}

@end

대부분의 시간은 괜찮습니다. 때로는 키 체인에 쓰거나 읽을 수없는 어설 션 오류가 발생하여 심각한 어설 션 오류가 발생합니다.


iOS 10 / XCode 8 수정 :

KeyChain 인 타이틀먼트 추가, 프로젝트 설정으로 이동-> 기능-> 키 체인 공유-> 키 체인 그룹 추가 + 켜기

Apple의 답변 :

업데이트 : 마침내 iOS 8.3에서 -34018 오류를 재현 할 수있었습니다. 이것은 근본 원인을 식별하고 수정 사항을 제시하는 첫 번째 단계입니다.

평소와 같이 릴리스 기간을 확정 할 수는 없지만 많은 개발자에게 영향을 미쳤으며이 문제를 해결하고자합니다.

이전에는 해결 방법으로 키 체인에 액세스하기 전에 application : didFinishLaunchingWithOptions 및 applicationDidBecomeActive :에 약간의 지연을 추가하는 것이 좋습니다. 그러나 실제로 도움이되지는 않습니다. 즉, 현재 앱을 다시 시작하는 것 외에 알려진 해결 방법이 없습니다.

이 문제는 메모리 부족과 관련된 것으로 보이므로 메모리 경고를보다 적극적으로 처리하면 문제가 완화 될 수 있습니다.

https://forums.developer.apple.com/thread/4743#14441

최신 정보

자, 여기 최신입니다.
여러 가지 가능한 원인이있는 복잡한 문제입니다.

  • 문제의 일부 인스턴스는 잘못된 앱 서명으로 인해 발생합니다. 문제는 100 % 재현 가능하므로이 경우를 쉽게 구별 할 수 있습니다.
  • 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

https://forums.developer.apple.com/thread/4743#126088


Basically you have to codesign your .xcttest folder by adding the following as a run script in your test target.

codesign --verify --force --sign "$CODE_SIGN_IDENTITY" "$CODESIGNING_FOLDER_PATH"

I got a lot of -34018 errors when testing my keychain on the device and this managed to fix it.

If the problem does not exist in your test target this is probably not the solution.


After inspecting the source code. I have noticed that the keychain features are accessed through a security daemon that runs in its own process (separated from the app process).

Your app and the securityd process 'talk' together through a technology called XPC.

If necessary, the securityd is launched via the well-known launchd command by XPC. You can probably check that the daemon is running in the Activity Monitor App (if running in Simulator of course) and that its parent process is launchd.

My guess here is that it is possible that for any unknown reason the security daemon fails to start or do it too slowly and is not ready when you try to use it.

Maybe you could think on how to pre-launch the daemon.

I apologize for not being more precise. I hope it could help you to go a bite further in your investigations.


I’m observing similar behavior after building and running my code in Xcode 6 beta with iOS 8 SDK (it’s working correctly with Xcode 5 / iOS 7). In Xcode 6, in iOS Simulator SecItemCopyMatching always returns -34018. It started working after turning on the “Keychain Sharing” in Capabilities tab.

However I have another issue. I’m developing static library, that is used by (among others) Demo application. The above solution works for Demo application project, but when I try to unit test my static library project, I have exactly the same error. And the problem is that my static library project doesn’t have the Capabilities tab (as it’s not the standalone application).

I’ve tried the solution posted here by JorgeDeCorte, with codesigning in the test target, but it doesn’t work for me.


Try disabling all breakpoints when launching the app from Xcode. You can enable them afterwards.

(None of the above workarounds worked for me)


I just had the same issue on the simulator running 7.1 & 8.0. While doing some digging, I noticed that the Apple sample app had KeyChain Sharing turned on for its target capabilities. I turned it on for my app which resulted in creating an entitlement file that I left with the default values and now I am not getting anymore -34018 errors. This is not ideal but I will live the KeyChain sharing option for now.


I got bitten by this, too and had no success with any of the other workarounds. I then cleaned up my provisioning profiles on the devices itself by deleting all of them related to my app as well as all the wildcard profiles (this seems to be the point). To do this, go to the "Devices" Window in Xcode and right-click your (connected) phone:

Click on "Show provisioning profiles" and delete the related ones, and especially the team profiles:

including the ones with the asterisk. After reinstallation the app, everything went back to normal.


Codesigning a .xctest bundle isn't as easy as it sounds in some cases. Principally JorgeDeCorte is right with his answer that the given short line as a Run Script is enough for most of the devs.

codesign --verify --force --sign "$CODE_SIGN_IDENTITY" "$CODESIGNING_FOLDER_PATH"

But when you have multiple certificates in your keychain this will fail with the following line

iPhone Developer: ambiguous (matches "iPhone Developer: Your Name (ABC123DEF45)" and "iPhone Developer: Your Name (123ABC456DE)"

A solution to get the right certificate even with multiple ones is this short script. For sure this is not ideal, but as of my knowledge you have no chance to get the certificate that Xcode found and uses for signing your .app.

echo "codesign --verify --force --sign \"$CODE_SIGN_IDENTITY\" \"$CODESIGNING_FOLDER_PATH\""
IDENTITIES=`security find-identity -v -s "Code Signing" | grep "iPhone Developer" | awk '{ print $2 }'`

for SHA in $IDENTITIES; do
    codesign --verify --force --sign $SHA "$CODESIGNING_FOLDER_PATH"
    if [ $? -eq 0 ]; then
        echo "Matching identity found: $SHA"
        exit 0
    fi
done;

exit 1

I have fixed this problem (I think). I had a wildcard provisioning profile on my device that showed it did not have a valid signing identity. I also had a provisioning profile for my app that was valid. When I deleted the wildcard profile, I stopped getting the -34018 errors.

I also made sure that the code signing identity and provisioning profile listed in the Code Signing section of the Build Settings of the target were identical to the one for the app (not the generic "iPhone Developer" one)


I was getting -34018 error in my app (iOS 8.4) very rarely. After some investigation I've found that this issue occurs when the app requests data from keychain too often.
For example, in my situation it was two read requests for one specific key at the same time from different application modules.
To fix that I've just added caching this value in memory


I was having the same problem, out of the blue, running on a test device with Xcode 6.2, iPhone 6, iOS 8.3. To be clear, this was not experienced while running Xcode tests, but rather while running the actual app on my device. In the simulator it was fine, and running on the app itself it had been perfectly fine until recently.

I tried all of the suggestions I could find here, such as removing the provisioning profiles on my device (I removed ALL of them), temporarily enabling the Keychain Sharing capability in my project (even though we don't really need that), making sure my development account in Xcode was totally refreshed with all of the certificates and provisioning profiles, etc. Nothing helped.

Then I temporarily changed the accessibility level from kSecAttrAccessibleAfterFirstUnlock to kSecAttrAccessibleAlwaysThisDeviceOnly, ran the app, and it worked fine and was able to write to the Keychain. Then I changed it back to kSecAttrAccessibleAfterFirstUnlock, and the problem seems to have gone away "permanently."


Just got bitten by this bug on Xcode 8 Beta 3. Turning on Keychain Sharing seems to be the only solution.


I had the same issue. Fixed it by setting up Keychain Sharing.


(this is not a direct answer to the OP's question, but might help others)

Started getting the keychain error -34018 consistently in simulator after updating Xcode from version 7.3.1 to 8.0.

Following this tip from daidai's answer,

Some instances of the problem are caused by incorrect app signing. You can easily distinguish this case because the problem is 100% reproducible.

it was discovered that Provisioning Profile had somehow been set to None in the Signing sections of the target.

However, setting the Provisioning Profile fields to valid values was not sufficient to resolve the issue in this case.

Further investigation showed that the Push Notifications entitlement also displayed an error. It said the "Add the Push Notifications feature to your App ID." step was completed, but step "Add the Push Notifications entitlement to your entitlements file" was not.

After pressing "Fix Issue" to fix the Push Notification issue, the keychain error was resolved.

For this particular target, the "Keychain Sharing" entitlement had already been turned on at some previous time. Turning it off has not caused the keychain error to reappear so far, so its not clear whether it is necessary in this case.


In iOS 9 I turned off Address Sanitizer and it started working on the device.


The only solution that worked for me was first storing nil for the specified key, and then storing my new value with a separate operation. It would fail due to error -34018 if I attempted to overwrite the existing value. But as long as I stored nil first, then the updated value would be stored successfully immediately afterwards.


I met this -34018 issue today when running SecItemDelete API. What I did to fix this is: 1. Following @k1th solution https://stackoverflow.com/a/33085955/889892 2. Run the SecItemDelete in main thread(Previously it's read from main thread, so just align this with deleting).

Sorry it comes back again :(


Turn on Keychain sharing in your project's capabilities, it should solve the problem. enter image description here


What worked for me

  • Turn on Keychain Sharing.
  • Use the keychain as less as possible and cache the data in memory, UserPreferences, disk, etc.
  • Retry many times the keychain CRUD operations if these failed.
  • Use DispatchQueue.sync for storing/deleting/updating the data.

For me it was an app signing issue. I simply switched to the correct signing team in Xcode and the error no longer occurred

참고URL : https://stackoverflow.com/questions/20344255/secitemadd-and-secitemcopymatching-returns-error-code-34018-errsecmissingentit

반응형