[PATCH wireguard-apple] Keychain: use data protection keychain on macOS

Kilian Ries mail at kilian-ries.de
Mon Oct 5 13:52:04 UTC 2026


On macOS, tunnel configurations are stored in the file-based login
keychain, with an access list that names the app and the network
extension. On a Mac enrolled through account-driven enrollment, apps
installed by MDM keep their data on a separate "Managed Data" volume.
There is no login keychain for those apps, so SecItemAdd tries to create
one, and the sandbox refuses:

  authd: Sandbox denied authorizing right 'system.keychain.create.loginkc' by client '/Applications/WireGuard.app'
  WireGuard: Unable to add config to keychain: -60005
  WireGuard: Add: Saving configuration failed: Error Domain=NEVPNErrorDomain Code=1 "Missing protocol or protocol has invalid type"

In that state no tunnel can be added or imported.

Store new items in the data protection keychain instead, in the app
group that the app and the network extension already share, as on iOS.
The access list is not needed there, because the shared access group
grants the network extension access.

Items created by earlier versions stay in the file-based keychain.
Reading, verifying and deleting a reference try the data protection
keychain first and then the file-based one, so existing tunnels keep
working. An existing tunnel moves to the data protection keychain the
next time it is saved.

Signed-off-by: Kilian Ries <mail at kilian-ries.de>
---

Notes:
    Seen on macOS 27.0.1 with WireGuard 1.0.16 from the App Store, on a Mac
    enrolled in Apple Business Manager through account-driven device
    enrollment. Apps installed there by MDM show a Personas entry in
    "pluginkit -mAvvv", and their containers live on the "Managed Data"
    APFS volume.
    
    Type-checked for macOS 12 and iOS 15. Not tested at runtime yet, since
    that needs a build signed for the app group.

 Sources/Shared/Keychain.swift | 96 +++++++++++++++++++----------------
 1 file changed, 51 insertions(+), 45 deletions(-)

