├── .gitignore ├── LICENSE ├── README.md ├── SecureEnclaveToken.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ ├── IDEWorkspaceChecks.plist │ │ └── swiftpm │ │ └── Package.resolved └── xcshareddata │ └── xcschemes │ ├── SecureEnclaveToken.xcscheme │ └── SecureEnclaveTokenExtension.xcscheme ├── SecureEnclaveToken ├── AppDelegate.swift ├── Assets.xcassets │ ├── AccentColor.colorset │ │ └── Contents.json │ ├── AppIcon.appiconset │ │ └── Contents.json │ └── Contents.json ├── ContentView.swift ├── Info.plist ├── Preview Content │ ├── Base.lproj │ │ └── Main.storyboard │ └── Preview Assets.xcassets │ │ └── Contents.json ├── SecureEnclaveToken.entitlements ├── SecureEnclaveTokenCLI.swift ├── SecureEnclaveTokenUtils.swift └── main.swift ├── SecureEnclaveTokenExtension ├── Info.plist ├── SecureEnclaveTokenExtension.entitlements ├── Token.swift ├── TokenDriver.swift └── TokenSession.swift └── images └── SecureEnclaveToken.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | .DS_Store 6 | 7 | ## User settings 8 | xcuserdata/ 9 | 10 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 11 | *.xcscmblueprint 12 | *.xccheckout 13 | 14 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 15 | build/ 16 | DerivedData/ 17 | *.moved-aside 18 | *.pbxuser 19 | !default.pbxuser 20 | *.mode1v3 21 | !default.mode1v3 22 | *.mode2v3 23 | !default.mode2v3 24 | *.perspectivev3 25 | !default.perspectivev3 26 | 27 | ## Obj-C/Swift specific 28 | *.hmap 29 | 30 | ## App packaging 31 | *.ipa 32 | *.dSYM.zip 33 | *.dSYM 34 | 35 | ## Playgrounds 36 | timeline.xctimeline 37 | playground.xcworkspace 38 | 39 | # Swift Package Manager 40 | # 41 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 42 | # Packages/ 43 | # Package.pins 44 | # Package.resolved 45 | # *.xcodeproj 46 | # 47 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 48 | # hence it is not needed unless you have added a package configuration file to your project 49 | # .swiftpm 50 | 51 | .build/ 52 | 53 | # CocoaPods 54 | # 55 | # We recommend against adding the Pods directory to your .gitignore. However 56 | # you should judge for yourself, the pros and cons are mentioned at: 57 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 58 | # 59 | # Pods/ 60 | # 61 | # Add this line if you want to avoid checking in source code from the Xcode workspace 62 | # *.xcworkspace 63 | 64 | # Carthage 65 | # 66 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 67 | # Carthage/Checkouts 68 | 69 | Carthage/Build/ 70 | 71 | # Accio dependency management 72 | Dependencies/ 73 | .accio/ 74 | 75 | # fastlane 76 | # 77 | # It is recommended to not store the screenshots in the git repo. 78 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 79 | # For more information about the recommended setup visit: 80 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 81 | 82 | fastlane/report.xml 83 | fastlane/Preview.html 84 | fastlane/screenshots/**/*.png 85 | fastlane/test_output 86 | 87 | # Code Injection 88 | # 89 | # After new code Injection tools there's a generated folder /iOSInjectionProject 90 | # https://github.com/johnno1962/injectionforxcode 91 | 92 | iOSInjectionProject/ 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Marcin Wielgoszewski 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SecureEnclaveToken Overview 2 | 3 | SecureEnclaveToken allows you to generate and use credentials backed by 4 | a cryptographic key stored on the Secure Enclave, protected with your 5 | fingerprint. SecureEnclaveToken provides a user interface for generating 6 | and deleting keys, creating certificate signing requests, and 7 | associating certificates with keys to establish an identity. This 8 | identity (comprised of key and certificate) can be used like that of an 9 | identity on a smartcard; e.g., authentication, establishing secured 10 | communication channels, etc. 11 | 12 | ## Building 13 | 14 | 1. Open .xcodeproj in Xcode 15 | 2. For each target under "Signing & Capabilities", configure the Team 16 | used for signing the application. 17 | 3. Run the application 18 | 19 | If you wish to build an installable version of the application, in the 20 | menu select Product > Archive. 21 | 22 | ## Steps to creating an identity 23 | 24 | 1. Launch SecureEnclaveToken.app. 25 | 2. Generate a key. Choose your key access control and security 26 | requirements. 27 | 3. Generate a certificate signing request. Use the text fields 28 | (Common Name, Email Address, etc) to specify attributes. 29 | 4. Submit your saved certificate request to your certificate authority, 30 | retrieve signed certificate and convert it to DER format with `.cer` 31 | extension. 32 | 5. Import signed certificate. On first use, you'll see a button that 33 | says "Query Token Configuration". If no certificate is currently 34 | loaded, you'll be prompted with an open file panel to select a 35 | certificate. 36 | 37 | Once you have a key generated and a signed certificate imported, the UI 38 | should indicate you have 2 token keychain items loaded. 39 | 40 | ![SecureEnclaveToken](https://github.com/mwielgoszewski/SecureEnclaveToken/blob/main/images/SecureEnclaveToken.png) 41 | 42 | ## Debugging 43 | 44 | To view the identities loaded in SecureEnclaveTokenExtension, run 45 | 46 | system_profiler SPSmartCardsDataType 47 | 48 | To list identites in your ctkd-db: 49 | 50 | defaults read ~/Library/Preferences/com.apple.security.ctkd-db 51 | 52 | Enable verbose logging for smartcard extensions (logs can be viewed in 53 | Console.app, under the SecureEnclaveTokenExtension process): 54 | 55 | sudo defaults write /Library/Preferences/com.apple.security.smartcard Logging 1 56 | 57 | 58 | ## References 59 | 60 | * [Gate](https://bitbucket.org/twocanoes/gate-secure-enclave-token-management) 61 | 62 | I happened to come across this late in my research, helped establish 63 | some patterns for working with the TKTokenConfiguration classes, of 64 | which documentation may as well have been non-existent. Similar 65 | CryptoTokenKit app extension, written in Objectivc-C. 66 | 67 | * [CertificateSigningRequest](https://github.com/cbaker6/CertificateSigningRequest) 68 | 69 | Swift package for generating certificate signing requests, written by 70 | Corey Baker. Components ported from [ios-csr](https://github.com/ateska/ios-csr) 71 | written by Ales Teska. 72 | -------------------------------------------------------------------------------- /SecureEnclaveToken.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 56; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | BD60D39425D58D6F0075CC34 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD60D39325D58D6F0075CC34 /* AppDelegate.swift */; }; 11 | BD60D39625D58D6F0075CC34 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD60D39525D58D6F0075CC34 /* ContentView.swift */; }; 12 | BD60D39825D58D6F0075CC34 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = BD60D39725D58D6F0075CC34 /* Assets.xcassets */; }; 13 | BD60D39B25D58D6F0075CC34 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = BD60D39A25D58D6F0075CC34 /* Preview Assets.xcassets */; }; 14 | BD60D39E25D58D6F0075CC34 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = BD60D39C25D58D6F0075CC34 /* Main.storyboard */; }; 15 | BD60D3AE25D58D9A0075CC34 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BD60D3AD25D58D9A0075CC34 /* Cocoa.framework */; }; 16 | BD60D3B125D58D9A0075CC34 /* Token.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD60D3B025D58D9A0075CC34 /* Token.swift */; }; 17 | BD60D3B325D58D9A0075CC34 /* TokenDriver.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD60D3B225D58D9A0075CC34 /* TokenDriver.swift */; }; 18 | BD60D3B525D58D9A0075CC34 /* TokenSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD60D3B425D58D9A0075CC34 /* TokenSession.swift */; }; 19 | BD60D3BA25D58D9A0075CC34 /* SecureEnclaveTokenExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = BD60D3AB25D58D9A0075CC34 /* SecureEnclaveTokenExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 20 | BD60D3C225D58E5A0075CC34 /* SecureEnclaveTokenUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD60D3C125D58E5A0075CC34 /* SecureEnclaveTokenUtils.swift */; }; 21 | BDE0445E25E0228C00C984E3 /* CertificateSigningRequest in Frameworks */ = {isa = PBXBuildFile; productRef = BDE0445D25E0228C00C984E3 /* CertificateSigningRequest */; }; 22 | D98B035928DF8CFE00D6EB1C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = D98B035828DF8CFE00D6EB1C /* main.swift */; }; 23 | D98B035C28DF955900D6EB1C /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = D98B035B28DF955900D6EB1C /* ArgumentParser */; }; 24 | D98B035E28E0915200D6EB1C /* SecureEnclaveTokenCLI.swift in Sources */ = {isa = PBXBuildFile; fileRef = D98B035D28E0915200D6EB1C /* SecureEnclaveTokenCLI.swift */; }; 25 | /* End PBXBuildFile section */ 26 | 27 | /* Begin PBXContainerItemProxy section */ 28 | BD60D3B825D58D9A0075CC34 /* PBXContainerItemProxy */ = { 29 | isa = PBXContainerItemProxy; 30 | containerPortal = BD60D38825D58D6F0075CC34 /* Project object */; 31 | proxyType = 1; 32 | remoteGlobalIDString = BD60D3AA25D58D9A0075CC34; 33 | remoteInfo = SecureEnclaveTokenExtension; 34 | }; 35 | /* End PBXContainerItemProxy section */ 36 | 37 | /* Begin PBXCopyFilesBuildPhase section */ 38 | BD60D3BE25D58D9A0075CC34 /* Embed App Extensions */ = { 39 | isa = PBXCopyFilesBuildPhase; 40 | buildActionMask = 2147483647; 41 | dstPath = ""; 42 | dstSubfolderSpec = 13; 43 | files = ( 44 | BD60D3BA25D58D9A0075CC34 /* SecureEnclaveTokenExtension.appex in Embed App Extensions */, 45 | ); 46 | name = "Embed App Extensions"; 47 | runOnlyForDeploymentPostprocessing = 0; 48 | }; 49 | BD6D6EE625DD910E00C507B4 /* Embed Frameworks */ = { 50 | isa = PBXCopyFilesBuildPhase; 51 | buildActionMask = 2147483647; 52 | dstPath = ""; 53 | dstSubfolderSpec = 10; 54 | files = ( 55 | ); 56 | name = "Embed Frameworks"; 57 | runOnlyForDeploymentPostprocessing = 0; 58 | }; 59 | D99219A828DF7DAE0088BA56 /* Embed CLI */ = { 60 | isa = PBXCopyFilesBuildPhase; 61 | buildActionMask = 2147483647; 62 | dstPath = ""; 63 | dstSubfolderSpec = 6; 64 | files = ( 65 | ); 66 | name = "Embed CLI"; 67 | runOnlyForDeploymentPostprocessing = 0; 68 | }; 69 | /* End PBXCopyFilesBuildPhase section */ 70 | 71 | /* Begin PBXFileReference section */ 72 | BD60D39025D58D6F0075CC34 /* SecureEnclaveToken.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SecureEnclaveToken.app; sourceTree = BUILT_PRODUCTS_DIR; }; 73 | BD60D39325D58D6F0075CC34 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 74 | BD60D39525D58D6F0075CC34 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; 75 | BD60D39725D58D6F0075CC34 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 76 | BD60D39A25D58D6F0075CC34 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; 77 | BD60D39D25D58D6F0075CC34 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 78 | BD60D39F25D58D6F0075CC34 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 79 | BD60D3A025D58D6F0075CC34 /* SecureEnclaveToken.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = SecureEnclaveToken.entitlements; sourceTree = ""; }; 80 | BD60D3AB25D58D9A0075CC34 /* SecureEnclaveTokenExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = SecureEnclaveTokenExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 81 | BD60D3AD25D58D9A0075CC34 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; 82 | BD60D3B025D58D9A0075CC34 /* Token.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Token.swift; sourceTree = ""; }; 83 | BD60D3B225D58D9A0075CC34 /* TokenDriver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenDriver.swift; sourceTree = ""; }; 84 | BD60D3B425D58D9A0075CC34 /* TokenSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenSession.swift; sourceTree = ""; }; 85 | BD60D3B625D58D9A0075CC34 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 86 | BD60D3B725D58D9A0075CC34 /* SecureEnclaveTokenExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = SecureEnclaveTokenExtension.entitlements; sourceTree = ""; }; 87 | BD60D3C125D58E5A0075CC34 /* SecureEnclaveTokenUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureEnclaveTokenUtils.swift; sourceTree = ""; }; 88 | D98B035828DF8CFE00D6EB1C /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; 89 | D98B035D28E0915200D6EB1C /* SecureEnclaveTokenCLI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureEnclaveTokenCLI.swift; sourceTree = ""; }; 90 | /* End PBXFileReference section */ 91 | 92 | /* Begin PBXFrameworksBuildPhase section */ 93 | BD60D38D25D58D6F0075CC34 /* Frameworks */ = { 94 | isa = PBXFrameworksBuildPhase; 95 | buildActionMask = 2147483647; 96 | files = ( 97 | D98B035C28DF955900D6EB1C /* ArgumentParser in Frameworks */, 98 | BDE0445E25E0228C00C984E3 /* CertificateSigningRequest in Frameworks */, 99 | ); 100 | runOnlyForDeploymentPostprocessing = 0; 101 | }; 102 | BD60D3A825D58D9A0075CC34 /* Frameworks */ = { 103 | isa = PBXFrameworksBuildPhase; 104 | buildActionMask = 2147483647; 105 | files = ( 106 | BD60D3AE25D58D9A0075CC34 /* Cocoa.framework in Frameworks */, 107 | ); 108 | runOnlyForDeploymentPostprocessing = 0; 109 | }; 110 | /* End PBXFrameworksBuildPhase section */ 111 | 112 | /* Begin PBXGroup section */ 113 | BD60D38725D58D6F0075CC34 = { 114 | isa = PBXGroup; 115 | children = ( 116 | BD60D39225D58D6F0075CC34 /* SecureEnclaveToken */, 117 | BD60D3AF25D58D9A0075CC34 /* SecureEnclaveTokenExtension */, 118 | BD60D3AC25D58D9A0075CC34 /* Frameworks */, 119 | BD60D39125D58D6F0075CC34 /* Products */, 120 | ); 121 | sourceTree = ""; 122 | }; 123 | BD60D39125D58D6F0075CC34 /* Products */ = { 124 | isa = PBXGroup; 125 | children = ( 126 | BD60D39025D58D6F0075CC34 /* SecureEnclaveToken.app */, 127 | BD60D3AB25D58D9A0075CC34 /* SecureEnclaveTokenExtension.appex */, 128 | ); 129 | name = Products; 130 | sourceTree = ""; 131 | }; 132 | BD60D39225D58D6F0075CC34 /* SecureEnclaveToken */ = { 133 | isa = PBXGroup; 134 | children = ( 135 | BD60D39325D58D6F0075CC34 /* AppDelegate.swift */, 136 | BD60D39525D58D6F0075CC34 /* ContentView.swift */, 137 | D98B035D28E0915200D6EB1C /* SecureEnclaveTokenCLI.swift */, 138 | BD60D3C125D58E5A0075CC34 /* SecureEnclaveTokenUtils.swift */, 139 | BD60D3A025D58D6F0075CC34 /* SecureEnclaveToken.entitlements */, 140 | BD60D39F25D58D6F0075CC34 /* Info.plist */, 141 | D98B035828DF8CFE00D6EB1C /* main.swift */, 142 | BD60D39725D58D6F0075CC34 /* Assets.xcassets */, 143 | BD60D39925D58D6F0075CC34 /* Preview Content */, 144 | ); 145 | path = SecureEnclaveToken; 146 | sourceTree = ""; 147 | }; 148 | BD60D39925D58D6F0075CC34 /* Preview Content */ = { 149 | isa = PBXGroup; 150 | children = ( 151 | BD60D39C25D58D6F0075CC34 /* Main.storyboard */, 152 | BD60D39A25D58D6F0075CC34 /* Preview Assets.xcassets */, 153 | ); 154 | path = "Preview Content"; 155 | sourceTree = ""; 156 | }; 157 | BD60D3AC25D58D9A0075CC34 /* Frameworks */ = { 158 | isa = PBXGroup; 159 | children = ( 160 | BD60D3AD25D58D9A0075CC34 /* Cocoa.framework */, 161 | ); 162 | name = Frameworks; 163 | sourceTree = ""; 164 | }; 165 | BD60D3AF25D58D9A0075CC34 /* SecureEnclaveTokenExtension */ = { 166 | isa = PBXGroup; 167 | children = ( 168 | BD60D3B025D58D9A0075CC34 /* Token.swift */, 169 | BD60D3B225D58D9A0075CC34 /* TokenDriver.swift */, 170 | BD60D3B425D58D9A0075CC34 /* TokenSession.swift */, 171 | BD60D3B625D58D9A0075CC34 /* Info.plist */, 172 | BD60D3B725D58D9A0075CC34 /* SecureEnclaveTokenExtension.entitlements */, 173 | ); 174 | path = SecureEnclaveTokenExtension; 175 | sourceTree = ""; 176 | }; 177 | /* End PBXGroup section */ 178 | 179 | /* Begin PBXNativeTarget section */ 180 | BD60D38F25D58D6F0075CC34 /* SecureEnclaveToken */ = { 181 | isa = PBXNativeTarget; 182 | buildConfigurationList = BD60D3A325D58D6F0075CC34 /* Build configuration list for PBXNativeTarget "SecureEnclaveToken" */; 183 | buildPhases = ( 184 | BD60D38C25D58D6F0075CC34 /* Sources */, 185 | BD60D38D25D58D6F0075CC34 /* Frameworks */, 186 | BD60D38E25D58D6F0075CC34 /* Resources */, 187 | BD60D3BE25D58D9A0075CC34 /* Embed App Extensions */, 188 | BD6D6EE625DD910E00C507B4 /* Embed Frameworks */, 189 | D99219A828DF7DAE0088BA56 /* Embed CLI */, 190 | ); 191 | buildRules = ( 192 | ); 193 | dependencies = ( 194 | BD60D3B925D58D9A0075CC34 /* PBXTargetDependency */, 195 | ); 196 | name = SecureEnclaveToken; 197 | packageProductDependencies = ( 198 | BDE0445D25E0228C00C984E3 /* CertificateSigningRequest */, 199 | D98B035B28DF955900D6EB1C /* ArgumentParser */, 200 | ); 201 | productName = SecureEnclaveToken; 202 | productReference = BD60D39025D58D6F0075CC34 /* SecureEnclaveToken.app */; 203 | productType = "com.apple.product-type.application"; 204 | }; 205 | BD60D3AA25D58D9A0075CC34 /* SecureEnclaveTokenExtension */ = { 206 | isa = PBXNativeTarget; 207 | buildConfigurationList = BD60D3BB25D58D9A0075CC34 /* Build configuration list for PBXNativeTarget "SecureEnclaveTokenExtension" */; 208 | buildPhases = ( 209 | BD60D3A725D58D9A0075CC34 /* Sources */, 210 | BD60D3A825D58D9A0075CC34 /* Frameworks */, 211 | BD60D3A925D58D9A0075CC34 /* Resources */, 212 | ); 213 | buildRules = ( 214 | ); 215 | dependencies = ( 216 | ); 217 | name = SecureEnclaveTokenExtension; 218 | productName = SecureEnclaveTokenExtension; 219 | productReference = BD60D3AB25D58D9A0075CC34 /* SecureEnclaveTokenExtension.appex */; 220 | productType = "com.apple.product-type.app-extension"; 221 | }; 222 | /* End PBXNativeTarget section */ 223 | 224 | /* Begin PBXProject section */ 225 | BD60D38825D58D6F0075CC34 /* Project object */ = { 226 | isa = PBXProject; 227 | attributes = { 228 | LastSwiftUpdateCheck = 1400; 229 | LastUpgradeCheck = 1320; 230 | TargetAttributes = { 231 | BD60D38F25D58D6F0075CC34 = { 232 | CreatedOnToolsVersion = 12.4; 233 | }; 234 | BD60D3AA25D58D9A0075CC34 = { 235 | CreatedOnToolsVersion = 12.4; 236 | }; 237 | }; 238 | }; 239 | buildConfigurationList = BD60D38B25D58D6F0075CC34 /* Build configuration list for PBXProject "SecureEnclaveToken" */; 240 | compatibilityVersion = "Xcode 14.0"; 241 | developmentRegion = en; 242 | hasScannedForEncodings = 0; 243 | knownRegions = ( 244 | en, 245 | Base, 246 | ); 247 | mainGroup = BD60D38725D58D6F0075CC34; 248 | packageReferences = ( 249 | BDE0445C25E0228C00C984E3 /* XCRemoteSwiftPackageReference "CertificateSigningRequest" */, 250 | D98B035A28DF955900D6EB1C /* XCRemoteSwiftPackageReference "swift-argument-parser" */, 251 | ); 252 | productRefGroup = BD60D39125D58D6F0075CC34 /* Products */; 253 | projectDirPath = ""; 254 | projectRoot = ""; 255 | targets = ( 256 | BD60D38F25D58D6F0075CC34 /* SecureEnclaveToken */, 257 | BD60D3AA25D58D9A0075CC34 /* SecureEnclaveTokenExtension */, 258 | ); 259 | }; 260 | /* End PBXProject section */ 261 | 262 | /* Begin PBXResourcesBuildPhase section */ 263 | BD60D38E25D58D6F0075CC34 /* Resources */ = { 264 | isa = PBXResourcesBuildPhase; 265 | buildActionMask = 2147483647; 266 | files = ( 267 | BD60D39E25D58D6F0075CC34 /* Main.storyboard in Resources */, 268 | BD60D39B25D58D6F0075CC34 /* Preview Assets.xcassets in Resources */, 269 | BD60D39825D58D6F0075CC34 /* Assets.xcassets in Resources */, 270 | ); 271 | runOnlyForDeploymentPostprocessing = 0; 272 | }; 273 | BD60D3A925D58D9A0075CC34 /* Resources */ = { 274 | isa = PBXResourcesBuildPhase; 275 | buildActionMask = 2147483647; 276 | files = ( 277 | ); 278 | runOnlyForDeploymentPostprocessing = 0; 279 | }; 280 | /* End PBXResourcesBuildPhase section */ 281 | 282 | /* Begin PBXSourcesBuildPhase section */ 283 | BD60D38C25D58D6F0075CC34 /* Sources */ = { 284 | isa = PBXSourcesBuildPhase; 285 | buildActionMask = 2147483647; 286 | files = ( 287 | D98B035E28E0915200D6EB1C /* SecureEnclaveTokenCLI.swift in Sources */, 288 | BD60D39625D58D6F0075CC34 /* ContentView.swift in Sources */, 289 | BD60D39425D58D6F0075CC34 /* AppDelegate.swift in Sources */, 290 | D98B035928DF8CFE00D6EB1C /* main.swift in Sources */, 291 | BD60D3C225D58E5A0075CC34 /* SecureEnclaveTokenUtils.swift in Sources */, 292 | ); 293 | runOnlyForDeploymentPostprocessing = 0; 294 | }; 295 | BD60D3A725D58D9A0075CC34 /* Sources */ = { 296 | isa = PBXSourcesBuildPhase; 297 | buildActionMask = 2147483647; 298 | files = ( 299 | BD60D3B525D58D9A0075CC34 /* TokenSession.swift in Sources */, 300 | BD60D3B125D58D9A0075CC34 /* Token.swift in Sources */, 301 | BD60D3B325D58D9A0075CC34 /* TokenDriver.swift in Sources */, 302 | ); 303 | runOnlyForDeploymentPostprocessing = 0; 304 | }; 305 | /* End PBXSourcesBuildPhase section */ 306 | 307 | /* Begin PBXTargetDependency section */ 308 | BD60D3B925D58D9A0075CC34 /* PBXTargetDependency */ = { 309 | isa = PBXTargetDependency; 310 | target = BD60D3AA25D58D9A0075CC34 /* SecureEnclaveTokenExtension */; 311 | targetProxy = BD60D3B825D58D9A0075CC34 /* PBXContainerItemProxy */; 312 | }; 313 | /* End PBXTargetDependency section */ 314 | 315 | /* Begin PBXVariantGroup section */ 316 | BD60D39C25D58D6F0075CC34 /* Main.storyboard */ = { 317 | isa = PBXVariantGroup; 318 | children = ( 319 | BD60D39D25D58D6F0075CC34 /* Base */, 320 | ); 321 | name = Main.storyboard; 322 | sourceTree = ""; 323 | }; 324 | /* End PBXVariantGroup section */ 325 | 326 | /* Begin XCBuildConfiguration section */ 327 | BD60D3A125D58D6F0075CC34 /* Debug */ = { 328 | isa = XCBuildConfiguration; 329 | buildSettings = { 330 | ALWAYS_SEARCH_USER_PATHS = NO; 331 | CLANG_ANALYZER_NONNULL = YES; 332 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 333 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 334 | CLANG_CXX_LIBRARY = "libc++"; 335 | CLANG_ENABLE_MODULES = YES; 336 | CLANG_ENABLE_OBJC_ARC = YES; 337 | CLANG_ENABLE_OBJC_WEAK = YES; 338 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 339 | CLANG_WARN_BOOL_CONVERSION = YES; 340 | CLANG_WARN_COMMA = YES; 341 | CLANG_WARN_CONSTANT_CONVERSION = YES; 342 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 343 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 344 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 345 | CLANG_WARN_EMPTY_BODY = YES; 346 | CLANG_WARN_ENUM_CONVERSION = YES; 347 | CLANG_WARN_INFINITE_RECURSION = YES; 348 | CLANG_WARN_INT_CONVERSION = YES; 349 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 350 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 351 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 352 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 353 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; 354 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 355 | CLANG_WARN_STRICT_PROTOTYPES = YES; 356 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 357 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 358 | CLANG_WARN_UNREACHABLE_CODE = YES; 359 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 360 | COPY_PHASE_STRIP = NO; 361 | DEBUG_INFORMATION_FORMAT = dwarf; 362 | ENABLE_STRICT_OBJC_MSGSEND = YES; 363 | ENABLE_TESTABILITY = YES; 364 | GCC_C_LANGUAGE_STANDARD = gnu11; 365 | GCC_DYNAMIC_NO_PIC = NO; 366 | GCC_NO_COMMON_BLOCKS = YES; 367 | GCC_OPTIMIZATION_LEVEL = 0; 368 | GCC_PREPROCESSOR_DEFINITIONS = ( 369 | "DEBUG=1", 370 | "$(inherited)", 371 | ); 372 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 373 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 374 | GCC_WARN_UNDECLARED_SELECTOR = YES; 375 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 376 | GCC_WARN_UNUSED_FUNCTION = YES; 377 | GCC_WARN_UNUSED_VARIABLE = YES; 378 | MACOSX_DEPLOYMENT_TARGET = 11.0; 379 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; 380 | MTL_FAST_MATH = YES; 381 | ONLY_ACTIVE_ARCH = YES; 382 | SDKROOT = macosx; 383 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; 384 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 385 | }; 386 | name = Debug; 387 | }; 388 | BD60D3A225D58D6F0075CC34 /* Release */ = { 389 | isa = XCBuildConfiguration; 390 | buildSettings = { 391 | ALWAYS_SEARCH_USER_PATHS = NO; 392 | CLANG_ANALYZER_NONNULL = YES; 393 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 394 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 395 | CLANG_CXX_LIBRARY = "libc++"; 396 | CLANG_ENABLE_MODULES = YES; 397 | CLANG_ENABLE_OBJC_ARC = YES; 398 | CLANG_ENABLE_OBJC_WEAK = YES; 399 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 400 | CLANG_WARN_BOOL_CONVERSION = YES; 401 | CLANG_WARN_COMMA = YES; 402 | CLANG_WARN_CONSTANT_CONVERSION = YES; 403 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 404 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 405 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 406 | CLANG_WARN_EMPTY_BODY = YES; 407 | CLANG_WARN_ENUM_CONVERSION = YES; 408 | CLANG_WARN_INFINITE_RECURSION = YES; 409 | CLANG_WARN_INT_CONVERSION = YES; 410 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 411 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 412 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 413 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 414 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; 415 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 416 | CLANG_WARN_STRICT_PROTOTYPES = YES; 417 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 418 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 419 | CLANG_WARN_UNREACHABLE_CODE = YES; 420 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 421 | COPY_PHASE_STRIP = NO; 422 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 423 | ENABLE_NS_ASSERTIONS = NO; 424 | ENABLE_STRICT_OBJC_MSGSEND = YES; 425 | GCC_C_LANGUAGE_STANDARD = gnu11; 426 | GCC_NO_COMMON_BLOCKS = YES; 427 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 428 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 429 | GCC_WARN_UNDECLARED_SELECTOR = YES; 430 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 431 | GCC_WARN_UNUSED_FUNCTION = YES; 432 | GCC_WARN_UNUSED_VARIABLE = YES; 433 | MACOSX_DEPLOYMENT_TARGET = 11.0; 434 | MTL_ENABLE_DEBUG_INFO = NO; 435 | MTL_FAST_MATH = YES; 436 | SDKROOT = macosx; 437 | SWIFT_COMPILATION_MODE = wholemodule; 438 | SWIFT_OPTIMIZATION_LEVEL = "-O"; 439 | }; 440 | name = Release; 441 | }; 442 | BD60D3A425D58D6F0075CC34 /* Debug */ = { 443 | isa = XCBuildConfiguration; 444 | buildSettings = { 445 | ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; 446 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 447 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; 448 | CODE_SIGN_ENTITLEMENTS = SecureEnclaveToken/SecureEnclaveToken.entitlements; 449 | CODE_SIGN_IDENTITY = "Apple Development"; 450 | CODE_SIGN_STYLE = Automatic; 451 | COMBINE_HIDPI_IMAGES = YES; 452 | DEVELOPMENT_ASSET_PATHS = "\"SecureEnclaveToken/Preview Content\""; 453 | DEVELOPMENT_TEAM = W8LYJ3542D; 454 | ENABLE_HARDENED_RUNTIME = YES; 455 | ENABLE_PREVIEWS = YES; 456 | FRAMEWORK_SEARCH_PATHS = ( 457 | "$(inherited)", 458 | "$(PROJECT_DIR)", 459 | ); 460 | INFOPLIST_FILE = SecureEnclaveToken/Info.plist; 461 | INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; 462 | LD_RUNPATH_SEARCH_PATHS = ( 463 | "$(inherited)", 464 | "@executable_path/../Frameworks", 465 | ); 466 | MARKETING_VERSION = 2.0; 467 | PRODUCT_BUNDLE_IDENTIFIER = com.mwielgoszewski.SecureEnclaveToken; 468 | PRODUCT_NAME = "$(TARGET_NAME)"; 469 | SWIFT_VERSION = 5.0; 470 | }; 471 | name = Debug; 472 | }; 473 | BD60D3A525D58D6F0075CC34 /* Release */ = { 474 | isa = XCBuildConfiguration; 475 | buildSettings = { 476 | ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; 477 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 478 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; 479 | CODE_SIGN_ENTITLEMENTS = SecureEnclaveToken/SecureEnclaveToken.entitlements; 480 | CODE_SIGN_IDENTITY = "Apple Development"; 481 | CODE_SIGN_STYLE = Automatic; 482 | COMBINE_HIDPI_IMAGES = YES; 483 | DEVELOPMENT_ASSET_PATHS = "\"SecureEnclaveToken/Preview Content\""; 484 | DEVELOPMENT_TEAM = W8LYJ3542D; 485 | ENABLE_HARDENED_RUNTIME = YES; 486 | ENABLE_PREVIEWS = YES; 487 | FRAMEWORK_SEARCH_PATHS = ( 488 | "$(inherited)", 489 | "$(PROJECT_DIR)", 490 | ); 491 | INFOPLIST_FILE = SecureEnclaveToken/Info.plist; 492 | INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; 493 | LD_RUNPATH_SEARCH_PATHS = ( 494 | "$(inherited)", 495 | "@executable_path/../Frameworks", 496 | ); 497 | MARKETING_VERSION = 2.0; 498 | PRODUCT_BUNDLE_IDENTIFIER = com.mwielgoszewski.SecureEnclaveToken; 499 | PRODUCT_NAME = "$(TARGET_NAME)"; 500 | SWIFT_VERSION = 5.0; 501 | }; 502 | name = Release; 503 | }; 504 | BD60D3BC25D58D9A0075CC34 /* Debug */ = { 505 | isa = XCBuildConfiguration; 506 | buildSettings = { 507 | CODE_SIGN_ENTITLEMENTS = SecureEnclaveTokenExtension/SecureEnclaveTokenExtension.entitlements; 508 | CODE_SIGN_IDENTITY = "Apple Development"; 509 | CODE_SIGN_STYLE = Automatic; 510 | COMBINE_HIDPI_IMAGES = YES; 511 | DEVELOPMENT_TEAM = W8LYJ3542D; 512 | ENABLE_HARDENED_RUNTIME = YES; 513 | INFOPLIST_FILE = SecureEnclaveTokenExtension/Info.plist; 514 | LD_RUNPATH_SEARCH_PATHS = ( 515 | "$(inherited)", 516 | "@executable_path/../Frameworks", 517 | "@executable_path/../../../../Frameworks", 518 | ); 519 | MARKETING_VERSION = 1.0.2; 520 | PRODUCT_BUNDLE_IDENTIFIER = com.mwielgoszewski.SecureEnclaveToken.SecureEnclaveTokenExtension; 521 | PRODUCT_NAME = "$(TARGET_NAME)"; 522 | SKIP_INSTALL = YES; 523 | SWIFT_VERSION = 5.0; 524 | }; 525 | name = Debug; 526 | }; 527 | BD60D3BD25D58D9A0075CC34 /* Release */ = { 528 | isa = XCBuildConfiguration; 529 | buildSettings = { 530 | CODE_SIGN_ENTITLEMENTS = SecureEnclaveTokenExtension/SecureEnclaveTokenExtension.entitlements; 531 | CODE_SIGN_IDENTITY = "Apple Development"; 532 | CODE_SIGN_STYLE = Automatic; 533 | COMBINE_HIDPI_IMAGES = YES; 534 | DEVELOPMENT_TEAM = W8LYJ3542D; 535 | ENABLE_HARDENED_RUNTIME = YES; 536 | INFOPLIST_FILE = SecureEnclaveTokenExtension/Info.plist; 537 | LD_RUNPATH_SEARCH_PATHS = ( 538 | "$(inherited)", 539 | "@executable_path/../Frameworks", 540 | "@executable_path/../../../../Frameworks", 541 | ); 542 | MARKETING_VERSION = 1.0.2; 543 | PRODUCT_BUNDLE_IDENTIFIER = com.mwielgoszewski.SecureEnclaveToken.SecureEnclaveTokenExtension; 544 | PRODUCT_NAME = "$(TARGET_NAME)"; 545 | SKIP_INSTALL = YES; 546 | SWIFT_VERSION = 5.0; 547 | }; 548 | name = Release; 549 | }; 550 | /* End XCBuildConfiguration section */ 551 | 552 | /* Begin XCConfigurationList section */ 553 | BD60D38B25D58D6F0075CC34 /* Build configuration list for PBXProject "SecureEnclaveToken" */ = { 554 | isa = XCConfigurationList; 555 | buildConfigurations = ( 556 | BD60D3A125D58D6F0075CC34 /* Debug */, 557 | BD60D3A225D58D6F0075CC34 /* Release */, 558 | ); 559 | defaultConfigurationIsVisible = 0; 560 | defaultConfigurationName = Release; 561 | }; 562 | BD60D3A325D58D6F0075CC34 /* Build configuration list for PBXNativeTarget "SecureEnclaveToken" */ = { 563 | isa = XCConfigurationList; 564 | buildConfigurations = ( 565 | BD60D3A425D58D6F0075CC34 /* Debug */, 566 | BD60D3A525D58D6F0075CC34 /* Release */, 567 | ); 568 | defaultConfigurationIsVisible = 0; 569 | defaultConfigurationName = Release; 570 | }; 571 | BD60D3BB25D58D9A0075CC34 /* Build configuration list for PBXNativeTarget "SecureEnclaveTokenExtension" */ = { 572 | isa = XCConfigurationList; 573 | buildConfigurations = ( 574 | BD60D3BC25D58D9A0075CC34 /* Debug */, 575 | BD60D3BD25D58D9A0075CC34 /* Release */, 576 | ); 577 | defaultConfigurationIsVisible = 0; 578 | defaultConfigurationName = Release; 579 | }; 580 | /* End XCConfigurationList section */ 581 | 582 | /* Begin XCRemoteSwiftPackageReference section */ 583 | BDE0445C25E0228C00C984E3 /* XCRemoteSwiftPackageReference "CertificateSigningRequest" */ = { 584 | isa = XCRemoteSwiftPackageReference; 585 | repositoryURL = "https://github.com/mwielgoszewski/CertificateSigningRequest"; 586 | requirement = { 587 | branch = "feature/extension-requests"; 588 | kind = branch; 589 | }; 590 | }; 591 | D98B035A28DF955900D6EB1C /* XCRemoteSwiftPackageReference "swift-argument-parser" */ = { 592 | isa = XCRemoteSwiftPackageReference; 593 | repositoryURL = "https://github.com/apple/swift-argument-parser.git"; 594 | requirement = { 595 | kind = upToNextMajorVersion; 596 | minimumVersion = 1.0.0; 597 | }; 598 | }; 599 | /* End XCRemoteSwiftPackageReference section */ 600 | 601 | /* Begin XCSwiftPackageProductDependency section */ 602 | BDE0445D25E0228C00C984E3 /* CertificateSigningRequest */ = { 603 | isa = XCSwiftPackageProductDependency; 604 | package = BDE0445C25E0228C00C984E3 /* XCRemoteSwiftPackageReference "CertificateSigningRequest" */; 605 | productName = CertificateSigningRequest; 606 | }; 607 | D98B035B28DF955900D6EB1C /* ArgumentParser */ = { 608 | isa = XCSwiftPackageProductDependency; 609 | package = D98B035A28DF955900D6EB1C /* XCRemoteSwiftPackageReference "swift-argument-parser" */; 610 | productName = ArgumentParser; 611 | }; 612 | /* End XCSwiftPackageProductDependency section */ 613 | }; 614 | rootObject = BD60D38825D58D6F0075CC34 /* Project object */; 615 | } 616 | -------------------------------------------------------------------------------- /SecureEnclaveToken.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SecureEnclaveToken.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /SecureEnclaveToken.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "pins" : [ 3 | { 4 | "identity" : "certificatesigningrequest", 5 | "kind" : "remoteSourceControl", 6 | "location" : "https://github.com/mwielgoszewski/CertificateSigningRequest", 7 | "state" : { 8 | "branch" : "feature/extension-requests", 9 | "revision" : "f2cf3284bf2763772ea0e81f107df030ac7b9e23" 10 | } 11 | }, 12 | { 13 | "identity" : "swift-argument-parser", 14 | "kind" : "remoteSourceControl", 15 | "location" : "https://github.com/apple/swift-argument-parser.git", 16 | "state" : { 17 | "revision" : "9f39744e025c7d377987f30b03770805dcb0bcd1", 18 | "version" : "1.1.4" 19 | } 20 | } 21 | ], 22 | "version" : 2 23 | } 24 | -------------------------------------------------------------------------------- /SecureEnclaveToken.xcodeproj/xcshareddata/xcschemes/SecureEnclaveToken.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 43 | 45 | 51 | 52 | 53 | 54 | 60 | 62 | 68 | 69 | 70 | 71 | 73 | 74 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /SecureEnclaveToken.xcodeproj/xcshareddata/xcschemes/SecureEnclaveTokenExtension.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 6 | 9 | 10 | 16 | 22 | 23 | 24 | 30 | 36 | 37 | 38 | 39 | 40 | 45 | 46 | 47 | 48 | 60 | 62 | 68 | 69 | 70 | 71 | 78 | 80 | 86 | 87 | 88 | 89 | 91 | 92 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /SecureEnclaveToken/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // SecureEnclaveToken 4 | // 5 | // Created by Marcin Wielgoszewski on 2/11/21. 6 | // 7 | 8 | import Cocoa 9 | import SwiftUI 10 | import ArgumentParser 11 | 12 | class AppDelegate: NSObject, NSApplicationDelegate { 13 | 14 | var window: NSWindow! 15 | 16 | func applicationDidFinishLaunching(_ aNotification: Notification) { 17 | // arg.0 is the current executable 18 | let args = Array(CommandLine.arguments.dropFirst()) 19 | 20 | // execute this as a cli app, then exit immediately 21 | if args.first == "cli" { 22 | SecureEnclaveTokenCLI.main(Array(args.dropFirst())) 23 | exit(0) 24 | } 25 | 26 | // Create the SwiftUI view that provides the window contents. 27 | let contentView = ContentView() 28 | 29 | // Create the window and set the content view. 30 | window = NSWindow( 31 | contentRect: NSRect(x: 0, y: 0, width: 480, height: 640), 32 | styleMask: [.titled, .closable, .miniaturizable, .fullSizeContentView], 33 | backing: .buffered, defer: false) 34 | window.isReleasedWhenClosed = false 35 | window.center() 36 | window.setFrameAutosaveName("Main Window") 37 | window.contentView = NSHostingView(rootView: contentView) 38 | window.makeKeyAndOrderFront(nil) 39 | } 40 | 41 | func applicationWillTerminate(_ aNotification: Notification) { 42 | // Insert code here to tear down your application 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /SecureEnclaveToken/Assets.xcassets/AccentColor.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "colors" : [ 3 | { 4 | "idiom" : "universal" 5 | } 6 | ], 7 | "info" : { 8 | "author" : "xcode", 9 | "version" : 1 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /SecureEnclaveToken/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "mac", 5 | "scale" : "1x", 6 | "size" : "16x16" 7 | }, 8 | { 9 | "idiom" : "mac", 10 | "scale" : "2x", 11 | "size" : "16x16" 12 | }, 13 | { 14 | "idiom" : "mac", 15 | "scale" : "1x", 16 | "size" : "32x32" 17 | }, 18 | { 19 | "idiom" : "mac", 20 | "scale" : "2x", 21 | "size" : "32x32" 22 | }, 23 | { 24 | "idiom" : "mac", 25 | "scale" : "1x", 26 | "size" : "128x128" 27 | }, 28 | { 29 | "idiom" : "mac", 30 | "scale" : "2x", 31 | "size" : "128x128" 32 | }, 33 | { 34 | "idiom" : "mac", 35 | "scale" : "1x", 36 | "size" : "256x256" 37 | }, 38 | { 39 | "idiom" : "mac", 40 | "scale" : "2x", 41 | "size" : "256x256" 42 | }, 43 | { 44 | "idiom" : "mac", 45 | "scale" : "1x", 46 | "size" : "512x512" 47 | }, 48 | { 49 | "idiom" : "mac", 50 | "scale" : "2x", 51 | "size" : "512x512" 52 | } 53 | ], 54 | "info" : { 55 | "author" : "xcode", 56 | "version" : 1 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /SecureEnclaveToken/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /SecureEnclaveToken/ContentView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContentView.swift 3 | // SecureEnclaveToken 4 | // 5 | // Created by Marcin Wielgoszewski on 2/11/21. 6 | // 7 | 8 | import SwiftUI 9 | import CryptoKit 10 | import CryptoTokenKit 11 | import CertificateSigningRequest 12 | 13 | struct ContentView: View { 14 | @State private var keysLoaded = 0 15 | @State private var certificateLabel = "" 16 | @State private var keyLabel = "" 17 | @State private var generateKeyDescription = "" 18 | @State private var showDeleteConfirmation = false 19 | @State private var commonName = "" 20 | @State private var emailAddress = "" 21 | @State private var organizationUnitName = "" 22 | @State private var organizationName = "" 23 | @State private var localityName = "" 24 | @State private var stateOrProvinceName = "" 25 | @State private var countryName = "" 26 | @State private var keyAccessibilityFlags = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 27 | @State private var keyAccessControlFlags = 0 28 | 29 | @State private var genTag = "" 30 | @State private var csrTag = "" 31 | @State private var deleteTag = "" 32 | @State private var exportTag = "" 33 | 34 | let queryTokenTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() 35 | 36 | var tokenConfig: TKToken.Configuration? { 37 | loadTokenConfig() 38 | } 39 | 40 | var keyTags: [String] { 41 | var item: AnyObject? 42 | 43 | let query: [String: Any] = [kSecClass as String: kSecClassKey, 44 | kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, 45 | kSecReturnRef as String: true, 46 | kSecReturnAttributes as String: true, 47 | kSecMatchLimit as String: kSecMatchLimitAll, 48 | ] 49 | 50 | let status = SecItemCopyMatching(query as CFDictionary, &item) 51 | guard status == errSecSuccess else { 52 | return [] 53 | } 54 | 55 | var items: [String] = [] 56 | 57 | for attr in item as! [NSDictionary] { 58 | let atag = attr[kSecAttrApplicationTag as String] as? Data 59 | items.append(String(data: atag!, encoding: .utf8)!) 60 | } 61 | return items 62 | } 63 | 64 | var body: some View { 65 | VStack(alignment: .leading, spacing: 10) { 66 | HStack(alignment: .top) { 67 | VStack { 68 | Text("SecureEnclaveToken; see cli help for more options") 69 | } 70 | } 71 | HStack(alignment: .top) { 72 | VStack(alignment: .leading) { 73 | Text("\(keysLoaded) token keychain items loaded") 74 | Text(certificateLabel) 75 | Text(keyLabel) 76 | }.onReceive(queryTokenTimer, perform: { _ in 77 | keysLoaded = tokenConfig?.keychainItems.count ?? 0 78 | }) 79 | } 80 | 81 | HStack(alignment: .top) { 82 | VStack(alignment: .leading) { 83 | Button(action: { 84 | let tag = genTag.data(using: .utf8)! 85 | var secKey = loadSecureEnclaveKey(tag: tag) 86 | if secKey != nil { 87 | generateKeyDescription = "Found key: \(secKey.debugDescription)" 88 | } else { 89 | secKey = generateKeyInEnclaveFromUi(tag: tag, accessibility: keyAccessibilityFlags, accessControlFlags: keyAccessControlFlags) 90 | generateKeyDescription = "Generated key: \(secKey.debugDescription)" 91 | } 92 | }) { 93 | Text("Generate Key") 94 | } 95 | }.padding(15) 96 | 97 | VStack(alignment: .leading) { 98 | TextField("Tag", text: $genTag) 99 | 100 | Picker(selection: $keyAccessibilityFlags, label: Text("Access:")) { 101 | Text("After first unlock").tag(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) 102 | Text("When unlocked").tag(kSecAttrAccessibleWhenUnlockedThisDeviceOnly) 103 | } 104 | 105 | Picker(selection: $keyAccessControlFlags, label: Text("Require:")) { 106 | Text("Biometric").tag(3) 107 | Text("Passcode").tag(2) 108 | Text("User Presence (Biometric OR Passcode)").tag(1) 109 | Text("No additional security").tag(0) 110 | } 111 | 112 | Text(generateKeyDescription) 113 | } 114 | } 115 | 116 | HStack { 117 | VStack(alignment: .leading) { 118 | Button(action: { 119 | self.showDeleteConfirmation = true 120 | }) { 121 | Text("Delete Key") 122 | } 123 | .alert(isPresented: $showDeleteConfirmation) { 124 | Alert(title: Text("Are you sure you want to delete this key?"), message: Text("Deleted keys cannot be recovered."), 125 | primaryButton: .cancel(), 126 | secondaryButton: .destructive(Text("Delete Key"), action: { 127 | let tag = deleteTag.data(using: .utf8)! 128 | if deleteSecureEnclaveKey(tag: tag) { 129 | print("Deleted key from enclave, unloading token configuration") 130 | unloadTokenConfig() 131 | } 132 | }) 133 | ) 134 | } 135 | }.padding(20) 136 | 137 | VStack { 138 | Picker(selection: $deleteTag, label: Text("")) { 139 | ForEach(0 ..< keyTags.count, id: \.self) { index in 140 | Text(self.keyTags[index]).tag(self.keyTags[index]) 141 | } 142 | } 143 | } 144 | } 145 | 146 | HStack { 147 | VStack(alignment: .leading) { 148 | Button(action: { 149 | let tag = exportTag.data(using: .utf8)! 150 | let secKey = loadSecureEnclaveKey(tag: tag) 151 | let publicKey = SecKeyCopyPublicKey(secKey!) 152 | 153 | var error: Unmanaged? 154 | let ixy = SecKeyCopyExternalRepresentation(publicKey!, &error) 155 | let bytes: Data = ixy! as Data 156 | 157 | // seq / seq / id-ecPublicKey / prime256v1 asn.1 158 | var der = Data(base64Encoded: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgA=")! 159 | // EC keys should be in ANSI X9.63, uncompressed byte string 04 || X || Y 160 | der.append(bytes) 161 | print(der.base64EncodedString()) 162 | 163 | let panel = NSSavePanel() 164 | // default filename to .pub 165 | panel.nameFieldStringValue = String(decoding: tag, as: UTF8.self) + ".pub" 166 | if panel.runModal() == .OK { 167 | let exportFilename = panel.url!.absoluteURL 168 | do { 169 | try der.write(to: exportFilename) 170 | } catch { 171 | print("Failed to write to \(exportFilename)") 172 | } 173 | } 174 | }) { 175 | Text("Export Public Key") 176 | } 177 | } 178 | 179 | VStack { 180 | Picker(selection: $exportTag, label: Text("")) { 181 | ForEach(0 ..< keyTags.count, id: \.self) { index in 182 | Text(self.keyTags[index]).tag(self.keyTags[index]) 183 | } 184 | } 185 | } 186 | } 187 | 188 | HStack(alignment: .top) { 189 | VStack { 190 | Button(action: { 191 | let tag = csrTag.data(using: .utf8)! 192 | let secKey = loadSecureEnclaveKey(tag: tag) 193 | if secKey != nil { 194 | let publicKey = SecKeyCopyPublicKey(secKey!) 195 | 196 | var error: Unmanaged? 197 | let ixy = SecKeyCopyExternalRepresentation(publicKey!, &error) 198 | let publicKeyBits: Data = ixy! as Data 199 | 200 | let savePanel = NSSavePanel() 201 | // default filename to .req 202 | savePanel.nameFieldStringValue = String(decoding: tag, as: UTF8.self) + ".req" 203 | if savePanel.runModal() == .OK { 204 | let exportFilename = savePanel.url! 205 | do { 206 | let keyAlgorithm = KeyAlgorithm.ec(signatureType: .sha256) 207 | let csr = CertificateSigningRequest.init( 208 | commonName: commonName, 209 | organizationName: organizationName, 210 | organizationUnitName: organizationUnitName.split(separator: ";").map(String.init), 211 | countryName: countryName, 212 | stateOrProvinceName: stateOrProvinceName, 213 | localityName: localityName, 214 | emailAddress: emailAddress.split(separator: ";").map(String.init), 215 | description: nil, 216 | keyAlgorithm: keyAlgorithm) 217 | 218 | let pem = csr.buildCSRAndReturnString(publicKeyBits, privateKey: secKey!, publicKey: publicKey) 219 | try pem?.data(using: .ascii)!.write(to: exportFilename) 220 | } catch { 221 | print("Failed to write to \(exportFilename)") 222 | } 223 | } 224 | } 225 | 226 | }) { 227 | Text("Generate CSR") 228 | } 229 | }.padding(15) 230 | 231 | VStack(alignment: .leading) { 232 | Picker(selection: $csrTag, label: Text("For key:")) { 233 | ForEach(0 ..< keyTags.count, id: \.self) { index in 234 | Text(self.keyTags[index]).tag(self.keyTags[index]) 235 | } 236 | } 237 | Text("Enter fields below:") 238 | TextField("Common Name", text: $commonName) 239 | TextField("Email Address (delimit using semicolon)", text: $emailAddress) 240 | TextField("Organizational Unit (delimit using semicolon)", text: $organizationUnitName) 241 | TextField("Organization", text: $organizationName) 242 | TextField("Locality", text: $localityName) 243 | TextField("State or Province", text: $stateOrProvinceName) 244 | TextField("Country", text: $countryName) 245 | } 246 | 247 | } 248 | } 249 | .padding() 250 | 251 | } 252 | } 253 | 254 | struct ContentView_Previews: PreviewProvider { 255 | static var previews: some View { 256 | ContentView() 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /SecureEnclaveToken/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | $(PRODUCT_BUNDLE_PACKAGE_TYPE) 19 | CFBundleShortVersionString 20 | $(MARKETING_VERSION) 21 | CFBundleVersion 22 | 1 23 | LSApplicationCategoryType 24 | public.app-category.utilities 25 | LSMinimumSystemVersion 26 | $(MACOSX_DEPLOYMENT_TARGET) 27 | NSHumanReadableCopyright 28 | Marcin Wielgoszewski 29 | NSMainStoryboardFile 30 | Main 31 | NSPrincipalClass 32 | NSApplication 33 | 34 | 35 | -------------------------------------------------------------------------------- /SecureEnclaveToken/Preview Content/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | Default 529 | 530 | 531 | 532 | 533 | 534 | 535 | Left to Right 536 | 537 | 538 | 539 | 540 | 541 | 542 | Right to Left 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | Default 554 | 555 | 556 | 557 | 558 | 559 | 560 | Left to Right 561 | 562 | 563 | 564 | 565 | 566 | 567 | Right to Left 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | -------------------------------------------------------------------------------- /SecureEnclaveToken/Preview Content/Preview Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /SecureEnclaveToken/SecureEnclaveToken.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.files.downloads.read-write 8 | 9 | com.apple.security.files.user-selected.read-write 10 | 11 | keychain-access-groups 12 | 13 | $(AppIdentifierPrefix)com.mwielgoszewski.SecureEnclaveToken 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /SecureEnclaveToken/SecureEnclaveTokenCLI.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SecureEnclaveTokenCLI.swift 3 | // SecureEnclaveToken 4 | // 5 | // Created by Marcin Wielgoszewski on 9/25/22. 6 | // 7 | 8 | import Foundation 9 | import ArgumentParser 10 | import CertificateSigningRequest 11 | import CryptoTokenKit 12 | import CryptoKit 13 | 14 | struct TokenConfiguration: Codable { 15 | var keys: [Data] 16 | } 17 | 18 | struct SecureEnclaveTokenCLI: ParsableCommand { 19 | static var configuration = CommandConfiguration( 20 | commandName: "SecureEnclaveToken cli", 21 | abstract: "A utility for managing secure enclave keys and tokens.", 22 | subcommands: [New.self, Destroy.self, Req.self, Pub.self, Keys.self, Token.self] 23 | ) 24 | } 25 | 26 | struct Options: ParsableArguments { 27 | @Argument(help: "Private tag of the key.", transform: ({return $0.data(using: .utf8)!})) var key: Data 28 | } 29 | 30 | extension SecureEnclaveTokenCLI { 31 | struct New: ParsableCommand { 32 | static var configuration = CommandConfiguration( 33 | abstract: "Generate a new secure enclave backed key." 34 | ) 35 | 36 | enum Require: String, ExpressibleByArgument { 37 | case none, userPresence, biometryAny, biometryCurrentSet, devicePasscode 38 | } 39 | 40 | enum Availability: String, ExpressibleByArgument { 41 | case whenUnlocked, afterFirstUnlock 42 | } 43 | 44 | @OptionGroup var options: Options 45 | @Option(help: "Possible values: none, userPresence, biometryAny, biometryCurrentSet, or devicePasscode") var require: Require = .none 46 | @Option(help: "Possible values: whenUnlocked or afterFirstUnlock") var available: Availability = .afterFirstUnlock 47 | 48 | mutating func run() throws { 49 | let keyExists = loadSecureEnclaveKey(tag: options.key) 50 | 51 | guard keyExists == nil else { 52 | print("Key \(String(data: options.key, encoding: .utf8) ?? "") already exists, destroy it before generating a new one.") 53 | throw ExitCode.failure 54 | } 55 | 56 | var flags: SecAccessControlCreateFlags 57 | 58 | switch require { 59 | case .userPresence: 60 | flags = [SecAccessControlCreateFlags.privateKeyUsage, SecAccessControlCreateFlags.userPresence] 61 | case .devicePasscode: 62 | flags = [SecAccessControlCreateFlags.privateKeyUsage, SecAccessControlCreateFlags.devicePasscode] 63 | case .biometryAny: 64 | flags = [SecAccessControlCreateFlags.privateKeyUsage, SecAccessControlCreateFlags.biometryAny] 65 | case .biometryCurrentSet: 66 | flags = [SecAccessControlCreateFlags.privateKeyUsage, SecAccessControlCreateFlags.biometryCurrentSet] 67 | case .none: 68 | flags = [SecAccessControlCreateFlags.privateKeyUsage] 69 | } 70 | 71 | var accessibility: CFString 72 | switch available { 73 | case .whenUnlocked: 74 | accessibility = kSecAttrAccessibleWhenUnlockedThisDeviceOnly 75 | case .afterFirstUnlock: 76 | accessibility = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 77 | } 78 | 79 | _ = generateKeyInEnclave(tag: options.key, accessibility: accessibility, flags: flags) 80 | } 81 | } 82 | 83 | struct Destroy: ParsableCommand { 84 | static var configuration = CommandConfiguration( 85 | abstract: "Destroy a key in the secure enclave." 86 | ) 87 | 88 | @OptionGroup var options: Options 89 | 90 | mutating func run() throws { 91 | guard let tokenConfig = loadTokenConfig() else { 92 | print("Could not load token configuration.") 93 | throw ExitCode.failure 94 | } 95 | guard loadSecureEnclaveKey(tag: options.key) != nil else { 96 | print("Key \(String(data: options.key, encoding: .utf8) ?? "") not found") 97 | throw ExitCode.failure 98 | } 99 | guard deleteSecureEnclaveKey(tag: options.key) else { 100 | print("Failed to delete key.") 101 | throw ExitCode.failure 102 | } 103 | var config = try? JSONDecoder().decode(TokenConfiguration.self, from: tokenConfig.configurationData ?? Data()) 104 | config?.keys.removeAll(where: {$0 == options.key}) 105 | tokenConfig.configurationData = try? JSONEncoder().encode(config) 106 | print("Successfully deleted key.") 107 | } 108 | } 109 | 110 | struct Req: ParsableCommand { 111 | static var configuration = CommandConfiguration( 112 | abstract: "Generate a certificate signing request for a given key." 113 | ) 114 | 115 | @OptionGroup var options: Options 116 | @Option(name: [.customLong("cn", withSingleDash: true)], help: "Common Name (eg, fully qualified host name)") var commonName: String? 117 | @Option(name: [.customShort("o")], help: "Organization Name (eg, company)") var organizationName: String? 118 | @Option(name: [.customLong("ou", withSingleDash: true)], help: "Organizational Unit Name (eg, section)") var organizationUnitName: String? 119 | @Option(name: [.customShort("c")], help: "Country Name (2 letter code)") var countryName: String? 120 | @Option(name: [.customLong("st", withSingleDash: true)], help: "State or Province Name (full name)") var stateOrProvinceName: String? 121 | @Option(name: [.customShort("l")], help: "Locality Name (eg, city)") var localityName: String? 122 | @Option(name: [.customLong("email", withSingleDash: true)], help: "Email Address") var emailAddress: String? 123 | @Option(name: [.customShort("d")], help: "Description") var description: String? 124 | @Flag(name: [.customLong("include-serial", withSingleDash: true)], help: "Include device serial number (default: false)") var includeSerialNumber = false 125 | 126 | mutating func run() throws { 127 | guard let secKey = loadSecureEnclaveKey(tag: options.key) else { 128 | print("Key \(String(data: options.key, encoding: .utf8) ?? "") not found") 129 | throw ExitCode.failure 130 | } 131 | 132 | let publicKey = SecKeyCopyPublicKey(secKey) 133 | 134 | var error: Unmanaged? 135 | let ixy = SecKeyCopyExternalRepresentation(publicKey!, &error) 136 | let publicKeyBits: Data = ixy! as Data 137 | 138 | let keyAlgorithm = KeyAlgorithm.ec(signatureType: .sha256) 139 | let csr = CertificateSigningRequest.init(commonName: commonName, 140 | organizationName: organizationName, 141 | organizationUnitName: organizationUnitName?.split(separator: ";", omittingEmptySubsequences: true).map(String.init), 142 | countryName: countryName, 143 | stateOrProvinceName: stateOrProvinceName, 144 | localityName: localityName, 145 | serialNumber: includeSerialNumber ? serialNumber : nil, 146 | emailAddress: emailAddress?.split(separator: ";", omittingEmptySubsequences: true).map(String.init), 147 | description: description, 148 | keyAlgorithm: keyAlgorithm) 149 | 150 | csr.addKeyUsage([KeyUsage.digitalSignature, KeyUsage.keyAgreement]) 151 | csr.addExtendedKeyUsage(ExtendedKeyUsage.clientAuth) 152 | 153 | if let emailAddress = emailAddress { 154 | for email in emailAddress.split(separator: ";", omittingEmptySubsequences: true).map(String.init) { 155 | csr.addSubjectAlternativeName(SubjectAlternativeName.rfc822Name(String(email))) 156 | } 157 | } 158 | 159 | guard let pem = csr.buildCSRAndReturnString(publicKeyBits, privateKey: secKey, publicKey: publicKey) else { 160 | print("Could not generate certificate signing request") 161 | throw ExitCode.failure 162 | } 163 | print(pem) 164 | } 165 | } 166 | 167 | struct Pub: ParsableCommand { 168 | static var configuration = CommandConfiguration( 169 | abstract: "Get the public key for a secure enclave backed key." 170 | ) 171 | 172 | @OptionGroup var options: Options 173 | 174 | mutating func run() throws { 175 | guard let secKey = loadSecureEnclaveKey(tag: options.key) else { 176 | print("Key \(String(data: options.key, encoding: .utf8) ?? "") not found") 177 | throw ExitCode.failure 178 | } 179 | 180 | let publicKey = SecKeyCopyPublicKey(secKey) 181 | 182 | var error: Unmanaged? 183 | let ixy = SecKeyCopyExternalRepresentation(publicKey!, &error) 184 | let bytes: Data = ixy! as Data 185 | print(bytes.base64EncodedString()) 186 | } 187 | } 188 | 189 | struct Keys: ParsableCommand { 190 | static var configuration = CommandConfiguration( 191 | abstract: "List known private keys stored in the secure enclave." 192 | ) 193 | 194 | mutating func run() throws { 195 | var item: AnyObject? 196 | 197 | let query: [String: Any] = [kSecClass as String: kSecClassKey, 198 | kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, 199 | kSecReturnRef as String: true, 200 | kSecReturnAttributes as String: true, 201 | kSecMatchLimit as String: kSecMatchLimitAll, 202 | ] 203 | 204 | let status = SecItemCopyMatching(query as CFDictionary, &item) 205 | guard status == errSecSuccess else { 206 | print("Error querying secure enclave, \(status)") 207 | throw ExitCode.failure 208 | } 209 | 210 | // https://opensource.apple.com/source/Security/Security-59754.80.3/OSX/sec/Security/SecItemConstants.c.auto.html 211 | 212 | print("Public Key Hash Created Tag") 213 | for attr in item as! [NSDictionary] { 214 | let atag = attr[kSecAttrApplicationTag as String] as? Data 215 | let cdat = attr[kSecAttrCreationDate as String] as? Date 216 | let klbl = attr[kSecAttrApplicationLabel as String] as? Data 217 | print(String(format: "%@ %@ %@", klbl!.hexEncodedString(), cdat!.description, String(data: atag!, encoding: .utf8)!)) 218 | } 219 | } 220 | } 221 | 222 | struct Token: ParsableCommand { 223 | static var configuration = CommandConfiguration( 224 | abstract: "Manage secure enclave token configuration.", 225 | subcommands: [Info.self, List.self, Import.self, Remove.self, Clear.self], 226 | defaultSubcommand: Info.self 227 | ) 228 | } 229 | 230 | } 231 | 232 | extension SecureEnclaveTokenCLI.Token { 233 | struct Info: ParsableCommand { 234 | static var configuration = CommandConfiguration( 235 | abstract: "Display information about this token configuration." 236 | ) 237 | 238 | mutating func run() throws { 239 | guard let tokenConfig = loadTokenConfig() else { 240 | print("Could not load token configuration.") 241 | throw ExitCode.failure 242 | } 243 | 244 | print("Token instance ID: \(tokenConfig.instanceID)") 245 | print("\(tokenConfig.keychainItems.count) items loaded.") 246 | } 247 | } 248 | 249 | struct List: ParsableCommand { 250 | static var configuration = CommandConfiguration( 251 | abstract: "List keys and certificates in the token configuration." 252 | ) 253 | 254 | mutating func run() throws { 255 | guard let tokenConfig = loadTokenConfig() else { 256 | print("Could not load token configuration.") 257 | throw ExitCode.failure 258 | } 259 | 260 | let items = Dictionary(grouping: tokenConfig.keychainItems, by: { 261 | (element: TKTokenKeychainItem) in return element.objectID as! Data }) 262 | 263 | for objectID in items.keys { 264 | let certificate = try? tokenConfig.certificate(for: objectID) 265 | let key = try? tokenConfig.key(for: objectID) 266 | var usage: [String] = [] 267 | if let key = key { 268 | if key.canSign { 269 | usage.append("sign") 270 | } 271 | if key.canDecrypt { 272 | usage.append("decrypt") 273 | } 274 | if key.canPerformKeyExchange { 275 | usage.append("derive") 276 | } 277 | 278 | var keyType: String 279 | switch key.keyType as CFString { 280 | case kSecAttrKeyTypeRSA: 281 | keyType = "RSA" 282 | case kSecAttrKeyTypeECSECPrimeRandom: 283 | keyType = "ECC" 284 | default: 285 | keyType = "ECC" 286 | } 287 | 288 | print(""" 289 | Private Key Object; \(keyType) 290 | label: \(key.label ?? "") 291 | ID: \(String(data: objectID, encoding: .utf8) ?? "") 292 | Usage: \(usage.joined(separator: ", ")) 293 | Public Key Object; \(keyType) \(key.keySizeInBits) bits 294 | label: \(key.label ?? "") 295 | ID: \(String(data: objectID, encoding: .utf8) ?? "") 296 | keyHash: \(key.publicKeyHash?.map { String(format: "%02hhx", $0) }.joined() ?? "") 297 | keyData: \(key.publicKeyData?.base64EncodedString() ?? "") 298 | """) 299 | } 300 | 301 | if let certificate = certificate { 302 | let cert = SecCertificateCreateWithData(nil, certificate.data as CFData)! 303 | let subject = SecCertificateCopySubjectSummary(cert) as? String 304 | print(""" 305 | Certificate Object; type = X.509 cert 306 | label: \(certificate.label ?? "") 307 | subject: \(subject ?? "") 308 | ID: \(String(data: objectID, encoding: .utf8) ?? "") 309 | """) 310 | } 311 | } 312 | 313 | } 314 | } 315 | 316 | struct Import: ParsableCommand { 317 | static var configuration = CommandConfiguration( 318 | abstract: "Map a certificate to a key in the token configuration." 319 | ) 320 | 321 | @OptionGroup var options: Options 322 | @Argument(help: "The DER-encoded certificate", transform:({return URL(fileURLWithPath: $0)})) var cert: URL 323 | 324 | mutating func run() throws { 325 | guard let tokenConfig = loadTokenConfig() else { 326 | print("Could not load token configuration.") 327 | throw ExitCode.failure 328 | } 329 | 330 | do { 331 | try tokenConfig.certificate(for: options.key) 332 | print("A token is already loaded for this key, remove it before importing a new certificate.") 333 | throw ExitCode.failure 334 | } catch is TKError { 335 | // carry on 336 | } 337 | 338 | var derBytes: Data 339 | do { 340 | derBytes = try Data(contentsOf: cert) 341 | } catch { 342 | print("Error reading file, exiting.") 343 | throw ExitCode.failure 344 | } 345 | 346 | guard let certificate = SecCertificateCreateWithData(nil, derBytes as CFData) else { 347 | print("Error parsing certificate, exiting.") 348 | throw ExitCode.failure 349 | } 350 | 351 | do { 352 | try addCertificateToToken(certificate: certificate, tag: options.key, tokenConfig: tokenConfig) 353 | print("Successfully loaded certificate into token \(String(data: options.key, encoding: .utf8) ?? "")") 354 | } catch CertificateImportError.keysMismatch { 355 | print("Error laoding certificate into token, public key does not match.") 356 | throw ExitCode.failure 357 | } catch CertificateImportError.keyDoesNotExist { 358 | print("Error loading certificate into token, \(String(data: options.key, encoding: .utf8) ?? "") does not exist") 359 | throw ExitCode.failure 360 | } catch { 361 | print("Error loading certificate into token, exiting.") 362 | throw ExitCode.failure 363 | } 364 | 365 | return 366 | } 367 | } 368 | 369 | struct Remove: ParsableCommand { 370 | static var configuration = CommandConfiguration( 371 | abstract: "Remove a mapped certificate and key from the token configuration." 372 | ) 373 | 374 | @OptionGroup var options: Options 375 | 376 | mutating func run() throws { 377 | guard let tokenConfig = loadTokenConfig() else { 378 | print("Could not load token configuration.") 379 | throw ExitCode.failure 380 | } 381 | 382 | let foundItems = tokenConfig.keychainItems.filter({ $0.objectID as! Data == options.key }) 383 | 384 | guard !foundItems.isEmpty else { 385 | print("Token not found with name \(String(data: options.key, encoding: .utf8) ?? "")") 386 | throw ExitCode.failure 387 | } 388 | 389 | tokenConfig.keychainItems = tokenConfig.keychainItems.filter({ $0.objectID as! Data != options.key }) 390 | } 391 | } 392 | 393 | struct Clear: ParsableCommand { 394 | static var configuration = CommandConfiguration( 395 | abstract: "Clear keys and certificates from token configuration." 396 | ) 397 | 398 | mutating func run() throws { 399 | guard let tokenConfig = loadTokenConfig() else { 400 | print("Could not load token configuration.") 401 | throw ExitCode.failure 402 | } 403 | 404 | guard !tokenConfig.keychainItems.isEmpty else { 405 | print("Token configuration is already empty.") 406 | throw ExitCode.failure 407 | } 408 | 409 | tokenConfig.keychainItems.removeAll() 410 | print("Cleared token configuration.") 411 | } 412 | } 413 | } 414 | 415 | 416 | var driverConfig: TKTokenDriver.Configuration { 417 | TKTokenDriver.Configuration.driverConfigurations["com.mwielgoszewski.SecureEnclaveToken.SecureEnclaveTokenExtension"]! 418 | } 419 | 420 | var serialNumber: String? { 421 | let platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice") ) 422 | 423 | guard platformExpert > 0 else { 424 | return nil 425 | } 426 | 427 | let serialNumber = (IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey as CFString, kCFAllocatorDefault, 0).takeUnretainedValue() as? String) 428 | 429 | IOObjectRelease(platformExpert) 430 | return serialNumber 431 | } 432 | 433 | 434 | // A unique, persistent identifier for this token. 435 | // This value is typically generated from the serial number of the target hardware. 436 | var tokenID: String { 437 | let fallbackInstanceID = "819D11D7A8F7D609F236F529996E9F4C" 438 | 439 | guard serialNumber != nil else { 440 | return fallbackInstanceID 441 | } 442 | 443 | let serialHash = SHA256.hash(data: serialNumber!.data(using: .utf8)!).hexStr.dropLast(32) 444 | return String(serialHash) 445 | } 446 | 447 | 448 | func loadTokenConfig() -> TKToken.Configuration? { 449 | if driverConfig.tokenConfigurations.isEmpty { 450 | driverConfig.addTokenConfiguration(for: tokenID) 451 | } 452 | var tokenConfig = driverConfig.tokenConfigurations[tokenID] 453 | if tokenConfig == nil { 454 | tokenConfig = driverConfig.addTokenConfiguration(for: tokenID) 455 | } 456 | return tokenConfig 457 | } 458 | 459 | func unloadTokenConfig() { 460 | driverConfig.removeTokenConfiguration(for: tokenID) 461 | } 462 | 463 | extension Data { 464 | func hexEncodedString() -> String { 465 | return map { String(format: "%02hhx", $0) }.joined() 466 | } 467 | } 468 | 469 | extension Digest { 470 | var bytes: [UInt8] { Array(makeIterator()) } 471 | var data: Data { Data(bytes) } 472 | 473 | var hexStr: String { 474 | bytes.map { String(format: "%02X", $0) }.joined() 475 | } 476 | } 477 | -------------------------------------------------------------------------------- /SecureEnclaveToken/SecureEnclaveTokenUtils.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SecureEnclaveTokenUtils.swift 3 | // SecureEnclaveToken 4 | // 5 | // Created by Marcin Wielgoszewski on 2/11/21. 6 | // 7 | 8 | import Foundation 9 | import Security 10 | import CryptoKit 11 | import CryptoTokenKit 12 | 13 | func generateKeyInEnclaveFromUi(tag: Data, accessibility: CFString, accessControlFlags: Int) -> SecKey { 14 | var flags: SecAccessControlCreateFlags 15 | 16 | switch accessControlFlags { 17 | case 1: 18 | flags = [SecAccessControlCreateFlags.privateKeyUsage, SecAccessControlCreateFlags.userPresence] 19 | case 2: 20 | flags = [SecAccessControlCreateFlags.privateKeyUsage, SecAccessControlCreateFlags.devicePasscode] 21 | case 3: 22 | flags = [SecAccessControlCreateFlags.privateKeyUsage, SecAccessControlCreateFlags.biometryAny] 23 | default: 24 | flags = [SecAccessControlCreateFlags.privateKeyUsage] 25 | } 26 | 27 | return generateKeyInEnclave(tag: tag, accessibility: accessibility, flags: flags) 28 | } 29 | 30 | func generateKeyInEnclave(tag: Data, accessibility: CFString, flags: SecAccessControlCreateFlags) -> SecKey { 31 | let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, 32 | accessibility, 33 | flags, 34 | nil)! // ignore error 35 | 36 | let attributes: [String: Any] = [ 37 | kSecAttrKeyType as String: kSecAttrKeyTypeEC, 38 | kSecAttrKeySizeInBits as String: 256, 39 | kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, 40 | kSecPrivateKeyAttrs as String: [ 41 | kSecAttrIsPermanent as String: true, 42 | kSecAttrApplicationTag as String: tag, 43 | kSecAttrAccessControl as String: access 44 | ] 45 | ] 46 | 47 | var publicKey, privateKey: SecKey? 48 | 49 | _ = SecKeyGeneratePair(attributes as CFDictionary, &publicKey, &privateKey) 50 | 51 | var error: Unmanaged? 52 | 53 | // Create a bogus signature of the data to prove biometric 54 | _ = SecKeyCreateSignature(privateKey!, 55 | .ecdsaSignatureMessageX962SHA256, 56 | tag as CFData, 57 | &error) as Data? 58 | 59 | return privateKey! 60 | } 61 | 62 | func loadSecureEnclaveKey(tag: Data) -> SecKey? { 63 | var item: CFTypeRef? 64 | var key: SecKey 65 | 66 | let query: [String: Any] = [kSecClass as String: kSecClassKey, 67 | kSecAttrApplicationTag as String: tag, 68 | kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, 69 | kSecReturnRef as String: true] 70 | 71 | let status = SecItemCopyMatching(query as CFDictionary, &item) 72 | if status == errSecSuccess { 73 | key = (item as! SecKey) 74 | return key 75 | } else { 76 | return nil 77 | } 78 | } 79 | 80 | func deleteSecureEnclaveKey(tag: Data) -> Bool { 81 | let query: [String: Any] = [kSecClass as String: kSecClassKey, 82 | kSecAttrApplicationTag as String: tag, 83 | kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, 84 | kSecReturnRef as String: true] 85 | 86 | let status = SecItemDelete(query as CFDictionary) 87 | return status == errSecSuccess 88 | } 89 | 90 | enum CertificateImportError: Error { 91 | case keysMismatch, keyDoesNotExist 92 | } 93 | 94 | func addCertificateToToken(certificate: SecCertificate, tag: Data, tokenConfig: TKToken.Configuration) throws { 95 | 96 | let certificatePublicKey = SecCertificateCopyKey(certificate) 97 | 98 | let secKey = loadSecureEnclaveKey(tag: tag) 99 | guard secKey != nil else { 100 | throw CertificateImportError.keyDoesNotExist 101 | } 102 | 103 | let publicKey = SecKeyCopyPublicKey(secKey!) 104 | 105 | var error: Unmanaged? 106 | let ixy = SecKeyCopyExternalRepresentation(publicKey!, &error) 107 | let bytes: Data = ixy! as Data 108 | 109 | let ixy2 = SecKeyCopyExternalRepresentation(certificatePublicKey!, &error) 110 | let bytes2: Data = ixy2! as Data 111 | 112 | if bytes != bytes2 { 113 | throw CertificateImportError.keysMismatch 114 | } 115 | 116 | let publicKeyHash = Insecure.SHA1.hash(data: bytes) 117 | 118 | var commonName: CFString? 119 | _ = SecCertificateCopyCommonName(certificate, &commonName) 120 | 121 | let tokenCertificate = TKTokenKeychainCertificate(certificate: certificate, objectID: tag) 122 | tokenCertificate?.label = "\(String(data: tag, encoding: .utf8) ?? "") certificate" 123 | 124 | let tokenKey = TKTokenKeychainKey(certificate: certificate, objectID: tag) 125 | tokenKey?.label = "\(String(data: tag, encoding: .utf8) ?? "") key" 126 | tokenKey?.canSign = true 127 | tokenKey?.canPerformKeyExchange = true 128 | tokenKey?.isSuitableForLogin = true 129 | tokenKey?.canDecrypt = false 130 | tokenKey?.applicationTag = tag 131 | tokenKey?.keyType = kSecAttrKeyTypeECSECPrimeRandom as String 132 | tokenKey?.publicKeyData = bytes 133 | tokenKey?.publicKeyHash = publicKeyHash.data 134 | 135 | tokenConfig.keychainItems.append(tokenKey!) 136 | tokenConfig.keychainItems.append(tokenCertificate!) 137 | return 138 | } 139 | 140 | 141 | func loadCertificateForTagIntoTokenConfig(certificatePath: URL, tag: Data, tokenConfig: TKToken.Configuration) -> SecCertificate? { 142 | 143 | if FileManager.default.fileExists(atPath: certificatePath.path) { 144 | do { 145 | let certificateData = try Data(contentsOf: certificatePath) 146 | print("Read certificate") 147 | 148 | let certificate = SecCertificateCreateWithData(nil, certificateData as CFData)! 149 | print(certificate) 150 | 151 | try addCertificateToToken(certificate: certificate, tag: tag, tokenConfig: tokenConfig) 152 | return certificate 153 | } catch { 154 | print("Failed to create cert??") 155 | } 156 | } else { 157 | print("Certificate is not a file") 158 | } 159 | return nil 160 | } 161 | 162 | func importCertificateAndCreateSecIdentity(key: SecKey, certificatePath: URL, tag: Data) -> SecIdentity? { 163 | print("Loading certificate from \(certificatePath.path)") 164 | 165 | do { 166 | let certificateData = try Data(contentsOf: certificatePath) 167 | let certificate = SecCertificateCreateWithData(nil, certificateData as CFData) 168 | 169 | if certificate != nil { 170 | print("Loaded certificate \(certificate.debugDescription)") 171 | } 172 | 173 | var identity: SecIdentity? 174 | var status = SecIdentityCreateWithCertificate(nil, certificate!, &identity) 175 | 176 | if status != errSecSuccess { 177 | print("Failed to create identity") 178 | } else { 179 | print("Got identity: \(identity.debugDescription)") 180 | 181 | var item: CFTypeRef? 182 | 183 | let label = "Secure Enclave Generated Key".data(using: .utf8)! 184 | 185 | let query: [String: Any] = [ 186 | kSecClass as String: kSecClassIdentity, 187 | kSecValueRef as String: identity!, 188 | kSecAttrApplicationTag as String: tag, 189 | kSecAttrLabel as String: label 190 | ] 191 | 192 | print("Adding identity to KeyChain") 193 | status = SecItemAdd(query as CFDictionary, &item) 194 | if status == errSecSuccess { 195 | print("Saved identity to KeyChain") 196 | } else { 197 | print("Failed to save identity: \(status)") 198 | } 199 | 200 | return identity 201 | } 202 | 203 | } catch { 204 | print("Failed to load certificate from \(certificatePath.path)") 205 | } 206 | 207 | return nil 208 | } 209 | -------------------------------------------------------------------------------- /SecureEnclaveToken/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // SecureEnclaveToken 4 | // 5 | // Created by Marcin Wielgoszewski on 9/24/22. 6 | // 7 | 8 | import Foundation 9 | import AppKit 10 | 11 | 12 | let app = NSApplication.shared 13 | let delegate = AppDelegate() 14 | app.delegate = delegate 15 | 16 | // 2 17 | _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) 18 | 19 | -------------------------------------------------------------------------------- /SecureEnclaveTokenExtension/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleDisplayName 8 | SecureEnclaveTokenExtension 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | $(PRODUCT_BUNDLE_PACKAGE_TYPE) 19 | CFBundleShortVersionString 20 | $(MARKETING_VERSION) 21 | CFBundleVersion 22 | 1 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSExtension 26 | 27 | NSExtensionAttributes 28 | 29 | com.apple.ctk.aid 30 | ___VARIABLE_smartCardAID___ 31 | com.apple.ctk.class-id 32 | com.mwielgoszewski.SecureEnclaveToken.SecureEnclaveTokenExtension 33 | com.apple.ctk.driver-class 34 | $(PRODUCT_MODULE_NAME).TokenDriver 35 | com.apple.ctk.token-type 36 | smartcard 37 | 38 | NSExtensionPointIdentifier 39 | com.apple.ctk-tokens 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /SecureEnclaveTokenExtension/SecureEnclaveTokenExtension.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.files.user-selected.read-write 8 | 9 | com.apple.security.smartcard 10 | 11 | keychain-access-groups 12 | 13 | $(AppIdentifierPrefix)com.mwielgoszewski.SecureEnclaveToken 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /SecureEnclaveTokenExtension/Token.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Token.swift 3 | // SecureEnclaveTokenExtension 4 | // 5 | // Created by Marcin Wielgoszewski on 2/11/21. 6 | // 7 | 8 | import CryptoTokenKit 9 | 10 | class Token: TKToken, TKTokenDelegate { 11 | 12 | init(tokenDriver: TokenDriver, instanceID: TKToken.InstanceID) throws { 13 | NSLog("Initializing Token configuration based interface") 14 | NSLog("Got instanceID: \(instanceID)") 15 | super.init(tokenDriver: tokenDriver, instanceID: instanceID) 16 | self.keychainContents?.fill(with: configuration.keychainItems) 17 | } 18 | 19 | func createSession(_ token: TKToken) throws -> TKTokenSession { 20 | return TokenSession(token: self) 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /SecureEnclaveTokenExtension/TokenDriver.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TokenDriver.swift 3 | // SecureEnclaveTokenExtension 4 | // 5 | // Created by Marcin Wielgoszewski on 2/11/21. 6 | // 7 | 8 | import CryptoTokenKit 9 | 10 | class TokenDriver: TKTokenDriver, TKTokenDriverDelegate { 11 | 12 | func tokenDriver(_ driver: TKTokenDriver, tokenFor configuration: TKToken.Configuration) throws -> TKToken { 13 | NSLog("CTK/SecureEnclaveTokenExtension Initializing") 14 | return try Token(tokenDriver: self, instanceID: configuration.instanceID) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /SecureEnclaveTokenExtension/TokenSession.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TokenSession.swift 3 | // SecureEnclaveTokenExtension 4 | // 5 | // Created by Marcin Wielgoszewski on 2/11/21. 6 | // 7 | 8 | import CryptoTokenKit 9 | 10 | class TokenSession: TKTokenSession, TKTokenSessionDelegate { 11 | 12 | func tokenSession(_ session: TKTokenSession, beginAuthFor operation: TKTokenOperation, constraint: Any) throws -> TKTokenAuthOperation { 13 | // Insert code here to create an instance of TKTokenAuthOperation based on the specified operation and constraint. 14 | // Note that the constraint was previously established when populating keychainContents during token initialization. 15 | return TKTokenSmartCardPINAuthOperation() 16 | } 17 | 18 | func tokenSession(_ session: TKTokenSession, supports operation: TKTokenOperation, keyObjectID: Any, algorithm: TKTokenKeyAlgorithm) -> Bool { 19 | // Indicate whether the given key supports the specified operation and algorithm. 20 | let tag = String(data: keyObjectID as! Data, encoding: .utf8)! 21 | 22 | NSLog("Querying for keyObjectID: \(tag) to determine whether TKTokenOperation:\(operation.rawValue) is supported") 23 | 24 | var item: CFTypeRef? 25 | var privateKey: SecKey 26 | let query: [String: Any] = [kSecClass as String: kSecClassKey, 27 | kSecAttrApplicationTag as String: tag, 28 | kSecAttrKeyType as String: kSecAttrKeyTypeEC, 29 | kSecReturnRef as String: true] 30 | 31 | let status = SecItemCopyMatching(query as CFDictionary, &item) 32 | guard status == errSecSuccess else { 33 | NSLog("Could not find private key with tag: \(tag)") 34 | return false 35 | } 36 | 37 | privateKey = (item as! SecKey) 38 | 39 | guard let alg = tokenAlgorithmToSecKeyAlgorithm(algorithm) else { 40 | return false 41 | } 42 | 43 | switch operation { 44 | case .signData: 45 | NSLog("Checking if keyObjectID: \(tag) can sign for algorithm \(alg.rawValue)") 46 | return SecKeyIsAlgorithmSupported(privateKey, SecKeyOperationType.sign, alg) 47 | case .performKeyExchange: 48 | NSLog("Checking if keyObjectID: \(tag) can perform key exchange \(alg.rawValue)") 49 | return SecKeyIsAlgorithmSupported(privateKey, SecKeyOperationType.keyExchange, alg) 50 | case .none: 51 | break 52 | case .readData: 53 | break 54 | case .decryptData: 55 | NSLog("Checking if keyObjectID: \(tag) can decrypt for algorithm \(alg.rawValue)") 56 | return SecKeyIsAlgorithmSupported(privateKey, SecKeyOperationType.decrypt, alg) 57 | @unknown default: 58 | NSLog("Unhandled token operation requested: \(operation.rawValue)") 59 | } 60 | 61 | NSLog("Key \(tag) does not support operation: \(operation.rawValue)") 62 | return false 63 | } 64 | 65 | func tokenSession(_ session: TKTokenSession, sign dataToSign: Data, keyObjectID: Any, algorithm: TKTokenKeyAlgorithm) throws -> Data { 66 | let tag = String(data: keyObjectID as! Data, encoding: .utf8)! 67 | 68 | guard let alg = tokenAlgorithmToSecKeyAlgorithm(algorithm) else { 69 | throw NSError(domain: TKErrorDomain, code: TKError.Code.badParameter.rawValue, userInfo: nil) 70 | } 71 | 72 | NSLog("Querying for keyObjectID: \(tag) to sign \(dataToSign) with \(alg.rawValue)") 73 | 74 | var item: CFTypeRef? 75 | var privateKey: SecKey 76 | let query: [String: Any] = [kSecClass as String: kSecClassKey, 77 | kSecAttrApplicationTag as String: tag, 78 | kSecAttrKeyType as String: kSecAttrKeyTypeEC, 79 | kSecReturnRef as String: true] 80 | 81 | let status = SecItemCopyMatching(query as CFDictionary, &item) 82 | guard status == errSecSuccess else { 83 | // If the operation failed for some reason, fill in an appropriate error like objectNotFound, corruptedData, etc. 84 | // Note that responding with TKErrorCodeAuthenticationNeeded will trigger user authentication after which the current operation will be re-attempted. 85 | throw NSError(domain: TKErrorDomain, code: TKError.Code.objectNotFound.rawValue, userInfo: nil) 86 | } 87 | 88 | privateKey = (item as! SecKey) 89 | 90 | var error: Unmanaged? 91 | guard let signature = SecKeyCreateSignature(privateKey, 92 | alg, 93 | dataToSign as CFData, 94 | &error) as Data? else { 95 | throw error!.takeRetainedValue() as Error 96 | } 97 | 98 | return signature 99 | } 100 | 101 | func tokenSession(_ session: TKTokenSession, decrypt ciphertext: Data, keyObjectID: Any, algorithm: TKTokenKeyAlgorithm) throws -> Data { 102 | throw NSError(domain: TKErrorDomain, code: TKError.Code.notImplemented.rawValue, userInfo: nil) 103 | } 104 | 105 | func tokenSession(_ session: TKTokenSession, performKeyExchange otherPartyPublicKeyData: Data, keyObjectID objectID: Any, algorithm: TKTokenKeyAlgorithm, parameters: TKTokenKeyExchangeParameters) throws -> Data { 106 | let tag = String(data: objectID as! Data, encoding: .utf8)! 107 | 108 | NSLog("Querying for keyObjectID: \(tag) to perform key exchange") 109 | 110 | var item: CFTypeRef? 111 | var privateKey: SecKey 112 | let query: [String: Any] = [kSecClass as String: kSecClassKey, 113 | kSecAttrApplicationTag as String: tag, 114 | kSecAttrKeyType as String: kSecAttrKeyTypeEC, 115 | kSecReturnRef as String: true] 116 | 117 | let status = SecItemCopyMatching(query as CFDictionary, &item) 118 | guard status == errSecSuccess else { 119 | // If the operation failed for some reason, fill in an appropriate error like objectNotFound, corruptedData, etc. 120 | // Note that responding with TKErrorCodeAuthenticationNeeded will trigger user authentication after which the current operation will be re-attempted. 121 | throw NSError(domain: TKErrorDomain, code: TKError.Code.objectNotFound.rawValue, userInfo: nil) 122 | } 123 | 124 | privateKey = (item as! SecKey) 125 | 126 | let attributes: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, 127 | kSecAttrKeyClass as String: kSecAttrKeyClassPublic, 128 | kSecAttrKeySizeInBits as String: 256] 129 | 130 | var error: Unmanaged? 131 | guard let publicKey = SecKeyCreateWithData(otherPartyPublicKeyData as CFData, 132 | attributes as CFDictionary, 133 | &error) else { 134 | throw error!.takeRetainedValue() as Error 135 | } 136 | 137 | guard let kexAlg = tokenAlgorithmToSecKeyAlgorithm(algorithm) else { 138 | throw NSError(domain: TKErrorDomain, code: TKError.Code.badParameter.rawValue, userInfo: nil) 139 | } 140 | 141 | guard let secret = SecKeyCopyKeyExchangeResult(privateKey, 142 | kexAlg, 143 | publicKey, 144 | parameters as! CFDictionary, 145 | &error) as Data? else { 146 | throw error!.takeRetainedValue() as Error 147 | } 148 | return secret 149 | } 150 | 151 | private func tokenAlgorithmToSecKeyAlgorithm(_ algorithm: TKTokenKeyAlgorithm) -> SecKeyAlgorithm? { 152 | 153 | if algorithm.isAlgorithm(.ecdsaSignatureRFC4754) { 154 | return .ecdsaSignatureRFC4754 155 | } else if algorithm.isAlgorithm(.ecdsaSignatureDigestX962) { 156 | return .ecdsaSignatureDigestX962 157 | } else if algorithm.isAlgorithm(.ecdsaSignatureDigestX962SHA1) { 158 | return .ecdsaSignatureDigestX962SHA1 159 | } else if algorithm.isAlgorithm(.ecdsaSignatureDigestX962SHA224) { 160 | return .ecdsaSignatureDigestX962SHA224 161 | } else if algorithm.isAlgorithm(.ecdsaSignatureDigestX962SHA256) { 162 | return .ecdsaSignatureDigestX962SHA256 163 | } else if algorithm.isAlgorithm(.ecdsaSignatureDigestX962SHA384) { 164 | return .ecdsaSignatureDigestX962SHA384 165 | } else if algorithm.isAlgorithm(.ecdsaSignatureDigestX962SHA512) { 166 | return .ecdsaSignatureDigestX962SHA512 167 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeStandard) { 168 | return .ecdhKeyExchangeStandard 169 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeStandardX963SHA1) { 170 | return .ecdhKeyExchangeStandardX963SHA1 171 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeStandardX963SHA224) { 172 | return .ecdhKeyExchangeStandardX963SHA224 173 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeStandardX963SHA256) { 174 | return .ecdhKeyExchangeStandardX963SHA256 175 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeStandardX963SHA384) { 176 | return .ecdhKeyExchangeStandardX963SHA384 177 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeStandardX963SHA512) { 178 | return .ecdhKeyExchangeStandardX963SHA512 179 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeCofactor) { 180 | return .ecdhKeyExchangeCofactor 181 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeCofactorX963SHA1) { 182 | return .ecdhKeyExchangeCofactorX963SHA1 183 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeCofactorX963SHA224) { 184 | return .ecdhKeyExchangeCofactorX963SHA224 185 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeCofactorX963SHA256) { 186 | return .ecdhKeyExchangeCofactorX963SHA256 187 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeCofactorX963SHA384) { 188 | return .ecdhKeyExchangeCofactorX963SHA384 189 | } else if algorithm.isAlgorithm(.ecdhKeyExchangeCofactorX963SHA512) { 190 | return .ecdhKeyExchangeCofactorX963SHA512 191 | } 192 | 193 | return nil 194 | 195 | } 196 | 197 | } 198 | -------------------------------------------------------------------------------- /images/SecureEnclaveToken.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mwielgoszewski/SecureEnclaveToken/c0ff9401a67800ec8a01da54202f3d31474f47e0/images/SecureEnclaveToken.png --------------------------------------------------------------------------------