Prioritize user privacy and data security in your app. Discuss best practices for data handling, user consent, and security measures to protect user information.

All subtopics
Posts under Privacy & Security topic

Post

Replies

Boosts

Views

Activity

Keychain error -25308
I've implemented a VPN app (with Packet tunnel Provider) for MacOS.Each user has a password, which I'm saving at the keychain with a persistentReference.For some users (not many), the app fails to save the password and I got error -25308 which is User interaction is not allowed.Why does it happening and how can I solve it?
10
0
16k
May ’22
Use kSecAttrAccessControl to only protect the private key in a SecIdentityRef
I try to use SecPKCS12Import to retrieve SecIdentityRef from PKCS#12 blob and store SecCertificateRef & SecKeyRef into keychain separately, so that I can use kSecAttrAccessControl to only protect private key with TouchID. The same code works on iOS, but not on Mac. The problem is SecPKCS12Import already saved the identity into keychain. I tried to delete the stored identity, however, no matter using SecItemDelete with transient reference or persistent reference of identity or delete both SecCertficateRef and SecKeyRef, the record will be deleted from keychain -> My Certificates and keychain -> Keys, but alwasy leave the certficate in keychain -> Certificates. If I use SecItemAdd to add certificate back, I got errSecDuplicateItem, using SecItemCopyMatching or SecItemDelete, I got errSecItemNotFound. The strange part is, even I open keychain app to manually delete the cert, I got error prompt saying deleting item not found, but after that, the cert disppear from keychain -> Certificates.Since I cannot delete identity and the add it back with access control attributes. I tried to use SecItemImport to avoid saving identity into keychain. However, this API only returns list of SecCertificateRef instead of SecIdentityRef. I found similar issue discussed on https://forums.developer.apple.com/thread/31711Is there anyway to retreive identity from PKCS#12 blob and make kSecAttrAccessControl protect the private key only?
9
0
3k
Nov ’22
Trying to use kSecACLAuthorizationPartitionID
Hi,I am trying to figure out how I can set the kSecACLAuthorizationPartitionID when creating a private key that will later be used by the macOS system ("apple:"). This key is to be used for things like Wi-Fi (eapolagent) and so on.I have been experimenting with the below code, the private key is created correctly, ACL is set and it is added to the keychain, however it seems it is overwritten when I add the key to the keychain: // create standard access SecAccessRef access = SecAccessCreateWithOwnerAndACL(0, 0, kSecUseOnlyUID, NULL, &error); // build partitions list NSMutableArray* partitions = [[NSMutableArray alloc] init]; // we want the apple system to be able to sign with this key [partitions addObject:@"apple:"]; NSMutableDictionary *descriptionDict = [[NSMutableDictionary alloc] init]; [descriptionDict setObject:(__bridge id)partitions forKey:(__bridge id)@"Partitions"]; NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:descriptionDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error]; SecACLRef newAcl = NULL; status = SecACLCreateWithSimpleContents(access, NULL, (CFStringRef)[self hexStringValue:xmlData], kSecKeychainPromptRequirePassphase, &newAcl); NSArray* authorizations = @[(__bridge id)kSecACLAuthorizationPartitionID]; // update ACL status = SecACLUpdateAuthorizations(newAcl, (__bridge CFArrayRef) authorizations);At this point, if I loop through the access ACLS, all look well.And I proceed to create the key:SecKeyRef privateKey = SecKeyCreateFromData((CFDictionaryRef)attributes, (CFDataRef)encodedKeyData, &error);And then add this to the keychain with the access I created above NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init]; [attributes setObject:(__bridge id)privateKey forKey:(id)kSecValueRef]; [attributes setObject:(id)kSecClassKey forKey:(id)kSecClass]; [attributes setObject:tag forKey:(id)kSecAttrApplicationTag]; [attributes setObject:(__bridge id)access forKey:(__bridge id)kSecAttrAccess ]; err = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL);All this runs without error, however dumping the keychain, I can see the ACL as follows: entry 0: authorizations (1): any don't-require-password description: <NULL> applications: <null> entry 1: authorizations (1): partition_id don't-require-password description: unsigned: applications: <null> entry 2: authorizations (1): change_acl don't-require-password description: <NULL> applications: <null>The "unsigned:" is I assume due to me running the app in debug mode, but it looks like the ACL I set is ignored and the keychain API hardcodes this to the caller partition_id.I have also tried to set the partition_id after adding the key to the keychain, but this requires the password of the User, something we do not want to request for obvious reasons.Is what I am trying even possible? Can you set the partition_id when creating a key?Thanks,S.
18
0
3.5k
Aug ’22
Can I delete keychain content when User uninstall App?
I store certificate (as SecIdentity ) in keychain because my application needs clientCertficate.I know when a User uninstall application, keychian content still exist.But in My application, I manage userInformation client certificate and CoreData.So, I want to delete keychain content when user uninstall application for not occering mismatch between Keychain and CoreData.Is it possible to do above ?Or should I delete keychain content when the app re-installed ?
3
0
7.3k
Aug ’23
Read Device Email and Name Information
Dear All,We have to read the device email id information ( apple cloud id or any gmail and email id ) and also i have to get the device name which is user menstioned in apple phone.One of the customer expecting to to fech the user email id and name of information to get in mobile apps while filling the forms to automatically detected to end user.kindly confirm me is to possible as per apple policy and giudelines.
2
0
1k
Jan ’23
SecCertificate data access
Hi. I'm working on a security related swift application, and I need som info from certificates stored in SecIdentities. Although I can access to SecCertificate to extract some info (serialnumber, common name, subject name) y can't find any example of function (or OSX API documentation) for other data extraction, like validity date (from/until), DER encoded public key, certificate usage policies, etc.I'm using Xcode 8.2.1 (Swift 3.0.2).Thank you in advance.
6
0
5.8k
Nov ’22
Integrating TouchID with Authorization Services
I'm currently using authorization services in a factored app(user mode app + privileged helper tool). When performing a privilged operation, the user is prompted for their password. How can I also allow authentication through touch ID?Additional info:Device: MacBook Pro (15-inch, 2017)macOS version: 10.13.4 (17E202)The code is adapted from the EvenBetterAuthorizationSample, so nothing fancy going on there.I also dug around a bit through /usr/libexec/authopen which does allow the user to choose between TouchID and password. If use codesign to change it's signature, only the password prompt is shown. Am I correct to assume that this feature is currently available only for Apple signed applications/binaries?As an alternative, I also fiddled around with LocalAuthentication which works great for a standalone app, but does it provide a way of passing the context between processes, as with AuthorizationMakeExternalForm?
8
0
4.6k
Jul ’22
Integrating Touch ID with Access To Multiple Users in iOS.
I have been working on integrating Touch ID in my iOS application. If the multiple fingerprints are registered at the OS level.Is there anyway to know which fingerprint was scanned. (not the fingerprint infodata just like a unique key)For example :- There are three fingerprint in the iOS DeviceIf fingerprint one is scanned then perform Task A.If fingerprint two is scanned then perform Task C.If fingerprint Three is scanned then perform Task B.
2
0
1.2k
Jul ’23
accessing private key without username/password from daemon
I am trying to read the private key from certificate in the system keychain on the client to sign random data send by the server.Note that the certificates aren't distributed by me. Users will install the certificate(s) either by downloading them from the different servers or importing pkcs file.I am using below code.std::string osxPrivateKey::signData(const uint8_t* pData, uint32_t nDataSize, vector <uint8_t>& aSignature) { OSStatus nStatus; osxObject<SecTransformRef> signer; CFDataRef rawData = CFDataCreate(NULL, (const uint8_t*)pHash, nHashSize); CFErrorRef error; SecTransformRef signerRef = SecSignTransformCreate(m_privKey.get(), &error); signer.set(signerRef); if (error) { return false; } SecTransformSetAttribute(signer.get(), kSecTransformInputAttributeName, rawData, &error); SecTransformSetAttribute(signer.get(), kSecInputIsAttributeName , kSecInputIsPlainText, &error); //SecTransformSetAttribute(signer.get(), kSecPaddingKey, kSecPaddingPKCS1Key, &error); //SecTransformSetAttribute(signer.get(), kSecDigestTypeAttribute, kSecDigestSHA1, NULL); SecTransformSetAttribute(signer.get(), kSecDigestTypeAttribute, kSecDigestSHA2, NULL); int digestLength = 160; //if (type ==2) digestLength = 256; CFNumberRef dLen = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &digestLength); Boolean set = SecTransformSetAttribute(signer.get(), kSecDigestLengthAttribute, dLen, &error); CFRelease(dLen); if (error) { return false; } DSVERBOSE(Sardeep, "SecTransformExecute begin"); Boolean allowed; SecKeychainGetUserInteractionAllowed(&allowed); DSVERBOSE(Sardeep, "SecKeychainGetUserInteractionAllowed '%d'", allowed); SecKeychainSetUserInteractionAllowed(true); CFDataRef signature = (CFDataRef)SecTransformExecute(signer.get(), &error); if (error) { CFStringRef errorDesc = CFErrorCopyDescription(error); CFIndex length = CFStringGetLength(errorDesc); CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char *buffer = (char *)malloc(maxSize); CFStringGetCString(errorDesc, buffer, maxSize, kCFStringEncodingUTF8); DSERROR(facility, "SecTransformExecute error : '%s'", buffer); delete buffer; return false; } DSVERBOSE(Sardeep, "SecTransformExecute end"); m_signHashAlgo = HCCertUtils::SIGN_HASH_ALGO_SHA256; char* base64Signature = new char[1024]; unsigned char* rawSignature = new unsigned char[1024]; int size = CFDataGetLength(signature); CFDataGetBytes(signature, CFRangeMake(0,CFDataGetLength(signature)), (UInt8*)(rawSignature)); DSUtilEncodeBase64((const char*)rawSignature, size, base64Signature, 1023); base64Signature[1023] = '\0'; strBase64Signature.assign(base64Signature); DSERROR(facility, "challenge data is successfully signed."); delete []base64Signature; delete []rawSignature; return true; }This code runs as a part of daemon on the client. I have written a test application (not a daemon) using same code and when I execute test application it prompts me for username/password in order to access the keychain. Once I provide username/password everything works fine.But when I execute same code through daemon (client-server communication), it doesn't prompt for username/password. So is there any way or API to skip the password required since daemon runs as system user?Coming from windows background, service (daemon) on windows can access the private key.I have tried following options so far:impersonate to current user from daemon so that user gets the authorisation prompt. But no prompt for username/password. I am expecting prompt when SecTransformExecute is executed ( as in my test application). But it fails with error "Error Domain=Internal CSSM error Code=-2147415839 "Internal error #800108e1 at SignTransform_block_invoke".try to read Access Control List of the certificate and modify access for this certificate so that it doesn't prompt for password everytime my app tries for access.SecAccessRef secaccess; OSStatus ret = SecKeychainItemCopyAccess(pKeychain, &secaccess); SecKeychainItemCopyAccess fails with error -25243 (The specified item has no access control ). 3. manually add my app in the access control from the keychain access.Only 3rd option is working. But I can't expect clients to add it manually as there could be multiple certificates setup for client/server communiation.Any suggestions? Is what I am trying to do possible on MacOS? If yes, how can I achieve it?
2
0
1.6k
Apr ’22
CGEventTapCreate fail on Mojave (10.14)
On MacOSX 10.14 (Mojave) the behavior changed, the following code runs on 10.13 but fail on 10.14.The creation of "CGEventTapCreate" is failing (returning null) on Mojave but works before.Any thoughts? Thanks in advance!// alterkeys.c // http://osxbook.com // // Complile using the following command line: // clang -Wall -o alterkeys alterkeys.c -framework ApplicationServices // #include <ApplicationServices/ApplicationServices.h> // This callback will be invoked every time there is a keystroke. // CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { // Paranoid sanity check. if ((type != kCGEventKeyDown) && (type != kCGEventKeyUp)) return event; // The incoming keycode. CGKeyCode keycode = (CGKeyCode)CGEventGetIntegerValueField( event, kCGKeyboardEventKeycode); // Swap 'a' (keycode=0) and 'z' (keycode=6). if (keycode == (CGKeyCode)0) keycode = (CGKeyCode)6; else if (keycode == (CGKeyCode)6) keycode = (CGKeyCode)0; // Set the modified keycode field in the event. CGEventSetIntegerValueField( event, kCGKeyboardEventKeycode, (int64_t)keycode); // We must return the event for it to be useful. return event; } int main(void) { CGEventMask eventMask = CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp); CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, myCGEventCallback, NULL); if (!eventTap) { fprintf(stderr, "failed to create event tap\n"); exit(1); } // Create a run loop source. CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource( kCFAllocatorDefault, eventTap, 0); // Add to the current run loop. CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); // Enable the event tap. CGEventTapEnable(eventTap, true); // Set it all running. CFRunLoopRun(); // In a real program, one would have arranged for cleaning up. exit(0); }
7
0
6.2k
Aug ’23
SFSafariViewController's `Save This Password?` prompt
In iOS 11, if `Settings > Safari > AutoFill > Names and Passwords` is set to `True`, then SFSafariViewController prompts `Save This Password?` alert/actionSheet. However, dismissing the `SFSafariViewController`, dismissing the alert before user has a chance to respond to the alert. How shall I take control of the alert and dismiss the SFSafariViewController only when user has responded to an alert?Thank you!Regards,Nimesh
3
0
3.4k
Feb ’23
Mark the iOS app content not to be backed up when doing unencrypted backup in iTunes
Hi,is there an option to mark the file or folder or item stored in user defaults ... not to be backed up when doing unencrypted backup in iTunes?We are developing iOS app that contains sensitive data. But even if we enable Data Protection for the iOS app it can be backed up on mac unencrypted using iTunes. Is there a way to allow backing up content only if the backup is encrypted?
2
0
1.9k
Oct ’25
remove certificate from keychaine ios swift
I want to remove certificate from keychaine using:let removeKeyQuery: [String: Any] = [kSecClass as String: kSecClassKey, kSecAttrLabel as String: "serverCertificate"] let status = SecItemDelete(removeKeyQuery as CFDictionary)I get the error errSecItemNotFound.And when I try to save it using:let getquery: [String: Any] = [kSecClass as String: kSecClassCertificate, kSecAttrLabel as String: "serverCertificate", kSecReturnRef as String: kCFBooleanTrue] var item: CFTypeRef? let status = SecItemCopyMatching(getquery as CFDictionary, &item) guard status == errSecSuccess else { print("Certificate not found") return nil } let certificate = item as! SecCertificateI get errSecSuccess and i get the certificate.
2
0
1k
Nov ’21
Unique RSA KeyChain item
During the creation of several key items, I noticed that there are several 'label' or 'tag' options. I did some investigation and I found three different, interesting, values.kSecAttrApplicationTag - A key whose value indicates the item's private tag.kSecAttrApplicationLabel - A key whose value indicates the item's application label.kSecAttrLabel - A key whose value is a string indicating the item's label.I read that the kSecAttrLabel is "human readable data". But what exactly is meant with the description of the kSecAttrApplicationTag? What exactly is the private tag.Another question I have is, how can I uniquely identify a key. Say I want to have a single key to encrypt a specific file, how would I go about doing so? Theoretically, I could set the kSecAttrApplicationLabel, as this has to be a unique value, meaing if I were to set the value to "com.app.appname.someidentifier".data(using: .utf8)! an error would occur if the key would (accidentally) be created again (which is what I want to prevent). However the discussion says "in particular, for keys of class kSecAttrKeyClassPublic and kSecAttrKeyClassPrivate, the value of this attribute is the hash of the public key", and RSA keys do have the public/private class, so the value would no longer be the hash of the public key. Am I actually allowed to overwrite the kSecAttrApplicationLabel? If not, do I have to check if a key for kSecAttrApplicationTag/kSecAttrLabel already exists and delete it first, before adding a new 'unique' key?Thanks in advance!
5
0
4.2k
Dec ’21
OS X custom login authentication
Hai, I need to authenticate the users at login with my own logic like, For eg: calling an external authentication server and using OpenDirectory in case if the server is not reachable.I know that i need to create an authorization plugin like the apple's sample code (NullAuthPlugin,NameAndPassword) and add an entry in authorizationdb at 'system.login.console' right to invoke my plugin to achieve this. NameAndPassword sample suggests to use different UI(using SFAuthorizationPluginView) other than the "loginwindow:login" to customize the login. Can I able to achieve my requirement without replacing the loginwindow GUI ie the mechanism "loginwindow:login"?? ie, Can i able to achieve this by keeping the existing mac's login screen as such and obtain the credentials to perform my own authentication ?? If possbile where should i place my mechanism at 'system.login.console' ?I think of replacing the <string>builtin:authenticate,privileged</string> with my own plugin to achieve my requirement ? Is it OK to replace the buitin login mechanism ?Is my approach correct ? Can anyone help me to clarify regarding this ?
4
0
3.4k
May ’22
How to obfuscate String literals?
Is there any compiler flag that we can use to entirely obfuscate string literals?Quick example, an app contains urls for different servers:fileprivate extension Environment { var url: String { switch self { case .dev: return "https://mydevserver.com/api" case .prod: return "https://myprodserver.com/api" } }But once the binary is compiled, it's quite easy to just open it and see the string inside.https://i.ibb.co/3M2zX0F/Screen-Shot.pngInitially, I thought this was just related to Swift literals, but further testing indicates that it also happens to Obj-C string literals.Shouldn't the compiled code be a safe binary, at least obfuscating any literals inside the code base?I would rather not take the path of manipulating the string in the code base, like using it encrypted, base64, or scrambled string literals mixing parts of string, etc...
5
0
7.5k
Mar ’23
Apple-App-Site-Association (AASA) behind VPN but Phone is in VPN
Hi,we are currently trying to test universal links also on our development server which is behind a VPN. From my understanding, correct if I am wrong, I thought it is enough that during app installation, the corresponding device (iPhone) is also connected via VPN so that iOS is able to download the AASA file?But at the moment I am not able to test this successfully. So my question is, is that possible in general to put the file on a server which is only reachable via VPN, and if yes, what could be the error?Best regardsChris
3
0
11k
Jul ’22
CryptoKit TOTP Generation
HiI'm using the new CryptoKit to generate a 6 or 8 digit TOTP code. Anyone been successful doing this?Using Xcode 11 BETA 5, targeting iOS 13 and Swift 5.1. Here is a snippet of generating an TOTP via CommonCrypto versus CryptoKit in playground (BETA). The base32Decode function returns Data.import CryptoKit import CommonCrypto import Foundation let period = TimeInterval(30) let digits = 6 let secret = base32Decode(value: "5FAA5JZ7WHO5WDNN")! var counter = UInt64(Date().timeIntervalSince1970 / period).bigEndian func cryptoKitOTP() { // Generate the key based on the counter. let key = SymmetricKey(data: Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter))) let hash = HMAC<Insecure.SHA1>.authenticationCode(for: secret, using: key) var truncatedHash = hash.withUnsafeBytes { ptr -> UInt32 in let offset = ptr[hash.byteCount - 1] & 0x0f let truncatedHashPtr = ptr.baseAddress! + Int(offset) return truncatedHashPtr.bindMemory(to: UInt32.self, capacity: 1).pointee } truncatedHash = UInt32(bigEndian: truncatedHash) truncatedHash = truncatedHash & 0x7FFF_FFFF truncatedHash = truncatedHash % UInt32(pow(10, Float(digits))) print("CryptoKit OTP value: \(String(format: "%0*u", digits, truncatedHash))") } func commonCryptoOTP() { let key = Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter)) let (hashAlgorithm, hashLength) = (CCHmacAlgorithm(kCCHmacAlgSHA1), Int(CC_SHA1_DIGEST_LENGTH)) let hashPtr = UnsafeMutablePointer.allocate(capacity: Int(hashLength)) defer { hashPtr.deallocate() } secret.withUnsafeBytes { secretBytes in // Generate the key from the counter value. counterData.withUnsafeBytes { counterBytes in CCHmac(hashAlgorithm, secretBytes.baseAddress, secret.count, counterBytes.baseAddress, key.count, hashPtr) } } let hash = Data(bytes: hashPtr, count: Int(hashLength)) var truncatedHash = hash.withUnsafeBytes { ptr -> UInt32 in let offset = ptr[hash.count - 1] & 0x0F let truncatedHashPtr = ptr.baseAddress! + Int(offset) return truncatedHashPtr.bindMemory(to: UInt32.self, capacity: 1).pointee } truncatedHash = UInt32(bigEndian: truncatedHash) truncatedHash = truncatedHash & 0x7FFF_FFFF truncatedHash = truncatedHash % UInt32(pow(10, Float(digits))) print("CommonCrypto OTP value: \(String(format: "%0*u", digits, truncatedHash))") } func otp() { commonCryptoOTP() cryptoKitOTP() } otp()The output based on now as in 2:28pm is: CommonCrypto OTP value: 819944 CryptoKit OTP value: 745890To confirm the OTP value, I used oathtool which you can brew install to generate an array of TOTP's. For example:oathtool --totp --base32 5FAA5JZ7WHO5WDNN -w 10Craig
7
0
6.0k
May ’22
Keychain error -25308
I've implemented a VPN app (with Packet tunnel Provider) for MacOS.Each user has a password, which I'm saving at the keychain with a persistentReference.For some users (not many), the app fails to save the password and I got error -25308 which is User interaction is not allowed.Why does it happening and how can I solve it?
Replies
10
Boosts
0
Views
16k
Activity
May ’22
Use kSecAttrAccessControl to only protect the private key in a SecIdentityRef
I try to use SecPKCS12Import to retrieve SecIdentityRef from PKCS#12 blob and store SecCertificateRef & SecKeyRef into keychain separately, so that I can use kSecAttrAccessControl to only protect private key with TouchID. The same code works on iOS, but not on Mac. The problem is SecPKCS12Import already saved the identity into keychain. I tried to delete the stored identity, however, no matter using SecItemDelete with transient reference or persistent reference of identity or delete both SecCertficateRef and SecKeyRef, the record will be deleted from keychain -> My Certificates and keychain -> Keys, but alwasy leave the certficate in keychain -> Certificates. If I use SecItemAdd to add certificate back, I got errSecDuplicateItem, using SecItemCopyMatching or SecItemDelete, I got errSecItemNotFound. The strange part is, even I open keychain app to manually delete the cert, I got error prompt saying deleting item not found, but after that, the cert disppear from keychain -> Certificates.Since I cannot delete identity and the add it back with access control attributes. I tried to use SecItemImport to avoid saving identity into keychain. However, this API only returns list of SecCertificateRef instead of SecIdentityRef. I found similar issue discussed on https://forums.developer.apple.com/thread/31711Is there anyway to retreive identity from PKCS#12 blob and make kSecAttrAccessControl protect the private key only?
Replies
9
Boosts
0
Views
3k
Activity
Nov ’22
Trying to use kSecACLAuthorizationPartitionID
Hi,I am trying to figure out how I can set the kSecACLAuthorizationPartitionID when creating a private key that will later be used by the macOS system ("apple:"). This key is to be used for things like Wi-Fi (eapolagent) and so on.I have been experimenting with the below code, the private key is created correctly, ACL is set and it is added to the keychain, however it seems it is overwritten when I add the key to the keychain: // create standard access SecAccessRef access = SecAccessCreateWithOwnerAndACL(0, 0, kSecUseOnlyUID, NULL, &error); // build partitions list NSMutableArray* partitions = [[NSMutableArray alloc] init]; // we want the apple system to be able to sign with this key [partitions addObject:@"apple:"]; NSMutableDictionary *descriptionDict = [[NSMutableDictionary alloc] init]; [descriptionDict setObject:(__bridge id)partitions forKey:(__bridge id)@"Partitions"]; NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:descriptionDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error]; SecACLRef newAcl = NULL; status = SecACLCreateWithSimpleContents(access, NULL, (CFStringRef)[self hexStringValue:xmlData], kSecKeychainPromptRequirePassphase, &newAcl); NSArray* authorizations = @[(__bridge id)kSecACLAuthorizationPartitionID]; // update ACL status = SecACLUpdateAuthorizations(newAcl, (__bridge CFArrayRef) authorizations);At this point, if I loop through the access ACLS, all look well.And I proceed to create the key:SecKeyRef privateKey = SecKeyCreateFromData((CFDictionaryRef)attributes, (CFDataRef)encodedKeyData, &error);And then add this to the keychain with the access I created above NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init]; [attributes setObject:(__bridge id)privateKey forKey:(id)kSecValueRef]; [attributes setObject:(id)kSecClassKey forKey:(id)kSecClass]; [attributes setObject:tag forKey:(id)kSecAttrApplicationTag]; [attributes setObject:(__bridge id)access forKey:(__bridge id)kSecAttrAccess ]; err = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL);All this runs without error, however dumping the keychain, I can see the ACL as follows: entry 0: authorizations (1): any don't-require-password description: <NULL> applications: <null> entry 1: authorizations (1): partition_id don't-require-password description: unsigned: applications: <null> entry 2: authorizations (1): change_acl don't-require-password description: <NULL> applications: <null>The "unsigned:" is I assume due to me running the app in debug mode, but it looks like the ACL I set is ignored and the keychain API hardcodes this to the caller partition_id.I have also tried to set the partition_id after adding the key to the keychain, but this requires the password of the User, something we do not want to request for obvious reasons.Is what I am trying even possible? Can you set the partition_id when creating a key?Thanks,S.
Replies
18
Boosts
0
Views
3.5k
Activity
Aug ’22
Can I delete keychain content when User uninstall App?
I store certificate (as SecIdentity ) in keychain because my application needs clientCertficate.I know when a User uninstall application, keychian content still exist.But in My application, I manage userInformation client certificate and CoreData.So, I want to delete keychain content when user uninstall application for not occering mismatch between Keychain and CoreData.Is it possible to do above ?Or should I delete keychain content when the app re-installed ?
Replies
3
Boosts
0
Views
7.3k
Activity
Aug ’23
Read Device Email and Name Information
Dear All,We have to read the device email id information ( apple cloud id or any gmail and email id ) and also i have to get the device name which is user menstioned in apple phone.One of the customer expecting to to fech the user email id and name of information to get in mobile apps while filling the forms to automatically detected to end user.kindly confirm me is to possible as per apple policy and giudelines.
Replies
2
Boosts
0
Views
1k
Activity
Jan ’23
SecCertificate data access
Hi. I'm working on a security related swift application, and I need som info from certificates stored in SecIdentities. Although I can access to SecCertificate to extract some info (serialnumber, common name, subject name) y can't find any example of function (or OSX API documentation) for other data extraction, like validity date (from/until), DER encoded public key, certificate usage policies, etc.I'm using Xcode 8.2.1 (Swift 3.0.2).Thank you in advance.
Replies
6
Boosts
0
Views
5.8k
Activity
Nov ’22
Integrating TouchID with Authorization Services
I'm currently using authorization services in a factored app(user mode app + privileged helper tool). When performing a privilged operation, the user is prompted for their password. How can I also allow authentication through touch ID?Additional info:Device: MacBook Pro (15-inch, 2017)macOS version: 10.13.4 (17E202)The code is adapted from the EvenBetterAuthorizationSample, so nothing fancy going on there.I also dug around a bit through /usr/libexec/authopen which does allow the user to choose between TouchID and password. If use codesign to change it's signature, only the password prompt is shown. Am I correct to assume that this feature is currently available only for Apple signed applications/binaries?As an alternative, I also fiddled around with LocalAuthentication which works great for a standalone app, but does it provide a way of passing the context between processes, as with AuthorizationMakeExternalForm?
Replies
8
Boosts
0
Views
4.6k
Activity
Jul ’22
Integrating Touch ID with Access To Multiple Users in iOS.
I have been working on integrating Touch ID in my iOS application. If the multiple fingerprints are registered at the OS level.Is there anyway to know which fingerprint was scanned. (not the fingerprint infodata just like a unique key)For example :- There are three fingerprint in the iOS DeviceIf fingerprint one is scanned then perform Task A.If fingerprint two is scanned then perform Task C.If fingerprint Three is scanned then perform Task B.
Replies
2
Boosts
0
Views
1.2k
Activity
Jul ’23
accessing private key without username/password from daemon
I am trying to read the private key from certificate in the system keychain on the client to sign random data send by the server.Note that the certificates aren't distributed by me. Users will install the certificate(s) either by downloading them from the different servers or importing pkcs file.I am using below code.std::string osxPrivateKey::signData(const uint8_t* pData, uint32_t nDataSize, vector <uint8_t>& aSignature) { OSStatus nStatus; osxObject<SecTransformRef> signer; CFDataRef rawData = CFDataCreate(NULL, (const uint8_t*)pHash, nHashSize); CFErrorRef error; SecTransformRef signerRef = SecSignTransformCreate(m_privKey.get(), &error); signer.set(signerRef); if (error) { return false; } SecTransformSetAttribute(signer.get(), kSecTransformInputAttributeName, rawData, &error); SecTransformSetAttribute(signer.get(), kSecInputIsAttributeName , kSecInputIsPlainText, &error); //SecTransformSetAttribute(signer.get(), kSecPaddingKey, kSecPaddingPKCS1Key, &error); //SecTransformSetAttribute(signer.get(), kSecDigestTypeAttribute, kSecDigestSHA1, NULL); SecTransformSetAttribute(signer.get(), kSecDigestTypeAttribute, kSecDigestSHA2, NULL); int digestLength = 160; //if (type ==2) digestLength = 256; CFNumberRef dLen = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &digestLength); Boolean set = SecTransformSetAttribute(signer.get(), kSecDigestLengthAttribute, dLen, &error); CFRelease(dLen); if (error) { return false; } DSVERBOSE(Sardeep, "SecTransformExecute begin"); Boolean allowed; SecKeychainGetUserInteractionAllowed(&allowed); DSVERBOSE(Sardeep, "SecKeychainGetUserInteractionAllowed '%d'", allowed); SecKeychainSetUserInteractionAllowed(true); CFDataRef signature = (CFDataRef)SecTransformExecute(signer.get(), &error); if (error) { CFStringRef errorDesc = CFErrorCopyDescription(error); CFIndex length = CFStringGetLength(errorDesc); CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char *buffer = (char *)malloc(maxSize); CFStringGetCString(errorDesc, buffer, maxSize, kCFStringEncodingUTF8); DSERROR(facility, "SecTransformExecute error : '%s'", buffer); delete buffer; return false; } DSVERBOSE(Sardeep, "SecTransformExecute end"); m_signHashAlgo = HCCertUtils::SIGN_HASH_ALGO_SHA256; char* base64Signature = new char[1024]; unsigned char* rawSignature = new unsigned char[1024]; int size = CFDataGetLength(signature); CFDataGetBytes(signature, CFRangeMake(0,CFDataGetLength(signature)), (UInt8*)(rawSignature)); DSUtilEncodeBase64((const char*)rawSignature, size, base64Signature, 1023); base64Signature[1023] = '\0'; strBase64Signature.assign(base64Signature); DSERROR(facility, "challenge data is successfully signed."); delete []base64Signature; delete []rawSignature; return true; }This code runs as a part of daemon on the client. I have written a test application (not a daemon) using same code and when I execute test application it prompts me for username/password in order to access the keychain. Once I provide username/password everything works fine.But when I execute same code through daemon (client-server communication), it doesn't prompt for username/password. So is there any way or API to skip the password required since daemon runs as system user?Coming from windows background, service (daemon) on windows can access the private key.I have tried following options so far:impersonate to current user from daemon so that user gets the authorisation prompt. But no prompt for username/password. I am expecting prompt when SecTransformExecute is executed ( as in my test application). But it fails with error "Error Domain=Internal CSSM error Code=-2147415839 "Internal error #800108e1 at SignTransform_block_invoke".try to read Access Control List of the certificate and modify access for this certificate so that it doesn't prompt for password everytime my app tries for access.SecAccessRef secaccess; OSStatus ret = SecKeychainItemCopyAccess(pKeychain, &secaccess); SecKeychainItemCopyAccess fails with error -25243 (The specified item has no access control ). 3. manually add my app in the access control from the keychain access.Only 3rd option is working. But I can't expect clients to add it manually as there could be multiple certificates setup for client/server communiation.Any suggestions? Is what I am trying to do possible on MacOS? If yes, how can I achieve it?
Replies
2
Boosts
0
Views
1.6k
Activity
Apr ’22
CGEventTapCreate fail on Mojave (10.14)
On MacOSX 10.14 (Mojave) the behavior changed, the following code runs on 10.13 but fail on 10.14.The creation of "CGEventTapCreate" is failing (returning null) on Mojave but works before.Any thoughts? Thanks in advance!// alterkeys.c // http://osxbook.com // // Complile using the following command line: // clang -Wall -o alterkeys alterkeys.c -framework ApplicationServices // #include <ApplicationServices/ApplicationServices.h> // This callback will be invoked every time there is a keystroke. // CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { // Paranoid sanity check. if ((type != kCGEventKeyDown) && (type != kCGEventKeyUp)) return event; // The incoming keycode. CGKeyCode keycode = (CGKeyCode)CGEventGetIntegerValueField( event, kCGKeyboardEventKeycode); // Swap 'a' (keycode=0) and 'z' (keycode=6). if (keycode == (CGKeyCode)0) keycode = (CGKeyCode)6; else if (keycode == (CGKeyCode)6) keycode = (CGKeyCode)0; // Set the modified keycode field in the event. CGEventSetIntegerValueField( event, kCGKeyboardEventKeycode, (int64_t)keycode); // We must return the event for it to be useful. return event; } int main(void) { CGEventMask eventMask = CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp); CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, myCGEventCallback, NULL); if (!eventTap) { fprintf(stderr, "failed to create event tap\n"); exit(1); } // Create a run loop source. CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource( kCFAllocatorDefault, eventTap, 0); // Add to the current run loop. CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); // Enable the event tap. CGEventTapEnable(eventTap, true); // Set it all running. CFRunLoopRun(); // In a real program, one would have arranged for cleaning up. exit(0); }
Replies
7
Boosts
0
Views
6.2k
Activity
Aug ’23
SFSafariViewController's `Save This Password?` prompt
In iOS 11, if `Settings > Safari > AutoFill > Names and Passwords` is set to `True`, then SFSafariViewController prompts `Save This Password?` alert/actionSheet. However, dismissing the `SFSafariViewController`, dismissing the alert before user has a chance to respond to the alert. How shall I take control of the alert and dismiss the SFSafariViewController only when user has responded to an alert?Thank you!Regards,Nimesh
Replies
3
Boosts
0
Views
3.4k
Activity
Feb ’23
Mark the iOS app content not to be backed up when doing unencrypted backup in iTunes
Hi,is there an option to mark the file or folder or item stored in user defaults ... not to be backed up when doing unencrypted backup in iTunes?We are developing iOS app that contains sensitive data. But even if we enable Data Protection for the iOS app it can be backed up on mac unencrypted using iTunes. Is there a way to allow backing up content only if the backup is encrypted?
Replies
2
Boosts
0
Views
1.9k
Activity
Oct ’25
remove certificate from keychaine ios swift
I want to remove certificate from keychaine using:let removeKeyQuery: [String: Any] = [kSecClass as String: kSecClassKey, kSecAttrLabel as String: "serverCertificate"] let status = SecItemDelete(removeKeyQuery as CFDictionary)I get the error errSecItemNotFound.And when I try to save it using:let getquery: [String: Any] = [kSecClass as String: kSecClassCertificate, kSecAttrLabel as String: "serverCertificate", kSecReturnRef as String: kCFBooleanTrue] var item: CFTypeRef? let status = SecItemCopyMatching(getquery as CFDictionary, &item) guard status == errSecSuccess else { print("Certificate not found") return nil } let certificate = item as! SecCertificateI get errSecSuccess and i get the certificate.
Replies
2
Boosts
0
Views
1k
Activity
Nov ’21
Unique RSA KeyChain item
During the creation of several key items, I noticed that there are several 'label' or 'tag' options. I did some investigation and I found three different, interesting, values.kSecAttrApplicationTag - A key whose value indicates the item's private tag.kSecAttrApplicationLabel - A key whose value indicates the item's application label.kSecAttrLabel - A key whose value is a string indicating the item's label.I read that the kSecAttrLabel is "human readable data". But what exactly is meant with the description of the kSecAttrApplicationTag? What exactly is the private tag.Another question I have is, how can I uniquely identify a key. Say I want to have a single key to encrypt a specific file, how would I go about doing so? Theoretically, I could set the kSecAttrApplicationLabel, as this has to be a unique value, meaing if I were to set the value to "com.app.appname.someidentifier".data(using: .utf8)! an error would occur if the key would (accidentally) be created again (which is what I want to prevent). However the discussion says "in particular, for keys of class kSecAttrKeyClassPublic and kSecAttrKeyClassPrivate, the value of this attribute is the hash of the public key", and RSA keys do have the public/private class, so the value would no longer be the hash of the public key. Am I actually allowed to overwrite the kSecAttrApplicationLabel? If not, do I have to check if a key for kSecAttrApplicationTag/kSecAttrLabel already exists and delete it first, before adding a new 'unique' key?Thanks in advance!
Replies
5
Boosts
0
Views
4.2k
Activity
Dec ’21
OS X custom login authentication
Hai, I need to authenticate the users at login with my own logic like, For eg: calling an external authentication server and using OpenDirectory in case if the server is not reachable.I know that i need to create an authorization plugin like the apple's sample code (NullAuthPlugin,NameAndPassword) and add an entry in authorizationdb at 'system.login.console' right to invoke my plugin to achieve this. NameAndPassword sample suggests to use different UI(using SFAuthorizationPluginView) other than the "loginwindow:login" to customize the login. Can I able to achieve my requirement without replacing the loginwindow GUI ie the mechanism "loginwindow:login"?? ie, Can i able to achieve this by keeping the existing mac's login screen as such and obtain the credentials to perform my own authentication ?? If possbile where should i place my mechanism at 'system.login.console' ?I think of replacing the <string>builtin:authenticate,privileged</string> with my own plugin to achieve my requirement ? Is it OK to replace the buitin login mechanism ?Is my approach correct ? Can anyone help me to clarify regarding this ?
Replies
4
Boosts
0
Views
3.4k
Activity
May ’22
How to obfuscate String literals?
Is there any compiler flag that we can use to entirely obfuscate string literals?Quick example, an app contains urls for different servers:fileprivate extension Environment { var url: String { switch self { case .dev: return "https://mydevserver.com/api" case .prod: return "https://myprodserver.com/api" } }But once the binary is compiled, it's quite easy to just open it and see the string inside.https://i.ibb.co/3M2zX0F/Screen-Shot.pngInitially, I thought this was just related to Swift literals, but further testing indicates that it also happens to Obj-C string literals.Shouldn't the compiled code be a safe binary, at least obfuscating any literals inside the code base?I would rather not take the path of manipulating the string in the code base, like using it encrypted, base64, or scrambled string literals mixing parts of string, etc...
Replies
5
Boosts
0
Views
7.5k
Activity
Mar ’23
Apple-App-Site-Association (AASA) behind VPN but Phone is in VPN
Hi,we are currently trying to test universal links also on our development server which is behind a VPN. From my understanding, correct if I am wrong, I thought it is enough that during app installation, the corresponding device (iPhone) is also connected via VPN so that iOS is able to download the AASA file?But at the moment I am not able to test this successfully. So my question is, is that possible in general to put the file on a server which is only reachable via VPN, and if yes, what could be the error?Best regardsChris
Replies
3
Boosts
0
Views
11k
Activity
Jul ’22
CryptoKit TOTP Generation
HiI'm using the new CryptoKit to generate a 6 or 8 digit TOTP code. Anyone been successful doing this?Using Xcode 11 BETA 5, targeting iOS 13 and Swift 5.1. Here is a snippet of generating an TOTP via CommonCrypto versus CryptoKit in playground (BETA). The base32Decode function returns Data.import CryptoKit import CommonCrypto import Foundation let period = TimeInterval(30) let digits = 6 let secret = base32Decode(value: "5FAA5JZ7WHO5WDNN")! var counter = UInt64(Date().timeIntervalSince1970 / period).bigEndian func cryptoKitOTP() { // Generate the key based on the counter. let key = SymmetricKey(data: Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter))) let hash = HMAC<Insecure.SHA1>.authenticationCode(for: secret, using: key) var truncatedHash = hash.withUnsafeBytes { ptr -> UInt32 in let offset = ptr[hash.byteCount - 1] & 0x0f let truncatedHashPtr = ptr.baseAddress! + Int(offset) return truncatedHashPtr.bindMemory(to: UInt32.self, capacity: 1).pointee } truncatedHash = UInt32(bigEndian: truncatedHash) truncatedHash = truncatedHash & 0x7FFF_FFFF truncatedHash = truncatedHash % UInt32(pow(10, Float(digits))) print("CryptoKit OTP value: \(String(format: "%0*u", digits, truncatedHash))") } func commonCryptoOTP() { let key = Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter)) let (hashAlgorithm, hashLength) = (CCHmacAlgorithm(kCCHmacAlgSHA1), Int(CC_SHA1_DIGEST_LENGTH)) let hashPtr = UnsafeMutablePointer.allocate(capacity: Int(hashLength)) defer { hashPtr.deallocate() } secret.withUnsafeBytes { secretBytes in // Generate the key from the counter value. counterData.withUnsafeBytes { counterBytes in CCHmac(hashAlgorithm, secretBytes.baseAddress, secret.count, counterBytes.baseAddress, key.count, hashPtr) } } let hash = Data(bytes: hashPtr, count: Int(hashLength)) var truncatedHash = hash.withUnsafeBytes { ptr -> UInt32 in let offset = ptr[hash.count - 1] & 0x0F let truncatedHashPtr = ptr.baseAddress! + Int(offset) return truncatedHashPtr.bindMemory(to: UInt32.self, capacity: 1).pointee } truncatedHash = UInt32(bigEndian: truncatedHash) truncatedHash = truncatedHash & 0x7FFF_FFFF truncatedHash = truncatedHash % UInt32(pow(10, Float(digits))) print("CommonCrypto OTP value: \(String(format: "%0*u", digits, truncatedHash))") } func otp() { commonCryptoOTP() cryptoKitOTP() } otp()The output based on now as in 2:28pm is: CommonCrypto OTP value: 819944 CryptoKit OTP value: 745890To confirm the OTP value, I used oathtool which you can brew install to generate an array of TOTP's. For example:oathtool --totp --base32 5FAA5JZ7WHO5WDNN -w 10Craig
Replies
7
Boosts
0
Views
6.0k
Activity
May ’22