diff --git a/Sources/Shared/Keychain.swift b/Sources/Shared/Keychain.swift
index 2e0e7f0..c99ea85 100644
--- a/Sources/Shared/Keychain.swift
+++ b/Sources/Shared/Keychain.swift
@@ -7,9 +7,8 @@ import Security
 class Keychain {
     static func openReference(called ref: Data) -> String? {
         var result: CFTypeRef?
-        let ret = SecItemCopyMatching([kSecValuePersistentRef: ref,
-                                        kSecReturnData: true] as CFDictionary,
-                                       &result)
+        let ret = firstSuccess([kSecValuePersistentRef: ref,
+                                kSecReturnData: true]) { SecItemCopyMatching($0, &result) }
         if ret != errSecSuccess || result == nil {
             wg_log(.error, message: "Unable to open config from keychain: \(ret)")
             return nil
@@ -19,7 +18,6 @@ class Keychain {
     }
 
     static func makeReference(containing value: String, called name: String, previouslyReferencedBy oldRef: Data? = nil) -> Data? {
-        var ret: OSStatus
         guard var bundleIdentifier = Bundle.main.bundleIdentifier else {
             wg_log(.error, staticMessage: "Unable to determine bundle identifier")
             return nil
@@ -40,38 +38,16 @@ class Keychain {
         items[kSecAttrAccessGroup] = FileManager.appGroupId
         items[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlock
         #elseif os(macOS)
+        items[kSecUseDataProtectionKeychain] = true
+        items[kSecAttrAccessGroup] = FileManager.appGroupId
         items[kSecAttrSynchronizable] = false
         items[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
-
-        guard let extensionPath = Bundle.main.builtInPlugInsURL?.appendingPathComponent("WireGuardNetworkExtension.appex", isDirectory: true).path else {
-            wg_log(.error, staticMessage: "Unable to determine app extension path")
-            return nil
-        }
-        var extensionApp: SecTrustedApplication?
-        var mainApp: SecTrustedApplication?
-        ret = SecTrustedApplicationCreateFromPath(extensionPath, &extensionApp)
-        if ret != kOSReturnSuccess || extensionApp == nil {
-            wg_log(.error, message: "Unable to create keychain extension trusted application object: \(ret)")
-            return nil
-        }
-        ret = SecTrustedApplicationCreateFromPath(nil, &mainApp)
-        if ret != errSecSuccess || mainApp == nil {
-            wg_log(.error, message: "Unable to create keychain local trusted application object: \(ret)")
-            return nil
-        }
-        var access: SecAccess?
-        ret = SecAccessCreate(itemLabel as CFString, [extensionApp!, mainApp!] as CFArray, &access)
-        if ret != errSecSuccess || access == nil {
-            wg_log(.error, message: "Unable to create keychain ACL object: \(ret)")
-            return nil
-        }
-        items[kSecAttrAccess] = access!
         #else
         #error("Unimplemented")
         #endif
 
         var ref: CFTypeRef?
-        ret = SecItemAdd(items as CFDictionary, &ref)
+        let ret = SecItemAdd(items as CFDictionary, &ref)
         if ret != errSecSuccess || ref == nil {
             wg_log(.error, message: "Unable to add config to keychain: \(ret)")
             return nil
@@ -83,32 +59,62 @@ class Keychain {
     }
 
     static func deleteReference(called ref: Data) {
-        let ret = SecItemDelete([kSecValuePersistentRef: ref] as CFDictionary)
+        let ret = firstSuccess([kSecValuePersistentRef: ref]) { SecItemDelete($0) }
         if ret != errSecSuccess {
             wg_log(.error, message: "Unable to delete config from keychain: \(ret)")
         }
     }
 
     static func deleteReferences(except whitelist: Set<Data>) {
-        var result: CFTypeRef?
-        let ret = SecItemCopyMatching([kSecClass: kSecClassGenericPassword,
-                                       kSecAttrService: Bundle.main.bundleIdentifier as Any,
-                                       kSecMatchLimit: kSecMatchLimitAll,
-                                       kSecReturnPersistentRef: true] as CFDictionary,
-                                      &result)
-        if ret != errSecSuccess || result == nil {
-            return
-        }
-        guard let items = result as? [Data] else { return }
-        for item in items {
-            if !whitelist.contains(item) {
-                deleteReference(called: item)
+        for query in keychainQueries([kSecClass: kSecClassGenericPassword,
+                                      kSecAttrService: Bundle.main.bundleIdentifier as Any,
+                                      kSecMatchLimit: kSecMatchLimitAll,
+                                      kSecReturnPersistentRef: true]) {
+            var result: CFTypeRef?
+            let ret = SecItemCopyMatching(query, &result)
+            if ret != errSecSuccess || result == nil {
+                continue
+            }
+            guard let items = result as? [Data] else { continue }
+            for item in items {
+                if !whitelist.contains(item) {
+                    deleteReference(called: item)
+                }
             }
         }
     }
 
     static func verifyReference(called ref: Data) -> Bool {
-        return SecItemCopyMatching([kSecValuePersistentRef: ref] as CFDictionary,
-                                   nil) != errSecItemNotFound
+        return firstSuccess([kSecValuePersistentRef: ref]) { SecItemCopyMatching($0, nil) } != errSecItemNotFound
+    }
+
+    /* On macOS, new items go into the data protection keychain. Items created by
+     * earlier versions live in the file-based login keychain, which does not exist
+     * for apps whose data the system keeps on a separate volume, such as apps
+     * installed by MDM. So every lookup tries the data protection keychain first
+     * and then the file-based one.
+     */
+    private static func keychainQueries(_ query: [CFString: Any]) -> [CFDictionary] {
+        #if os(macOS)
+        var dataProtectionQuery = query
+        dataProtectionQuery[kSecUseDataProtectionKeychain] = true
+        return [dataProtectionQuery as CFDictionary, query as CFDictionary]
+        #else
+        return [query as CFDictionary]
+        #endif
+    }
+
+    private static func firstSuccess(_ query: [CFString: Any], _ operation: (CFDictionary) -> OSStatus) -> OSStatus {
+        var ret = errSecItemNotFound
+        for query in keychainQueries(query) {
+            let status = operation(query)
+            if status == errSecSuccess {
+                return status
+            }
+            if status != errSecItemNotFound && status != errSecNoSuchKeychain {
+                ret = status
+            }
+        }
+        return ret
     }
 }
-- 
2.54.0 (Apple Git-157)



More information about the WireGuard mailing list