Compare commits
161 Commits
Author | SHA1 | Date | |
---|---|---|---|
067f1526b0 | |||
f43dea0d0d | |||
db8833fa25 | |||
1409e9ac31 | |||
adabe801d3 | |||
19f9494492 | |||
c50d2feaf9 | |||
03d3cc9177 | |||
141cc03b60 | |||
07559bd7ef | |||
cb206a18c2 | |||
6cb3ff80d9 | |||
05c5aca9b6 | |||
5894bbca00 | |||
3df7ce6256 | |||
b0322b4c1f | |||
7b7615ca38 | |||
da2c460c60 | |||
eb282b4116 | |||
fb6cebe92f | |||
22d9b37d63 | |||
ee3e844519 | |||
3f34e91a2c | |||
f249932ff2 | |||
6eee29e1fa | |||
836aa983ed | |||
9aacd73673 | |||
cda56ea14b | |||
86719e893b | |||
79f7177ffb | |||
6bb9fd376f | |||
7d9fee0546 | |||
faed5514e2 | |||
4ab3783a15 | |||
88b7ef82da | |||
3d305d95ac | |||
3f04126d00 | |||
9d6bbd2a04 | |||
35aea0729d | |||
c5bd4c2189 | |||
8114acf50a | |||
cd965b9ec6 | |||
f30d1f802f | |||
af479408a4 | |||
42b034270a | |||
dca340ad40 | |||
8dfabd35aa | |||
9c28efab5c | |||
698a69a034 | |||
4105c1d6f6 | |||
4de805dd37 | |||
0544287141 | |||
8ec19d1fb7 | |||
6c3748b6bf | |||
dc91f61dba | |||
702388fdf8 | |||
a368acea62 | |||
76514d410b | |||
08b5c7b13c | |||
f801853878 | |||
3c9659bd06 | |||
4d4b20c38d | |||
1f0100ff2d | |||
59ec40c611 | |||
edf01cc6d4 | |||
de21e1040e | |||
d47c5424ad | |||
b85acebae1 | |||
4d4619bdd8 | |||
50adf4cd48 | |||
dc5c21c568 | |||
3328ada3bf | |||
3774352dfd | |||
85e096f8cc | |||
331e4ed0d6 | |||
4cc312d4fa | |||
f3d70a57c5 | |||
55b57e0cbf | |||
82dcb76ee6 | |||
bd0e27060c | |||
393f2797ab | |||
f1bf863a9d | |||
c09d1e4020 | |||
52225ab5e3 | |||
8b7e3f6b87 | |||
bc25576c1f | |||
b234100aa5 | |||
bc0a45366a | |||
6dbb3b7fb3 | |||
8bbf489146 | |||
30148ee3a4 | |||
c306801149 | |||
9c60a0b7dd | |||
5b38ef00c1 | |||
ccbf92785d | |||
f1e8e43f62 | |||
7b1563f167 | |||
cca070dbe4 | |||
31e51e45c1 | |||
4bfb3a0012 | |||
a0ed880386 | |||
92b9648e04 | |||
4a2a342670 | |||
1d147d8e34 | |||
4dcc9b113d | |||
1f7ebcfe75 | |||
b090a96975 | |||
594d855f19 | |||
89f0798576 | |||
0d74f6f561 | |||
efeb7f09a3 | |||
104199cf53 | |||
f214da98a4 | |||
95cf88d3ca | |||
04835fa437 | |||
31dfba8265 | |||
df8eedebd0 | |||
0a9ecb039e | |||
2e9a3eb90d | |||
df599fbe62 | |||
7c60e9b04b | |||
f7f182ec77 | |||
a0052e8395 | |||
10d3fa150c | |||
c5abca4099 | |||
f674d47507 | |||
1e3ece600d | |||
7481498c5b | |||
a6fbcdbe55 | |||
36e655e527 | |||
dd3acf5ae1 | |||
2257e1e190 | |||
fe16e4d9c4 | |||
1caf65c68d | |||
85eb4983bc | |||
5a2d3ecc2e | |||
32f0ed88f4 | |||
d35c58509b | |||
f810b185f0 | |||
5ef1fe996b | |||
2b5fdf541d | |||
4b66e874a7 | |||
aa52da2c04 | |||
bd683b16f2 | |||
017bdb85a4 | |||
99c8562cf5 | |||
12b920b0af | |||
bfb4f80b8c | |||
d661b9002b | |||
9daae8957a | |||
bde9085d31 | |||
84521cf8d6 | |||
4a6e8c0b11 | |||
ae06e8e892 | |||
57e6b6779f | |||
6136fc2e69 | |||
2c052e2657 | |||
0918e570e4 | |||
024c25bcd9 | |||
154dac3e50 | |||
d778760cc1 |
1
.github/FUNDING.yml
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
github: maxgoedjen
|
BIN
.github/readme/app.png
vendored
Before Width: | Height: | Size: 348 KiB After Width: | Height: | Size: 456 KiB |
BIN
.github/readme/apple_watch_auth_mac.png
vendored
Normal file
After Width: | Height: | Size: 192 KiB |
BIN
.github/readme/apple_watch_auth_watch.png
vendored
Normal file
After Width: | Height: | Size: 26 KiB |
BIN
.github/readme/apple_watch_system_prefs.png
vendored
Normal file
After Width: | Height: | Size: 631 KiB |
BIN
.github/readme/notification.png
vendored
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 1.1 MiB |
BIN
.github/readme/touchid.png
vendored
Before Width: | Height: | Size: 135 KiB After Width: | Height: | Size: 190 KiB |
5
.github/scripts/signing.sh
vendored
@ -10,10 +10,13 @@ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k ci ci.keyc
|
|||||||
|
|
||||||
# Import Profiles
|
# Import Profiles
|
||||||
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
|
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
|
||||||
|
|
||||||
echo $HOST_PROFILE_DATA | base64 -d -o Host.provisionprofile
|
echo $HOST_PROFILE_DATA | base64 -d -o Host.provisionprofile
|
||||||
HOST_UUID=`grep UUID -A1 -a Host.provisionprofile | grep -io "[-A-F0-9]\{36\}"`
|
HOST_UUID=`grep UUID -A1 -a Host.provisionprofile | grep -io "[-A-F0-9]\{36\}"`
|
||||||
cp Host.provisionprofile ~/Library/MobileDevice/Provisioning\ Profiles/$HOST_UUID.provisionprofile
|
cp Host.provisionprofile ~/Library/MobileDevice/Provisioning\ Profiles/$HOST_UUID.provisionprofile
|
||||||
echo $AGENT_PROFILE_DATA | base64 -d -o Agent.provisionprofile
|
echo $AGENT_PROFILE_DATA | base64 -d -o Agent.provisionprofile
|
||||||
AGENT_UUID=`grep UUID -A1 -a Agent.provisionprofile | grep -io "[-A-F0-9]\{36\}"`
|
AGENT_UUID=`grep UUID -A1 -a Agent.provisionprofile | grep -io "[-A-F0-9]\{36\}"`
|
||||||
cp Agent.provisionprofile ~/Library/MobileDevice/Provisioning\ Profiles/$AGENT_UUID.provisionprofile
|
cp Agent.provisionprofile ~/Library/MobileDevice/Provisioning\ Profiles/$AGENT_UUID.provisionprofile
|
||||||
|
|
||||||
|
# Create directories for ASC key
|
||||||
|
mkdir ~/.private_keys
|
||||||
|
echo -n "$APPLE_API_KEY_DATA" > ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8
|
||||||
|
49
.github/workflows/nightly.yml
vendored
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
name: Nightly
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 8 * * *"
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: macos-11.0
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Setup Signing
|
||||||
|
env:
|
||||||
|
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||||
|
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||||
|
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||||
|
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||||
|
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
run: ./.github/scripts/signing.sh
|
||||||
|
- name: Set Environment
|
||||||
|
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||||
|
- name: Update Build Number
|
||||||
|
env:
|
||||||
|
RUN_ID: ${{ github.run_id }}
|
||||||
|
run: |
|
||||||
|
sed -i '' -e "s/GITHUB_CI_VERSION/0.0.0/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Secretive/Credits.rtf
|
||||||
|
- name: Build
|
||||||
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||||
|
- name: Create ZIPs
|
||||||
|
run: |
|
||||||
|
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
||||||
|
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
||||||
|
- name: Notarize
|
||||||
|
env:
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||||
|
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
||||||
|
- name: Document SHAs
|
||||||
|
run: |
|
||||||
|
shasum -a 512 Secretive.zip
|
||||||
|
shasum -a 512 Archive.zip
|
||||||
|
- name: Upload App to Artifacts
|
||||||
|
uses: actions/upload-artifact@v1
|
||||||
|
with:
|
||||||
|
name: Secretive.zip
|
||||||
|
path: Secretive.zip
|
111
.github/workflows/release.yml
vendored
@ -5,11 +5,67 @@ on:
|
|||||||
tags:
|
tags:
|
||||||
- '*'
|
- '*'
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
test:
|
||||||
runs-on: macOS-latest
|
runs-on: macos-11.0
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v1
|
||||||
|
- name: Setup Signing
|
||||||
|
env:
|
||||||
|
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||||
|
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||||
|
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||||
|
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||||
|
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
run: ./.github/scripts/signing.sh
|
||||||
|
- name: Set Environment
|
||||||
|
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||||
|
- name: Test
|
||||||
|
run: |
|
||||||
|
pushd Sources/Packages
|
||||||
|
swift test
|
||||||
|
popd
|
||||||
|
build:
|
||||||
|
runs-on: macos-11.0
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Setup Signing
|
||||||
|
env:
|
||||||
|
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||||
|
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||||
|
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||||
|
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||||
|
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
run: ./.github/scripts/signing.sh
|
||||||
|
- name: Set Environment
|
||||||
|
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||||
|
- name: Update Build Number
|
||||||
|
env:
|
||||||
|
TAG_NAME: ${{ github.ref }}
|
||||||
|
RUN_ID: ${{ github.run_id }}
|
||||||
|
run: |
|
||||||
|
export CLEAN_TAG=$(echo $TAG_NAME | sed -e 's/refs\/tags\/v//')
|
||||||
|
sed -i '' -e "s/GITHUB_CI_VERSION/$CLEAN_TAG/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||||
|
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Secretive/Credits.rtf
|
||||||
|
- name: Build
|
||||||
|
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||||
|
- name: Create ZIPs
|
||||||
|
run: |
|
||||||
|
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
||||||
|
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
||||||
|
- name: Notarize
|
||||||
|
env:
|
||||||
|
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||||
|
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||||
|
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
||||||
|
- name: Document SHAs
|
||||||
|
run: |
|
||||||
|
shasum -a 512 Secretive.zip
|
||||||
|
shasum -a 512 Archive.zip
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: actions/create-release@v1
|
uses: actions/create-release@v1
|
||||||
@ -18,33 +74,24 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
tag_name: ${{ github.ref }}
|
tag_name: ${{ github.ref }}
|
||||||
release_name: ${{ github.ref }}
|
release_name: ${{ github.ref }}
|
||||||
body: ''
|
body: |
|
||||||
|
Update description
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
|
||||||
|
## Fixes
|
||||||
|
|
||||||
|
|
||||||
|
## Minimum macOS Version
|
||||||
|
|
||||||
|
|
||||||
|
## Build
|
||||||
|
https://github.com/maxgoedjen/secretive/actions/runs/${{ github.run_id }}
|
||||||
draft: true
|
draft: true
|
||||||
prerelease: false
|
prerelease: false
|
||||||
- name: Set up signing
|
|
||||||
env:
|
|
||||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
|
||||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
|
||||||
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
|
||||||
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
|
||||||
run: ./.github/scripts/signing.sh
|
|
||||||
- name: Build
|
|
||||||
run: xcrun xcodebuild -project Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
|
||||||
- name: Create ZIPs
|
|
||||||
run: |
|
|
||||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
|
||||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
|
||||||
- name: Notarize
|
|
||||||
env:
|
|
||||||
APPLE_USERNAME: ${{ secrets.APPLE_USERNAME }}
|
|
||||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
|
||||||
run: xcrun altool --notarize-app --primary-bundle-id "com.maxgoedjen.secretive.host" --username $APPLE_USERNAME --password $APPLE_PASSWORD --file Secretive.zip
|
|
||||||
- name: Document SHAs
|
|
||||||
run: |
|
|
||||||
shasum -a 512 Secretive.zip
|
|
||||||
shasum -a 512 Archive.zip
|
|
||||||
- name: Upload App to Release
|
- name: Upload App to Release
|
||||||
id: upload-release-asset
|
id: upload-release-asset-app
|
||||||
uses: actions/upload-release-asset@v1.0.1
|
uses: actions/upload-release-asset@v1.0.1
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@ -53,13 +100,13 @@ jobs:
|
|||||||
asset_path: ./Secretive.zip
|
asset_path: ./Secretive.zip
|
||||||
asset_name: Secretive.zip
|
asset_name: Secretive.zip
|
||||||
asset_content_type: application/zip
|
asset_content_type: application/zip
|
||||||
- name: Upload Archive to Artifacts
|
- name: Upload App to Artifacts
|
||||||
uses: actions/upload-artifact@v1
|
|
||||||
with:
|
|
||||||
name: Archive.zip
|
|
||||||
path: Archive.zip
|
|
||||||
- name: Upload Archive to Artifacts
|
|
||||||
uses: actions/upload-artifact@v1
|
uses: actions/upload-artifact@v1
|
||||||
with:
|
with:
|
||||||
name: Secretive.zip
|
name: Secretive.zip
|
||||||
path: Secretive.zip
|
path: Secretive.zip
|
||||||
|
- name: Upload Archive to Artifacts
|
||||||
|
uses: actions/upload-artifact@v1
|
||||||
|
with:
|
||||||
|
name: Xcode_Archive.zip
|
||||||
|
path: Archive.zip
|
||||||
|
16
.github/workflows/test.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
name: Test
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: macos-11.0
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Set Environment
|
||||||
|
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||||
|
- name: Test
|
||||||
|
run: |
|
||||||
|
pushd Sources/Packages
|
||||||
|
swift test
|
||||||
|
popd
|
2
.gitignore
vendored
@ -91,3 +91,5 @@ iOSInjectionProject/
|
|||||||
|
|
||||||
# Build script products
|
# Build script products
|
||||||
Archive.xcarchive
|
Archive.xcarchive
|
||||||
|
.DS_Store
|
||||||
|
contents.xcworkspacedata
|
||||||
|
82
APP_CONFIG.md
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
# Setting up Third Party Apps FAQ
|
||||||
|
|
||||||
|
## Tower
|
||||||
|
|
||||||
|
Tower provides [instructions](https://www.git-tower.com/help/mac/integration/environment).
|
||||||
|
|
||||||
|
## GitHub Desktop
|
||||||
|
|
||||||
|
Should just work, no configuration needed
|
||||||
|
|
||||||
|
## Fork
|
||||||
|
|
||||||
|
Add this to your `~/.ssh/config` (the path should match the socket path from the setup flow).
|
||||||
|
|
||||||
|
```
|
||||||
|
Host *
|
||||||
|
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
|
||||||
|
```
|
||||||
|
|
||||||
|
## VS Code
|
||||||
|
|
||||||
|
Add this to your `~/.ssh/config` (the path should match the socket path from the setup flow).
|
||||||
|
|
||||||
|
```
|
||||||
|
Host *
|
||||||
|
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cyberduck
|
||||||
|
|
||||||
|
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
||||||
|
|
||||||
|
```
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key>
|
||||||
|
<string>link-ssh-auth-sock</string>
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
<string>/bin/sh</string>
|
||||||
|
<string>-c</string>
|
||||||
|
<string>/bin/ln -sf $HOME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh $SSH_AUTH_SOCK</string>
|
||||||
|
</array>
|
||||||
|
<key>RunAtLoad</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
|
```
|
||||||
|
|
||||||
|
Log out and log in again before launching Cyberduck.
|
||||||
|
|
||||||
|
## GitKraken
|
||||||
|
|
||||||
|
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
||||||
|
|
||||||
|
```
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key>
|
||||||
|
<string>link-ssh-auth-sock</string>
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
<string>/bin/sh</string>
|
||||||
|
<string>-c</string>
|
||||||
|
<string>/bin/ln -sf $HOME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh $SSH_AUTH_SOCK</string>
|
||||||
|
</array>
|
||||||
|
<key>RunAtLoad</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
|
```
|
||||||
|
|
||||||
|
Log out and log in again before launching Gitkraken. Then enable "Use local SSH agent in GitKraken Preferences (Located under Preferences -> SSH)
|
||||||
|
|
||||||
|
# The app I use isn't listed here!
|
||||||
|
|
||||||
|
If you know how to get it set up, please open a PR for this page and add it! Contributions are very welcome.
|
||||||
|
If you're not able to get it working, please file a [GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) for it. No guarantees we'll be able to get it working, but chances are someone else in the community might be able to.
|
76
CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
In the interest of fostering an open and welcoming environment, we as
|
||||||
|
contributors and maintainers pledge to making participation in our project and
|
||||||
|
our community a harassment-free experience for everyone, regardless of age, body
|
||||||
|
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||||
|
level of experience, education, socio-economic status, nationality, personal
|
||||||
|
appearance, race, religion, or sexual identity and orientation.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to creating a positive environment
|
||||||
|
include:
|
||||||
|
|
||||||
|
* Using welcoming and inclusive language
|
||||||
|
* Being respectful of differing viewpoints and experiences
|
||||||
|
* Gracefully accepting constructive criticism
|
||||||
|
* Focusing on what is best for the community
|
||||||
|
* Showing empathy towards other community members
|
||||||
|
|
||||||
|
Examples of unacceptable behavior by participants include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||||
|
advances
|
||||||
|
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or electronic
|
||||||
|
address, without explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a
|
||||||
|
professional setting
|
||||||
|
|
||||||
|
## Our Responsibilities
|
||||||
|
|
||||||
|
Project maintainers are responsible for clarifying the standards of acceptable
|
||||||
|
behavior and are expected to take appropriate and fair corrective action in
|
||||||
|
response to any instances of unacceptable behavior.
|
||||||
|
|
||||||
|
Project maintainers have the right and responsibility to remove, edit, or
|
||||||
|
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||||
|
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||||
|
permanently any contributor for other behaviors that they deem inappropriate,
|
||||||
|
threatening, offensive, or harmful.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies both within project spaces and in public spaces
|
||||||
|
when an individual is representing the project or its community. Examples of
|
||||||
|
representing a project or community include using an official project e-mail
|
||||||
|
address, posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event. Representation of a project may be
|
||||||
|
further defined and clarified by project maintainers.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported by contacting the project team at max.goedjen@gmail.com. All
|
||||||
|
complaints will be reviewed and investigated and will result in a response that
|
||||||
|
is deemed necessary and appropriate to the circumstances. The project team is
|
||||||
|
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||||
|
Further details of specific enforcement policies may be posted separately.
|
||||||
|
|
||||||
|
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||||
|
faith may face temporary or permanent repercussions as determined by other
|
||||||
|
members of the project's leadership.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||||
|
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see
|
||||||
|
https://www.contributor-covenant.org/faq
|
27
CONTRIBUTING.md
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
# Contributing to Secretive
|
||||||
|
|
||||||
|
Thanks for your interest in contributing to Secretive! Before you contribute, there are a few things I'd like to lay out.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
Security is obviously paramount for a project like Secretive. As such, any contributions that compromise the security or auditabilty of the project will be rejected.
|
||||||
|
|
||||||
|
### Dependencies
|
||||||
|
|
||||||
|
Secretive is designed to be easily auditable by people who are considering using it. In keeping with this, Secretive has no third party dependencies, and any contributions which bring in new dependencies will be rejected.
|
||||||
|
|
||||||
|
## Code of Conduct
|
||||||
|
|
||||||
|
All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md)
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
|
||||||
|
If you make a material contribution to the app, please add yourself to the end of the [credits](https://github.com/maxgoedjen/secretive/blob/main/Secretive/Credits.rtf).
|
||||||
|
|
||||||
|
## Collaborator Status
|
||||||
|
|
||||||
|
I will not grant collaborator access to any contributors for this repository. This is basically just because collaborators [can accesss the secrets Secretive uses for the signing credentials stored in the repository](https://docs.github.com/en/actions/reference/encrypted-secrets#accessing-your-secrets).
|
||||||
|
|
||||||
|
## Secretive is Opinionated
|
||||||
|
|
||||||
|
I'm releasing Secretive as open source so that other people can use it and audit it, feeling comfortable in knowing that the source is available so they can see what it's doing. I have a pretty strong idea of what I'd like this project to look like, and I may respectfully decline contributions that don't line up with that vision. If you'd like to propose a change before implementing, please feel free to [Open an Issue with the proposed tag](https://github.com/maxgoedjen/secretive/issues/new?labels=proposed).
|
3
DESIGN.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# Design
|
||||||
|
|
||||||
|
The art assets for the App Icon and GitHub image are located on [Sketch Cloud](https://www.sketch.com/s/574333cd-8ceb-40e1-a6d9-189da3f1e5dd).
|
57
FAQ.md
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
# FAQ
|
||||||
|
|
||||||
|
### How do I import my current SSH keys, or export my Secretive Keys?
|
||||||
|
|
||||||
|
The secure enclave doesn't allow import or export of private keys. For any new computer, you should just create a new set of keys. If you're using a smart card, you _might_ be able to export your private key from the vendor's software.
|
||||||
|
|
||||||
|
### Secretive doesn't work with my git client/app
|
||||||
|
|
||||||
|
Secretive relies on the `SSH_AUTH_SOCK` environment variable being respected. The `git` and `ssh` command line tools natively respect this, but third party apps may require some configuration to work. A non-exhaustive list of setup steps is provided in the [App Config FAQ](APP_CONFIG.md).
|
||||||
|
|
||||||
|
### Secretive isn't working for me
|
||||||
|
|
||||||
|
Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [new GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) with a description of your issue.
|
||||||
|
|
||||||
|
### Secretive prompts me to type my password instead of using my Apple Watch
|
||||||
|
|
||||||
|
1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
2) Ensure that unlocking your Mac with Apple Watch is working (lock and unlock at least once)
|
||||||
|
3) Now you should get prompted on the watch when your key is accessed. Double click the side button to approve:
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
### How do I tell SSH to use a specific key?
|
||||||
|
|
||||||
|
You can create a `mykey.pub` (where `mykey` is the name of your key) in your `~/.ssh/` directory with the contents of your public key, and specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up
|
||||||
|
|
||||||
|
### Why should I trust you?
|
||||||
|
|
||||||
|
You shouldn't, for a piece of software like this. Secretive, by design, has an auditable build process. Each build has a fully auditable build log, showing the source it was built from and a SHA of the build product. You can check the SHA of the zip you download against the SHA output in the build log (which is linked in the About window).
|
||||||
|
|
||||||
|
### I want to build Secretive from source
|
||||||
|
|
||||||
|
Awesome! Just bear in mind that because an app only has access to the keychain items that it created, if you have secrets that you created with the prebuilt version of Secretive, you'll be unable to access them using your own custom build (since you'll have changed the bundled ID).
|
||||||
|
|
||||||
|
### What's this network request to GitHub?
|
||||||
|
|
||||||
|
Secretive checks in with GitHub's releases API to check if there's a new version of Secretive available. You can audit the source code for this feature [here](https://github.com/maxgoedjen/secretive/blob/main/Sources/Packages/Sources/Brief/Updater.swift).
|
||||||
|
|
||||||
|
### How do I uninstall Secretive?
|
||||||
|
|
||||||
|
Drag Secretive.app to the trash and remove `~/Library/Containers/com.maxgoedjen.Secretive.SecretAgent`. `SecretAgent` may continue running until you quit it or reboot.
|
||||||
|
|
||||||
|
### I have a security issue
|
||||||
|
|
||||||
|
Please contact [max.goedjen@gmail.com](mailto:max.goedjen@gmail.com) with a subject containing "SECRETIVE SECURITY" immediately with details, and I'll address the issue and credit you ASAP.
|
||||||
|
|
||||||
|
### I have a non-security related bug
|
||||||
|
|
||||||
|
Please file a [GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) for it. I will not provide email support with the exception of the critical security issues mentioned above.
|
||||||
|
|
||||||
|
### I want to contribute to Secretive
|
||||||
|
|
||||||
|
Sweet! Please check out the [contributing guidelines](CONTRIBUTING.md) and go from there.
|
32
README.md
@ -1,9 +1,11 @@
|
|||||||
# Secretive
|
# Secretive  
|
||||||
|
|
||||||
|
|
||||||
Secretive is an app for storing and managing SSH keys in the Secure Enclave. It is inspired by the [sekey project](https://github.com/sekey/sekey), but rewritten in Swift with no external dependencies and with a handy native management app.
|
Secretive is an app for storing and managing SSH keys in the Secure Enclave. It is inspired by the [sekey project](https://github.com/sekey/sekey), but rewritten in Swift with no external dependencies and with a handy native management app.
|
||||||
|
|
||||||
<img src="/.github/readme/app.png" alt="Screenshot of Secretive" width="600">
|
<img src="/.github/readme/app.png" alt="Screenshot of Secretive" width="600">
|
||||||
|
|
||||||
|
|
||||||
## Why?
|
## Why?
|
||||||
|
|
||||||
### Safer Storage
|
### Safer Storage
|
||||||
@ -12,13 +14,13 @@ The most common setup for SSH keys is just keeping them on disk, guarded by prop
|
|||||||
|
|
||||||
### Access Control
|
### Access Control
|
||||||
|
|
||||||
If your Mac has a Secure Enclave, it also has support for strong biometric access controls like Touch ID. You can configure your key so that they require Touch ID (or Watch) authentication before they're accessed.
|
If your Mac has a Secure Enclave, it also has support for strong access controls like Touch ID, or authentication with Apple Watch. You can configure your key so that they require Touch ID (or Watch) authentication before they're accessed.
|
||||||
|
|
||||||
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID">
|
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID">
|
||||||
|
|
||||||
### Notifications
|
### Notifications
|
||||||
|
|
||||||
Secretive also notifies you whenever your keys are acceessed, so you're never caught off guard.
|
Secretive also notifies you whenever your keys are accessed, so you're never caught off guard.
|
||||||
|
|
||||||
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user">
|
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user">
|
||||||
|
|
||||||
@ -28,17 +30,23 @@ For Macs without Secure Enclaves, you can configure a Smart Card (such as a Yubi
|
|||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
### Setup for Third Party Apps
|
### Installation
|
||||||
|
|
||||||
When you first launch Secretive, you'll be prompted to set up your command line environment. You can redisplay this prompt at any time by going to `Menu > Help -> Set Up Helper App`.
|
#### Direct Download
|
||||||
For non-command-line based apps, like GUI Git clients, you may need to go through app-specific setup.
|
|
||||||
|
|
||||||
[Tower](https://www.git-tower.com/help/mac/integration/environment)
|
You can download the latest release over on the [Releases Page](https://github.com/maxgoedjen/secretive/releases)
|
||||||
|
|
||||||
|
#### Using Homebrew
|
||||||
|
|
||||||
### Security Considerations
|
brew install secretive
|
||||||
|
|
||||||
For the moment, you must build Secretive from source. For an app like this, it's critical that you trust that the app you're running is the app whose source you've checked out. To this end, Secretive has no third party dependecies, and is designed to be easy for you to audit for exploits.
|
### FAQ
|
||||||
|
|
||||||
|
There's a [FAQ here](FAQ.md).
|
||||||
|
|
||||||
|
### Auditable Build Process
|
||||||
|
|
||||||
|
Builds are produced by GitHub Actions with an auditable build and release generation process. Each build has a "Document SHAs" step, which will output SHA checksums for the build produced by the GitHub Action, so you can verify that the source code for a given build corresponds to any given release.
|
||||||
|
|
||||||
### A Note Around Code Signing and Keychains
|
### A Note Around Code Signing and Keychains
|
||||||
|
|
||||||
@ -46,4 +54,8 @@ While Secretive uses the Secure Enclave for key storage, it still relies on Keyc
|
|||||||
|
|
||||||
### Backups and Transfers to New Machines
|
### Backups and Transfers to New Machines
|
||||||
|
|
||||||
Beacuse secrets in the Secure Enclave are not exportable, they are not able to be backed up, and you will not be able to transfer them to a new machine. If you get a new Mac, just create a new set of secrets specific to that Mac.
|
Because secrets in the Secure Enclave are not exportable, they are not able to be backed up, and you will not be able to transfer them to a new machine. If you get a new Mac, just create a new set of secrets specific to that Mac.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
If you discover any vulnerabilities in this project, please notify [max.goedjen@gmail.com](mailto:max.goedjen@gmail.com) with the subject containing "SECRETIVE SECURITY."
|
||||||
|
9
SECURITY.md
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Security Policy
|
||||||
|
|
||||||
|
## Supported Versions
|
||||||
|
|
||||||
|
The latest version on the [Releases page](https://github.com/maxgoedjen/secretive/releases) is the only currently supported version.
|
||||||
|
|
||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
If you discover any vulnerabilities in this project, please notify max.goedjen@gmail.com with the subject containing "SECRETIVE SECURITY."
|
@ -1,150 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import CryptoKit
|
|
||||||
import OSLog
|
|
||||||
import SecretKit
|
|
||||||
import SecretAgentKit
|
|
||||||
|
|
||||||
class Agent {
|
|
||||||
|
|
||||||
fileprivate let storeList: SecretStoreList
|
|
||||||
fileprivate let notifier: Notifier
|
|
||||||
|
|
||||||
public init(storeList: SecretStoreList, notifier: Notifier) {
|
|
||||||
os_log(.debug, "Agent is running")
|
|
||||||
self.storeList = storeList
|
|
||||||
self.notifier = notifier
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Agent {
|
|
||||||
|
|
||||||
func handle(fileHandle: FileHandle) {
|
|
||||||
os_log(.debug, "Agent handling new data")
|
|
||||||
let data = fileHandle.availableData
|
|
||||||
guard !data.isEmpty else { return }
|
|
||||||
let requestTypeInt = data[4]
|
|
||||||
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else { return }
|
|
||||||
os_log(.debug, "Agent handling request of type %@", requestType.debugDescription)
|
|
||||||
let subData = Data(data[5...])
|
|
||||||
handle(requestType: requestType, data: subData, fileHandle: fileHandle)
|
|
||||||
}
|
|
||||||
|
|
||||||
func handle(requestType: SSHAgent.RequestType, data: Data, fileHandle: FileHandle) {
|
|
||||||
var response = Data()
|
|
||||||
do {
|
|
||||||
switch requestType {
|
|
||||||
case .requestIdentities:
|
|
||||||
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
|
|
||||||
response.append(try identities())
|
|
||||||
os_log(.debug, "Agent returned %@", SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)
|
|
||||||
case .signRequest:
|
|
||||||
response.append(SSHAgent.ResponseType.agentSignResponse.data)
|
|
||||||
response.append(try sign(data: data))
|
|
||||||
os_log(.debug, "Agent returned %@", SSHAgent.ResponseType.agentSignResponse.debugDescription)
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
response.removeAll()
|
|
||||||
response.append(SSHAgent.ResponseType.agentFailure.data)
|
|
||||||
os_log(.debug, "Agent returned %@", SSHAgent.ResponseType.agentFailure.debugDescription)
|
|
||||||
}
|
|
||||||
let full = OpenSSHKeyWriter().lengthAndData(of: response)
|
|
||||||
fileHandle.write(full)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Agent {
|
|
||||||
|
|
||||||
func identities() throws -> Data {
|
|
||||||
// TODO: RESTORE ONCE XCODE 11.4 IS GM
|
|
||||||
let secrets = storeList.stores.flatMap { $0.secrets }
|
|
||||||
// let secrets = storeList.stores.flatMap(\.secrets)
|
|
||||||
var count = UInt32(secrets.count).bigEndian
|
|
||||||
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
|
||||||
var keyData = Data()
|
|
||||||
let writer = OpenSSHKeyWriter()
|
|
||||||
for secret in secrets {
|
|
||||||
let keyBlob = writer.data(secret: secret)
|
|
||||||
keyData.append(writer.lengthAndData(of: keyBlob))
|
|
||||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
|
||||||
keyData.append(writer.lengthAndData(of: curveData))
|
|
||||||
}
|
|
||||||
os_log(.debug, "Agent enumerated %@ identities", secrets.count as NSNumber)
|
|
||||||
return countData + keyData
|
|
||||||
}
|
|
||||||
|
|
||||||
func sign(data: Data) throws -> Data {
|
|
||||||
let reader = OpenSSHReader(data: data)
|
|
||||||
let writer = OpenSSHKeyWriter()
|
|
||||||
let hash = try reader.readNextChunk()
|
|
||||||
let matching = storeList.stores.compactMap { store -> (AnySecretStore, AnySecret)? in
|
|
||||||
let allMatching = store.secrets.filter { secret in
|
|
||||||
hash == writer.data(secret: secret)
|
|
||||||
}
|
|
||||||
if let matching = allMatching.first {
|
|
||||||
return (store, matching)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
guard let (store, secret) = matching.first else {
|
|
||||||
throw AgentError.noMatchingKey
|
|
||||||
}
|
|
||||||
let dataToSign = try reader.readNextChunk()
|
|
||||||
let derSignature = try store.sign(data: dataToSign, with: secret)
|
|
||||||
// TODO: Move this
|
|
||||||
notifier.notify(accessTo: secret)
|
|
||||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
|
||||||
|
|
||||||
// Convert from DER formatted rep to raw (r||s)
|
|
||||||
|
|
||||||
let rawRepresentation: Data
|
|
||||||
switch (secret.algorithm, secret.keySize) {
|
|
||||||
case (.ellipticCurve, 256):
|
|
||||||
rawRepresentation = try CryptoKit.P256.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
|
||||||
case (.ellipticCurve, 384):
|
|
||||||
rawRepresentation = try CryptoKit.P384.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
let rawLength = rawRepresentation.count/2
|
|
||||||
let r = rawRepresentation[0..<rawLength]
|
|
||||||
let s = rawRepresentation[rawLength...]
|
|
||||||
|
|
||||||
var signatureChunk = Data()
|
|
||||||
signatureChunk.append(writer.lengthAndData(of: r))
|
|
||||||
signatureChunk.append(writer.lengthAndData(of: s))
|
|
||||||
|
|
||||||
var signedData = Data()
|
|
||||||
var sub = Data()
|
|
||||||
sub.append(writer.lengthAndData(of: curveData))
|
|
||||||
sub.append(writer.lengthAndData(of: signatureChunk))
|
|
||||||
signedData.append(writer.lengthAndData(of: sub))
|
|
||||||
|
|
||||||
os_log(.debug, "Agent signed request")
|
|
||||||
|
|
||||||
return signedData
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
extension Agent {
|
|
||||||
|
|
||||||
enum AgentError: Error {
|
|
||||||
case unhandledType
|
|
||||||
case noMatchingKey
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SSHAgent.ResponseType {
|
|
||||||
|
|
||||||
var data: Data {
|
|
||||||
var raw = self.rawValue
|
|
||||||
return Data(bytes: &raw, count: UInt8.bitWidth/8)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,37 +0,0 @@
|
|||||||
import Cocoa
|
|
||||||
import SecretKit
|
|
||||||
import OSLog
|
|
||||||
|
|
||||||
@NSApplicationMain
|
|
||||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
|
||||||
|
|
||||||
let storeList: SecretStoreList = {
|
|
||||||
let list = SecretStoreList()
|
|
||||||
list.add(store: SecureEnclave.Store())
|
|
||||||
list.add(store: SmartCard.Store())
|
|
||||||
return list
|
|
||||||
}()
|
|
||||||
let notifier = Notifier()
|
|
||||||
lazy var agent: Agent = {
|
|
||||||
Agent(storeList: storeList, notifier: notifier)
|
|
||||||
}()
|
|
||||||
lazy var socketController: SocketController = {
|
|
||||||
let path = (NSHomeDirectory() as NSString).appendingPathComponent("socket.ssh") as String
|
|
||||||
return SocketController(path: path)
|
|
||||||
}()
|
|
||||||
|
|
||||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
|
||||||
os_log(.debug, "SecretAgent finished launching")
|
|
||||||
DispatchQueue.main.async {
|
|
||||||
self.socketController.handler = self.agent.handle(fileHandle:)
|
|
||||||
}
|
|
||||||
notifier.prompt()
|
|
||||||
}
|
|
||||||
|
|
||||||
func applicationWillTerminate(_ aNotification: Notification) {
|
|
||||||
// Insert code here to tear down your application
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
Before Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 66 KiB |
@ -1,22 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import SecretKit
|
|
||||||
import UserNotifications
|
|
||||||
|
|
||||||
class Notifier {
|
|
||||||
|
|
||||||
func prompt() {
|
|
||||||
let notificationCenter = UNUserNotificationCenter.current()
|
|
||||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func notify<SecretType: Secret>(accessTo secret: SecretType) {
|
|
||||||
let notificationCenter = UNUserNotificationCenter.current()
|
|
||||||
let notificationContent = UNMutableNotificationContent()
|
|
||||||
notificationContent.title = "Signed Request"
|
|
||||||
notificationContent.body = "\(secret.name) was used to sign a request."
|
|
||||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
|
||||||
notificationCenter.add(request, withCompletionHandler: nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,67 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import OSLog
|
|
||||||
|
|
||||||
class SocketController {
|
|
||||||
|
|
||||||
fileprivate var fileHandle: FileHandle?
|
|
||||||
fileprivate var port: SocketPort?
|
|
||||||
var handler: ((FileHandle) -> Void)?
|
|
||||||
|
|
||||||
init(path: String) {
|
|
||||||
os_log(.debug, "Socket controller setting up at %@", path)
|
|
||||||
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
|
||||||
os_log(.debug, "Socket controller removed existing socket")
|
|
||||||
}
|
|
||||||
let exists = FileManager.default.fileExists(atPath: path)
|
|
||||||
assert(!exists)
|
|
||||||
os_log(.debug, "Socket controller path is clear")
|
|
||||||
port = socketPort(at: path)
|
|
||||||
configureSocket(at: path)
|
|
||||||
os_log(.debug, "Socket listening at %@", path)
|
|
||||||
}
|
|
||||||
|
|
||||||
func configureSocket(at path: String) {
|
|
||||||
guard let port = port else { return }
|
|
||||||
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
|
||||||
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionAccept(notification:)), name: .NSFileHandleConnectionAccepted, object: nil)
|
|
||||||
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionDataAvailable(notification:)), name: .NSFileHandleDataAvailable, object: nil)
|
|
||||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
|
||||||
}
|
|
||||||
|
|
||||||
func socketPort(at path: String) -> SocketPort {
|
|
||||||
var addr = sockaddr_un()
|
|
||||||
addr.sun_family = sa_family_t(AF_UNIX)
|
|
||||||
|
|
||||||
var len: Int = 0
|
|
||||||
_ = withUnsafeMutablePointer(to: &addr.sun_path.0) { pointer in
|
|
||||||
path.withCString { cstring in
|
|
||||||
len = strlen(cstring)
|
|
||||||
strncpy(pointer, cstring, len)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addr.sun_len = UInt8(len+2)
|
|
||||||
|
|
||||||
var data: Data!
|
|
||||||
_ = withUnsafePointer(to: &addr) { pointer in
|
|
||||||
data = Data(bytes: pointer, count: MemoryLayout<sockaddr_un>.size)
|
|
||||||
}
|
|
||||||
|
|
||||||
return SocketPort(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc func handleConnectionAccept(notification: Notification) {
|
|
||||||
os_log(.debug, "Socket controller accepted connection")
|
|
||||||
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
|
||||||
handler?(new)
|
|
||||||
new.waitForDataInBackgroundAndNotify()
|
|
||||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc func handleConnectionDataAvailable(notification: Notification) {
|
|
||||||
os_log(.debug, "Socket controller has new data available")
|
|
||||||
guard let new = notification.object as? FileHandle else { return }
|
|
||||||
os_log(.debug, "Socket controller received new file handle")
|
|
||||||
handler?(new)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>CFBundleDevelopmentRegion</key>
|
|
||||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
|
||||||
<key>CFBundleExecutable</key>
|
|
||||||
<string>$(EXECUTABLE_NAME)</string>
|
|
||||||
<key>CFBundleIdentifier</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
|
||||||
<key>CFBundleInfoDictionaryVersion</key>
|
|
||||||
<string>6.0</string>
|
|
||||||
<key>CFBundleName</key>
|
|
||||||
<string>$(PRODUCT_NAME)</string>
|
|
||||||
<key>CFBundlePackageType</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
|
||||||
<key>CFBundleShortVersionString</key>
|
|
||||||
<string>1.0</string>
|
|
||||||
<key>CFBundleVersion</key>
|
|
||||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
|
||||||
<key>NSHumanReadableCopyright</key>
|
|
||||||
<string>Copyright © 2020 Max Goedjen. All rights reserved.</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,19 +0,0 @@
|
|||||||
//
|
|
||||||
// SecretAgentKit.h
|
|
||||||
// SecretAgentKit
|
|
||||||
//
|
|
||||||
// Created by Max Goedjen on 2/22/20.
|
|
||||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
|
||||||
//
|
|
||||||
|
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
//! Project version number for SecretAgentKit.
|
|
||||||
FOUNDATION_EXPORT double SecretAgentKitVersionNumber;
|
|
||||||
|
|
||||||
//! Project version string for SecretAgentKit.
|
|
||||||
FOUNDATION_EXPORT const unsigned char SecretAgentKitVersionString[];
|
|
||||||
|
|
||||||
// In this header, you should import all the public headers of your framework using statements like #import <SecretAgentKit/PublicHeader.h>
|
|
||||||
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
|||||||
//
|
|
||||||
// SecretAgentKitTests.swift
|
|
||||||
// SecretAgentKitTests
|
|
||||||
//
|
|
||||||
// Created by Max Goedjen on 2/22/20.
|
|
||||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
|
||||||
//
|
|
||||||
|
|
||||||
import XCTest
|
|
||||||
@testable import SecretAgentKit
|
|
||||||
|
|
||||||
class SecretAgentKitTests: XCTestCase {
|
|
||||||
|
|
||||||
override func setUpWithError() throws {
|
|
||||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
|
||||||
}
|
|
||||||
|
|
||||||
override func tearDownWithError() throws {
|
|
||||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
|
||||||
}
|
|
||||||
|
|
||||||
func testExample() throws {
|
|
||||||
// This is an example of a functional test case.
|
|
||||||
// Use XCTAssert and related functions to verify your tests produce the correct results.
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPerformanceExample() throws {
|
|
||||||
// This is an example of a performance test case.
|
|
||||||
self.measure {
|
|
||||||
// Put the code you want to measure the time of here.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,49 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import CryptoKit
|
|
||||||
|
|
||||||
// For the moment, only supports ecdsa-sha2-nistp256 and ecdsa-sha2-nistp386 keys
|
|
||||||
public struct OpenSSHKeyWriter {
|
|
||||||
|
|
||||||
public init() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public func data<SecretType: Secret>(secret: SecretType) -> Data {
|
|
||||||
lengthAndData(of: curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
|
||||||
lengthAndData(of: curveIdentifier(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
|
||||||
lengthAndData(of: secret.publicKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
public func openSSHString<SecretType: Secret>(secret: SecretType) -> String {
|
|
||||||
"\(curveType(for: secret.algorithm, length: secret.keySize)) \(data(secret: secret).base64EncodedString())"
|
|
||||||
}
|
|
||||||
|
|
||||||
public func openSSHFingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
|
||||||
Insecure.MD5.hash(data: data(secret: secret))
|
|
||||||
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
|
||||||
.joined(separator: ":")
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension OpenSSHKeyWriter {
|
|
||||||
|
|
||||||
public func lengthAndData(of data: Data) -> Data {
|
|
||||||
let rawLength = UInt32(data.count)
|
|
||||||
var endian = rawLength.bigEndian
|
|
||||||
return Data(bytes: &endian, count: UInt32.bitWidth/8) + data
|
|
||||||
}
|
|
||||||
|
|
||||||
public func curveIdentifier(for algorithm: Algorithm, length: Int) -> String {
|
|
||||||
switch algorithm {
|
|
||||||
case .ellipticCurve:
|
|
||||||
return "nistp" + String(describing: length)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public func curveType(for algorithm: Algorithm, length: Int) -> String {
|
|
||||||
switch algorithm {
|
|
||||||
case .ellipticCurve:
|
|
||||||
return "ecdsa-sha2-nistp" + String(describing: length)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>CFBundleDevelopmentRegion</key>
|
|
||||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
|
||||||
<key>CFBundleExecutable</key>
|
|
||||||
<string>$(EXECUTABLE_NAME)</string>
|
|
||||||
<key>CFBundleIdentifier</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
|
||||||
<key>CFBundleInfoDictionaryVersion</key>
|
|
||||||
<string>6.0</string>
|
|
||||||
<key>CFBundleName</key>
|
|
||||||
<string>$(PRODUCT_NAME)</string>
|
|
||||||
<key>CFBundlePackageType</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
|
||||||
<key>CFBundleShortVersionString</key>
|
|
||||||
<string>1.0</string>
|
|
||||||
<key>CFBundleVersion</key>
|
|
||||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
|
||||||
<key>NSHumanReadableCopyright</key>
|
|
||||||
<string>Copyright © 2020 Max Goedjen. All rights reserved.</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,21 +0,0 @@
|
|||||||
public protocol Secret: Identifiable, Hashable {
|
|
||||||
|
|
||||||
var name: String { get }
|
|
||||||
var algorithm: Algorithm { get }
|
|
||||||
var keySize: Int { get }
|
|
||||||
var publicKey: Data { get }
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum Algorithm {
|
|
||||||
case ellipticCurve
|
|
||||||
public init(secAttr: NSNumber) {
|
|
||||||
let secAttrString = secAttr.stringValue as CFString
|
|
||||||
switch secAttrString {
|
|
||||||
case kSecAttrKeyTypeEC:
|
|
||||||
self = .ellipticCurve
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,19 +0,0 @@
|
|||||||
//
|
|
||||||
// SecretKit.h
|
|
||||||
// SecretKit
|
|
||||||
//
|
|
||||||
// Created by Max Goedjen on 2/18/20.
|
|
||||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
|
||||||
//
|
|
||||||
|
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
//! Project version number for SecretKit.
|
|
||||||
FOUNDATION_EXPORT double SecretKitVersionNumber;
|
|
||||||
|
|
||||||
//! Project version string for SecretKit.
|
|
||||||
FOUNDATION_EXPORT const unsigned char SecretKitVersionString[];
|
|
||||||
|
|
||||||
// In this header, you should import all the public headers of your framework using statements like #import <SecretKit/PublicHeader.h>
|
|
||||||
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
|||||||
import Combine
|
|
||||||
|
|
||||||
public protocol SecretStore: ObservableObject, Identifiable {
|
|
||||||
|
|
||||||
associatedtype SecretType: Secret
|
|
||||||
|
|
||||||
var isAvailable: Bool { get }
|
|
||||||
var id: UUID { get }
|
|
||||||
var name: String { get }
|
|
||||||
var secrets: [SecretType] { get }
|
|
||||||
|
|
||||||
func sign(data: Data, with secret: SecretType) throws -> Data
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public protocol SecretStoreModifiable: SecretStore {
|
|
||||||
|
|
||||||
func create(name: String, requiresAuthentication: Bool) throws
|
|
||||||
func delete(secret: SecretType) throws
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension NSNotification.Name {
|
|
||||||
|
|
||||||
static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
|
|
||||||
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
public enum SecureEnclave {}
|
|
@ -1,185 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import Security
|
|
||||||
import CryptoTokenKit
|
|
||||||
|
|
||||||
extension SecureEnclave {
|
|
||||||
|
|
||||||
public class Store: SecretStoreModifiable {
|
|
||||||
|
|
||||||
public var isAvailable: Bool {
|
|
||||||
// For some reason, as of build time, CryptoKit.SecureEnclave.isAvailable always returns false
|
|
||||||
// error msg "Received error sending GET UNIQUE DEVICE command"
|
|
||||||
// Verify it with TKTokenWatcher manually.
|
|
||||||
TKTokenWatcher().tokenIDs.contains("com.apple.setoken")
|
|
||||||
}
|
|
||||||
public let id = UUID()
|
|
||||||
public let name = NSLocalizedString("Secure Enclave", comment: "Secure Enclave")
|
|
||||||
@Published public fileprivate(set) var secrets: [Secret] = []
|
|
||||||
|
|
||||||
public init() {
|
|
||||||
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
|
|
||||||
self.reloadSecrets(notify: false)
|
|
||||||
}
|
|
||||||
loadSecrets()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Public API
|
|
||||||
|
|
||||||
public func create(name: String, requiresAuthentication: Bool) throws {
|
|
||||||
var accessError: SecurityError?
|
|
||||||
let flags: SecAccessControlCreateFlags
|
|
||||||
if requiresAuthentication {
|
|
||||||
flags = [.privateKeyUsage, .userPresence]
|
|
||||||
} else {
|
|
||||||
flags = .privateKeyUsage
|
|
||||||
}
|
|
||||||
let access =
|
|
||||||
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
|
||||||
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
|
||||||
flags,
|
|
||||||
&accessError) as Any
|
|
||||||
if let error = accessError {
|
|
||||||
throw error.takeRetainedValue() as Error
|
|
||||||
}
|
|
||||||
|
|
||||||
let attributes = [
|
|
||||||
kSecAttrLabel: name,
|
|
||||||
kSecAttrKeyType: Constants.keyType,
|
|
||||||
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
|
||||||
kSecAttrApplicationTag: Constants.keyTag,
|
|
||||||
kSecPrivateKeyAttrs: [
|
|
||||||
kSecAttrIsPermanent: true,
|
|
||||||
kSecAttrAccessControl: access
|
|
||||||
]
|
|
||||||
] as CFDictionary
|
|
||||||
|
|
||||||
var privateKey: SecKey? = nil
|
|
||||||
var publicKey: SecKey? = nil
|
|
||||||
let status = SecKeyGeneratePair(attributes, &publicKey, &privateKey)
|
|
||||||
guard privateKey != nil, let pk = publicKey else {
|
|
||||||
throw KeychainError(statusCode: status)
|
|
||||||
}
|
|
||||||
try savePublicKey(pk, name: name)
|
|
||||||
reloadSecrets()
|
|
||||||
}
|
|
||||||
|
|
||||||
public func delete(secret: Secret) throws {
|
|
||||||
let deleteAttributes = [
|
|
||||||
kSecClass: kSecClassKey,
|
|
||||||
kSecAttrApplicationLabel: secret.id as CFData
|
|
||||||
] as CFDictionary
|
|
||||||
let status = SecItemDelete(deleteAttributes)
|
|
||||||
if status != errSecSuccess {
|
|
||||||
throw KeychainError(statusCode: status)
|
|
||||||
}
|
|
||||||
reloadSecrets()
|
|
||||||
}
|
|
||||||
|
|
||||||
public func sign(data: Data, with secret: SecretType) throws -> Data {
|
|
||||||
let attributes = [
|
|
||||||
kSecClass: kSecClassKey,
|
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
|
||||||
kSecAttrApplicationLabel: secret.id as CFData,
|
|
||||||
kSecAttrKeyType: Constants.keyType,
|
|
||||||
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
|
||||||
kSecAttrApplicationTag: Constants.keyTag,
|
|
||||||
kSecReturnRef: true
|
|
||||||
] as CFDictionary
|
|
||||||
var untyped: CFTypeRef?
|
|
||||||
let status = SecItemCopyMatching(attributes, &untyped)
|
|
||||||
if status != errSecSuccess {
|
|
||||||
throw KeychainError(statusCode: status)
|
|
||||||
}
|
|
||||||
guard let untypedSafe = untyped else {
|
|
||||||
throw KeychainError(statusCode: errSecSuccess)
|
|
||||||
}
|
|
||||||
let key = untypedSafe as! SecKey
|
|
||||||
var signError: SecurityError?
|
|
||||||
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
|
||||||
throw SigningError(error: signError)
|
|
||||||
}
|
|
||||||
return signature as Data
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave.Store {
|
|
||||||
|
|
||||||
fileprivate func reloadSecrets(notify: Bool = true) {
|
|
||||||
secrets.removeAll()
|
|
||||||
loadSecrets()
|
|
||||||
if notify {
|
|
||||||
DistributedNotificationCenter.default().post(name: .secretStoreUpdated, object: nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fileprivate func loadSecrets() {
|
|
||||||
let attributes = [
|
|
||||||
kSecClass: kSecClassKey,
|
|
||||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
|
||||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
|
||||||
kSecReturnRef: true,
|
|
||||||
kSecMatchLimit: kSecMatchLimitAll,
|
|
||||||
kSecReturnAttributes: true
|
|
||||||
] as CFDictionary
|
|
||||||
var untyped: CFTypeRef?
|
|
||||||
SecItemCopyMatching(attributes, &untyped)
|
|
||||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
|
||||||
let wrapped: [SecureEnclave.Secret] = typed.map {
|
|
||||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
|
||||||
let id = $0[kSecAttrApplicationLabel] as! Data
|
|
||||||
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
|
||||||
let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any]
|
|
||||||
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
|
||||||
return SecureEnclave.Secret(id: id, name: name, publicKey: publicKey)
|
|
||||||
}
|
|
||||||
secrets.append(contentsOf: wrapped)
|
|
||||||
}
|
|
||||||
|
|
||||||
fileprivate func savePublicKey(_ publicKey: SecKey, name: String) throws {
|
|
||||||
let attributes = [
|
|
||||||
kSecClass: kSecClassKey,
|
|
||||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
|
||||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
|
||||||
kSecValueRef: publicKey,
|
|
||||||
kSecAttrIsPermanent: true,
|
|
||||||
kSecReturnData: true,
|
|
||||||
kSecAttrLabel: name
|
|
||||||
] as CFDictionary
|
|
||||||
let status = SecItemAdd(attributes, nil)
|
|
||||||
if status != errSecSuccess {
|
|
||||||
throw SecureEnclave.KeychainError(statusCode: status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave {
|
|
||||||
|
|
||||||
public struct KeychainError: Error {
|
|
||||||
public let statusCode: OSStatus
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct SigningError: Error {
|
|
||||||
public let error: SecurityError?
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave {
|
|
||||||
|
|
||||||
public typealias SecurityError = Unmanaged<CFError>
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
fileprivate static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
|
|
||||||
fileprivate static let keyType = kSecAttrKeyTypeECSECPrimeRandom
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
public enum SmartCard {}
|
|
@ -1,22 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>CFBundleDevelopmentRegion</key>
|
|
||||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
|
||||||
<key>CFBundleExecutable</key>
|
|
||||||
<string>$(EXECUTABLE_NAME)</string>
|
|
||||||
<key>CFBundleIdentifier</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
|
||||||
<key>CFBundleInfoDictionaryVersion</key>
|
|
||||||
<string>6.0</string>
|
|
||||||
<key>CFBundleName</key>
|
|
||||||
<string>$(PRODUCT_NAME)</string>
|
|
||||||
<key>CFBundlePackageType</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
|
||||||
<key>CFBundleShortVersionString</key>
|
|
||||||
<string>1.0</string>
|
|
||||||
<key>CFBundleVersion</key>
|
|
||||||
<string>1</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,34 +0,0 @@
|
|||||||
//
|
|
||||||
// SecretKitTests.swift
|
|
||||||
// SecretKitTests
|
|
||||||
//
|
|
||||||
// Created by Max Goedjen on 2/18/20.
|
|
||||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
|
||||||
//
|
|
||||||
|
|
||||||
import XCTest
|
|
||||||
@testable import SecretKit
|
|
||||||
|
|
||||||
class SecretKitTests: XCTestCase {
|
|
||||||
|
|
||||||
override func setUp() {
|
|
||||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
|
||||||
}
|
|
||||||
|
|
||||||
override func tearDown() {
|
|
||||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
|
||||||
}
|
|
||||||
|
|
||||||
func testExample() {
|
|
||||||
// This is an example of a functional test case.
|
|
||||||
// Use XCTAssert and related functions to verify your tests produce the correct results.
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPerformanceExample() {
|
|
||||||
// This is an example of a performance test case.
|
|
||||||
self.measure {
|
|
||||||
// Put the code you want to measure the time of here.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,67 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Scheme
|
|
||||||
LastUpgradeVersion = "1140"
|
|
||||||
version = "1.3">
|
|
||||||
<BuildAction
|
|
||||||
parallelizeBuildables = "YES"
|
|
||||||
buildImplicitDependencies = "YES">
|
|
||||||
<BuildActionEntries>
|
|
||||||
<BuildActionEntry
|
|
||||||
buildForTesting = "YES"
|
|
||||||
buildForRunning = "YES"
|
|
||||||
buildForProfiling = "YES"
|
|
||||||
buildForArchiving = "YES"
|
|
||||||
buildForAnalyzing = "YES">
|
|
||||||
<BuildableReference
|
|
||||||
BuildableIdentifier = "primary"
|
|
||||||
BlueprintIdentifier = "5099A06B240242BA0062B6F2"
|
|
||||||
BuildableName = "SecretAgentKit.framework"
|
|
||||||
BlueprintName = "SecretAgentKit"
|
|
||||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
|
||||||
</BuildableReference>
|
|
||||||
</BuildActionEntry>
|
|
||||||
</BuildActionEntries>
|
|
||||||
</BuildAction>
|
|
||||||
<TestAction
|
|
||||||
buildConfiguration = "Debug"
|
|
||||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
|
||||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
|
||||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
|
||||||
<Testables>
|
|
||||||
</Testables>
|
|
||||||
</TestAction>
|
|
||||||
<LaunchAction
|
|
||||||
buildConfiguration = "Debug"
|
|
||||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
|
||||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
|
||||||
launchStyle = "0"
|
|
||||||
useCustomWorkingDirectory = "NO"
|
|
||||||
ignoresPersistentStateOnLaunch = "NO"
|
|
||||||
debugDocumentVersioning = "YES"
|
|
||||||
debugServiceExtension = "internal"
|
|
||||||
allowLocationSimulation = "YES">
|
|
||||||
</LaunchAction>
|
|
||||||
<ProfileAction
|
|
||||||
buildConfiguration = "Release"
|
|
||||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
|
||||||
savedToolIdentifier = ""
|
|
||||||
useCustomWorkingDirectory = "NO"
|
|
||||||
debugDocumentVersioning = "YES">
|
|
||||||
<MacroExpansion>
|
|
||||||
<BuildableReference
|
|
||||||
BuildableIdentifier = "primary"
|
|
||||||
BlueprintIdentifier = "5099A06B240242BA0062B6F2"
|
|
||||||
BuildableName = "SecretAgentKit.framework"
|
|
||||||
BlueprintName = "SecretAgentKit"
|
|
||||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
|
||||||
</BuildableReference>
|
|
||||||
</MacroExpansion>
|
|
||||||
</ProfileAction>
|
|
||||||
<AnalyzeAction
|
|
||||||
buildConfiguration = "Debug">
|
|
||||||
</AnalyzeAction>
|
|
||||||
<ArchiveAction
|
|
||||||
buildConfiguration = "Release"
|
|
||||||
revealArchiveInOrganizer = "YES">
|
|
||||||
</ArchiveAction>
|
|
||||||
</Scheme>
|
|
@ -1,67 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Scheme
|
|
||||||
LastUpgradeVersion = "1140"
|
|
||||||
version = "1.3">
|
|
||||||
<BuildAction
|
|
||||||
parallelizeBuildables = "YES"
|
|
||||||
buildImplicitDependencies = "YES">
|
|
||||||
<BuildActionEntries>
|
|
||||||
<BuildActionEntry
|
|
||||||
buildForTesting = "YES"
|
|
||||||
buildForRunning = "YES"
|
|
||||||
buildForProfiling = "YES"
|
|
||||||
buildForArchiving = "YES"
|
|
||||||
buildForAnalyzing = "YES">
|
|
||||||
<BuildableReference
|
|
||||||
BuildableIdentifier = "primary"
|
|
||||||
BlueprintIdentifier = "50617DA723FCE4AB0099B055"
|
|
||||||
BuildableName = "SecretKit.framework"
|
|
||||||
BlueprintName = "SecretKit"
|
|
||||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
|
||||||
</BuildableReference>
|
|
||||||
</BuildActionEntry>
|
|
||||||
</BuildActionEntries>
|
|
||||||
</BuildAction>
|
|
||||||
<TestAction
|
|
||||||
buildConfiguration = "Debug"
|
|
||||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
|
||||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
|
||||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
|
||||||
<Testables>
|
|
||||||
</Testables>
|
|
||||||
</TestAction>
|
|
||||||
<LaunchAction
|
|
||||||
buildConfiguration = "Debug"
|
|
||||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
|
||||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
|
||||||
launchStyle = "0"
|
|
||||||
useCustomWorkingDirectory = "NO"
|
|
||||||
ignoresPersistentStateOnLaunch = "NO"
|
|
||||||
debugDocumentVersioning = "YES"
|
|
||||||
debugServiceExtension = "internal"
|
|
||||||
allowLocationSimulation = "YES">
|
|
||||||
</LaunchAction>
|
|
||||||
<ProfileAction
|
|
||||||
buildConfiguration = "Release"
|
|
||||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
|
||||||
savedToolIdentifier = ""
|
|
||||||
useCustomWorkingDirectory = "NO"
|
|
||||||
debugDocumentVersioning = "YES">
|
|
||||||
<MacroExpansion>
|
|
||||||
<BuildableReference
|
|
||||||
BuildableIdentifier = "primary"
|
|
||||||
BlueprintIdentifier = "50617DA723FCE4AB0099B055"
|
|
||||||
BuildableName = "SecretKit.framework"
|
|
||||||
BlueprintName = "SecretKit"
|
|
||||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
|
||||||
</BuildableReference>
|
|
||||||
</MacroExpansion>
|
|
||||||
</ProfileAction>
|
|
||||||
<AnalyzeAction
|
|
||||||
buildConfiguration = "Debug">
|
|
||||||
</AnalyzeAction>
|
|
||||||
<ArchiveAction
|
|
||||||
buildConfiguration = "Release"
|
|
||||||
revealArchiveInOrganizer = "YES">
|
|
||||||
</ArchiveAction>
|
|
||||||
</Scheme>
|
|
@ -1,84 +0,0 @@
|
|||||||
import Cocoa
|
|
||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
@NSApplicationMain
|
|
||||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
|
||||||
|
|
||||||
var window: NSWindow!
|
|
||||||
@IBOutlet var toolbar: NSToolbar!
|
|
||||||
let storeList: SecretStoreList = {
|
|
||||||
let list = SecretStoreList()
|
|
||||||
list.add(store: SecureEnclave.Store())
|
|
||||||
list.add(store: SmartCard.Store())
|
|
||||||
return list
|
|
||||||
}()
|
|
||||||
|
|
||||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
|
||||||
|
|
||||||
let contentView = ContentView(storeList: storeList)
|
|
||||||
// Create the window and set the content view.
|
|
||||||
window = NSWindow(
|
|
||||||
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
|
|
||||||
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
|
|
||||||
backing: .buffered, defer: false)
|
|
||||||
window.center()
|
|
||||||
window.setFrameAutosaveName("Main Window")
|
|
||||||
window.contentView = NSHostingView(rootView: contentView)
|
|
||||||
window.makeKeyAndOrderFront(nil)
|
|
||||||
window.titleVisibility = .hidden
|
|
||||||
window.toolbar = toolbar
|
|
||||||
if storeList.modifiableStore?.isAvailable ?? false {
|
|
||||||
let plus = NSTitlebarAccessoryViewController()
|
|
||||||
plus.view = NSButton(image: NSImage(named: NSImage.addTemplateName)!, target: self, action: #selector(add(sender:)))
|
|
||||||
plus.layoutAttribute = .right
|
|
||||||
window.addTitlebarAccessoryViewController(plus)
|
|
||||||
}
|
|
||||||
runSetupIfNeeded()
|
|
||||||
}
|
|
||||||
|
|
||||||
@IBAction func add(sender: AnyObject?) {
|
|
||||||
var addWindow: NSWindow!
|
|
||||||
let addView = CreateSecretView(store: storeList.modifiableStore!) {
|
|
||||||
self.window.endSheet(addWindow)
|
|
||||||
}
|
|
||||||
addWindow = NSWindow(
|
|
||||||
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
|
|
||||||
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
|
|
||||||
backing: .buffered, defer: false)
|
|
||||||
addWindow.contentView = NSHostingView(rootView: addView)
|
|
||||||
window.beginSheet(addWindow, completionHandler: nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@IBAction func runSetup(sender: AnyObject?) {
|
|
||||||
let setupWindow = NSWindow(
|
|
||||||
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
|
|
||||||
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
|
|
||||||
backing: .buffered, defer: false)
|
|
||||||
let setupView = SetupView() { success in
|
|
||||||
self.window.endSheet(setupWindow)
|
|
||||||
}
|
|
||||||
setupWindow.contentView = NSHostingView(rootView: setupView)
|
|
||||||
window.beginSheet(setupWindow, completionHandler: nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AppDelegate {
|
|
||||||
|
|
||||||
func runSetupIfNeeded() {
|
|
||||||
if !UserDefaults.standard.bool(forKey: Constants.defaultsHasRunSetup) {
|
|
||||||
UserDefaults.standard.set(true, forKey: Constants.defaultsHasRunSetup)
|
|
||||||
runSetup(sender: nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AppDelegate {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let defaultsHasRunSetup = "defaultsHasRunSetup"
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
Before Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 66 KiB |
@ -1,159 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="15702" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
|
|
||||||
<dependencies>
|
|
||||||
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15702"/>
|
|
||||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
|
||||||
</dependencies>
|
|
||||||
<scenes>
|
|
||||||
<!--Application-->
|
|
||||||
<scene sceneID="JPo-4y-FX3">
|
|
||||||
<objects>
|
|
||||||
<application id="hnw-xV-0zn" sceneMemberID="viewController">
|
|
||||||
<menu key="mainMenu" title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
|
|
||||||
<items>
|
|
||||||
<menuItem title="Secretive" id="1Xt-HY-uBw">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<menu key="submenu" title="Secretive" systemMenu="apple" id="uQy-DD-JDr">
|
|
||||||
<items>
|
|
||||||
<menuItem title="About Secretive" id="5kV-Vb-QxS">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<connections>
|
|
||||||
<action selector="orderFrontStandardAboutPanel:" target="Ady-hI-5gd" id="Exp-CZ-Vem"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
|
|
||||||
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
|
|
||||||
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
|
|
||||||
<menuItem title="Services" id="NMo-om-nkz">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
|
|
||||||
<menuItem title="Hide Secretive" keyEquivalent="h" id="Olw-nP-bQN">
|
|
||||||
<connections>
|
|
||||||
<action selector="hide:" target="Ady-hI-5gd" id="PnN-Uc-m68"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
|
|
||||||
<connections>
|
|
||||||
<action selector="hideOtherApplications:" target="Ady-hI-5gd" id="VT4-aY-XCT"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem title="Show All" id="Kd2-mp-pUS">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<connections>
|
|
||||||
<action selector="unhideAllApplications:" target="Ady-hI-5gd" id="Dhg-Le-xox"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
|
|
||||||
<menuItem title="Quit Secretive" keyEquivalent="q" id="4sb-4s-VLi">
|
|
||||||
<connections>
|
|
||||||
<action selector="terminate:" target="Ady-hI-5gd" id="Te7-pn-YzF"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
</items>
|
|
||||||
</menu>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem title="File" id="dMs-cI-mzQ">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<menu key="submenu" title="File" id="bib-Uj-vzu">
|
|
||||||
<items>
|
|
||||||
<menuItem title="New" keyEquivalent="n" id="Was-JA-tGl">
|
|
||||||
<connections>
|
|
||||||
<action selector="addWithSender:" target="Voe-Tx-rLC" id="U1t-YZ-Hn5"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem isSeparatorItem="YES" id="m54-Is-iLE"/>
|
|
||||||
<menuItem title="Close" keyEquivalent="w" id="DVo-aG-piG">
|
|
||||||
<connections>
|
|
||||||
<action selector="performClose:" target="Ady-hI-5gd" id="HmO-Ls-i7Q"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
</items>
|
|
||||||
</menu>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem title="Window" id="aUF-d1-5bR">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
|
|
||||||
<items>
|
|
||||||
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
|
|
||||||
<connections>
|
|
||||||
<action selector="performMiniaturize:" target="Ady-hI-5gd" id="VwT-WD-YPe"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem title="Zoom" id="R4o-n2-Eq4">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<connections>
|
|
||||||
<action selector="performZoom:" target="Ady-hI-5gd" id="DIl-cC-cCs"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
|
|
||||||
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<connections>
|
|
||||||
<action selector="arrangeInFront:" target="Ady-hI-5gd" id="DRN-fu-gQh"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
</items>
|
|
||||||
</menu>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem title="Help" id="wpr-3q-Mcd">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ">
|
|
||||||
<items>
|
|
||||||
<menuItem title="Set Up Helper App" id="04y-R6-7bF">
|
|
||||||
<modifierMask key="keyEquivalentModifierMask"/>
|
|
||||||
<connections>
|
|
||||||
<action selector="runSetupWithSender:" target="Voe-Tx-rLC" id="Fty-2m-eng"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
<menuItem isSeparatorItem="YES" id="Ddf-5M-Bmf"/>
|
|
||||||
<menuItem title="Secretive Help" keyEquivalent="?" id="FKE-Sm-Kum">
|
|
||||||
<connections>
|
|
||||||
<action selector="showHelp:" target="Ady-hI-5gd" id="y7X-2Q-9no"/>
|
|
||||||
</connections>
|
|
||||||
</menuItem>
|
|
||||||
</items>
|
|
||||||
</menu>
|
|
||||||
</menuItem>
|
|
||||||
</items>
|
|
||||||
</menu>
|
|
||||||
<connections>
|
|
||||||
<outlet property="delegate" destination="Voe-Tx-rLC" id="PrD-fu-P6m"/>
|
|
||||||
</connections>
|
|
||||||
</application>
|
|
||||||
<customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="Secretive" customModuleProvider="target">
|
|
||||||
<connections>
|
|
||||||
<outlet property="toolbar" destination="bvo-mt-QR4" id="XSF-g2-znt"/>
|
|
||||||
</connections>
|
|
||||||
</customObject>
|
|
||||||
<toolbar implicitIdentifier="09D11707-F4A3-4FD5-970E-AC5832E91C2B" autosavesConfiguration="NO" displayMode="iconAndLabel" sizeMode="regular" id="bvo-mt-QR4">
|
|
||||||
<allowedToolbarItems>
|
|
||||||
<toolbarItem implicitItemIdentifier="NSToolbarFlexibleSpaceItem" id="9Xm-OQ-a7h"/>
|
|
||||||
<toolbarItem implicitItemIdentifier="728E7E6E-F692-41A1-9439-C6EF9BE96CBA" label="Secretive" paletteLabel="" sizingBehavior="auto" id="xbD-W8-Ypr">
|
|
||||||
<nil key="toolTip"/>
|
|
||||||
<textField key="view" horizontalHuggingPriority="251" verticalHuggingPriority="750" id="Mg0-Hm-7bW">
|
|
||||||
<rect key="frame" x="0.0" y="14" width="65" height="16"/>
|
|
||||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
|
|
||||||
<textFieldCell key="cell" lineBreakMode="clipping" title="Secretive" id="EXw-BM-zF7">
|
|
||||||
<font key="font" usesAppearanceFont="YES"/>
|
|
||||||
<color key="textColor" name="windowFrameTextColor" catalog="System" colorSpace="catalog"/>
|
|
||||||
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
|
|
||||||
</textFieldCell>
|
|
||||||
</textField>
|
|
||||||
</toolbarItem>
|
|
||||||
</allowedToolbarItems>
|
|
||||||
<defaultToolbarItems>
|
|
||||||
<toolbarItem reference="9Xm-OQ-a7h"/>
|
|
||||||
<toolbarItem reference="xbD-W8-Ypr"/>
|
|
||||||
<toolbarItem reference="9Xm-OQ-a7h"/>
|
|
||||||
</defaultToolbarItems>
|
|
||||||
</toolbar>
|
|
||||||
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
|
|
||||||
<customObject id="Ady-hI-5gd" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/>
|
|
||||||
</objects>
|
|
||||||
<point key="canvasLocation" x="75" y="0.0"/>
|
|
||||||
</scene>
|
|
||||||
</scenes>
|
|
||||||
</document>
|
|
@ -1,97 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
struct ContentView: View {
|
|
||||||
|
|
||||||
@ObservedObject var storeList: SecretStoreList
|
|
||||||
|
|
||||||
@State fileprivate var active: AnySecret.ID?
|
|
||||||
@State fileprivate var showingDeletion = false
|
|
||||||
@State fileprivate var deletingSecret: AnySecret?
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
NavigationView {
|
|
||||||
List(selection: $active) {
|
|
||||||
ForEach(storeList.stores) { store in
|
|
||||||
if store.isAvailable {
|
|
||||||
Section(header: Text(store.name)) {
|
|
||||||
if store.secrets.isEmpty {
|
|
||||||
if store is AnySecretStoreModifiable {
|
|
||||||
NavigationLink(destination: EmptyStoreModifiableView(), tag: Constants.emptyStoreModifiableTag, selection: self.$active) {
|
|
||||||
Text("No Secrets")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
NavigationLink(destination: EmptyStoreView(), tag: Constants.emptyStoreTag, selection: self.$active) {
|
|
||||||
Text("No Secrets")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ForEach(store.secrets) { secret in
|
|
||||||
NavigationLink(destination: SecretDetailView(secret: secret), tag: secret.id, selection: self.$active) {
|
|
||||||
Text(secret.name)
|
|
||||||
}.contextMenu {
|
|
||||||
if store is AnySecretStoreModifiable {
|
|
||||||
Button(action: { self.delete(secret: secret) }) {
|
|
||||||
Text("Delete")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}.onAppear {
|
|
||||||
let fallback: AnyHashable
|
|
||||||
if self.storeList.modifiableStore?.isAvailable ?? false {
|
|
||||||
fallback = Constants.emptyStoreModifiableTag
|
|
||||||
} else {
|
|
||||||
fallback = Constants.emptyStoreTag
|
|
||||||
}
|
|
||||||
self.active = self.storeList.stores.compactMap { $0.secrets.first }.first?.id ?? fallback
|
|
||||||
}
|
|
||||||
.listStyle(SidebarListStyle())
|
|
||||||
.frame(minWidth: 100, idealWidth: 240)
|
|
||||||
}
|
|
||||||
.navigationViewStyle(DoubleColumnNavigationViewStyle())
|
|
||||||
.sheet(isPresented: $showingDeletion) {
|
|
||||||
if self.storeList.modifiableStore != nil {
|
|
||||||
DeleteSecretView(secret: self.deletingSecret!, store: self.storeList.modifiableStore!) {
|
|
||||||
self.showingDeletion = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
func delete<SecretType: Secret>(secret: SecretType) {
|
|
||||||
deletingSecret = AnySecret(secret)
|
|
||||||
self.showingDeletion = true
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension ContentView {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let emptyStoreModifiableTag: AnyHashable = "emptyStoreModifiableTag"
|
|
||||||
static let emptyStoreTag: AnyHashable = "emptyStoreModifiableTag"
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
#if DEBUG
|
|
||||||
|
|
||||||
struct ContentView_Previews: PreviewProvider {
|
|
||||||
static var previews: some View {
|
|
||||||
Group {
|
|
||||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]))
|
|
||||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store()], modifiableStores: [Preview.StoreModifiable()]))
|
|
||||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store()]))
|
|
||||||
ContentView(storeList: Preview.storeList(modifiableStores: [Preview.StoreModifiable()]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
@ -1,54 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
struct CreateSecretView: View {
|
|
||||||
|
|
||||||
@ObservedObject var store: AnySecretStoreModifiable
|
|
||||||
|
|
||||||
@State var name = ""
|
|
||||||
@State var requiresAuthentication = true
|
|
||||||
|
|
||||||
var dismissalBlock: () -> ()
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
VStack {
|
|
||||||
HStack {
|
|
||||||
Image(nsImage: NSApp.applicationIconImage)
|
|
||||||
.resizable()
|
|
||||||
.frame(width: 64, height: 64)
|
|
||||||
.padding()
|
|
||||||
VStack {
|
|
||||||
HStack {
|
|
||||||
Text("Create a New Secret").bold()
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
HStack {
|
|
||||||
Text("Name:")
|
|
||||||
TextField("Shhhhh", text: $name)
|
|
||||||
}
|
|
||||||
HStack {
|
|
||||||
Toggle(isOn: $requiresAuthentication) {
|
|
||||||
Text("Requires Authentication (Biometrics or Password)")
|
|
||||||
}
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.onExitCommand(perform: dismissalBlock)
|
|
||||||
}
|
|
||||||
HStack {
|
|
||||||
Spacer()
|
|
||||||
Button(action: dismissalBlock) {
|
|
||||||
Text("Cancel")
|
|
||||||
}
|
|
||||||
Button(action: save) {
|
|
||||||
Text("Create")
|
|
||||||
}.disabled(name.isEmpty)
|
|
||||||
}
|
|
||||||
}.padding()
|
|
||||||
}
|
|
||||||
|
|
||||||
func save() {
|
|
||||||
try! store.create(name: name, requiresAuthentication: requiresAuthentication)
|
|
||||||
dismissalBlock()
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,67 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
struct SecretDetailView<SecretType: Secret>: View {
|
|
||||||
|
|
||||||
@State var secret: SecretType
|
|
||||||
let keyWriter = OpenSSHKeyWriter()
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Form {
|
|
||||||
Section {
|
|
||||||
GroupBox(label: Text("Fingerprint")) {
|
|
||||||
HStack {
|
|
||||||
Text(keyWriter.openSSHFingerprint(secret: secret))
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
.frame(minWidth: 150, maxWidth: .infinity)
|
|
||||||
.padding()
|
|
||||||
}.onDrag {
|
|
||||||
return NSItemProvider(item: NSData(data: self.keyWriter.openSSHFingerprint(secret: self.secret).data(using: .utf8)!), typeIdentifier: kUTTypeUTF8PlainText as String)
|
|
||||||
}
|
|
||||||
Spacer().frame(height: 10)
|
|
||||||
GroupBox(label: Text("Public Key")) {
|
|
||||||
VStack {
|
|
||||||
Text(keyWriter.openSSHString(secret: secret))
|
|
||||||
.multilineTextAlignment(.leading)
|
|
||||||
.frame(minWidth: 150, maxWidth: .infinity)
|
|
||||||
HStack {
|
|
||||||
Spacer()
|
|
||||||
Button(action: copy) {
|
|
||||||
Text("Copy")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
}
|
|
||||||
.onDrag {
|
|
||||||
return NSItemProvider(item: NSData(data: self.keyString.data(using: .utf8)!), typeIdentifier: kUTTypeUTF8PlainText as String)
|
|
||||||
}
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
}.padding()
|
|
||||||
.frame(minHeight: 150, maxHeight: .infinity)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
var keyString: String {
|
|
||||||
keyWriter.openSSHString(secret: secret)
|
|
||||||
}
|
|
||||||
|
|
||||||
func copy() {
|
|
||||||
NSPasteboard.general.declareTypes([.string], owner: nil)
|
|
||||||
NSPasteboard.general.setString(keyString, forType: .string)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
#if DEBUG
|
|
||||||
|
|
||||||
struct SecretDetailView_Previews: PreviewProvider {
|
|
||||||
static var previews: some View {
|
|
||||||
SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
@ -1,133 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import SwiftUI
|
|
||||||
import ServiceManagement
|
|
||||||
|
|
||||||
struct SetupView: View {
|
|
||||||
|
|
||||||
var completion: ((Bool) -> Void)?
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Form {
|
|
||||||
SetupStepView<Spacer>(text: "Secretive needs to install a helper app to sign requests when the main app isn't running. This app is called \"SecretAgent\" and you might see it in Activity Manager from time to time.",
|
|
||||||
index: 1,
|
|
||||||
nestedView: nil,
|
|
||||||
actionText: "Install") {
|
|
||||||
self.installLaunchAgent()
|
|
||||||
}
|
|
||||||
SetupStepView(text: "You need to add a line to your shell config (.bashrc or .zshrc) telling SSH to talk to SecretAgent when it wants to authenticate. Drag this into your config file.",
|
|
||||||
index: 2,
|
|
||||||
nestedView: SetupStepCommandView(text: Constants.socketPrompt),
|
|
||||||
actionText: "Added") {
|
|
||||||
self.markAsDone()
|
|
||||||
}
|
|
||||||
HStack {
|
|
||||||
Spacer()
|
|
||||||
Button(action: { self.completion?(true) }) {
|
|
||||||
Text("Finish")
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SetupStepView<NestedViewType: View>: View {
|
|
||||||
|
|
||||||
let text: String
|
|
||||||
let index: Int
|
|
||||||
let nestedView: NestedViewType?
|
|
||||||
@State var completed = false
|
|
||||||
let actionText: String
|
|
||||||
let action: (() -> Bool)
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Section {
|
|
||||||
HStack {
|
|
||||||
ZStack {
|
|
||||||
if completed {
|
|
||||||
Circle().foregroundColor(.green)
|
|
||||||
.frame(width: 30, height: 30)
|
|
||||||
Text("✓")
|
|
||||||
.foregroundColor(.white)
|
|
||||||
.bold()
|
|
||||||
} else {
|
|
||||||
Circle().foregroundColor(.blue)
|
|
||||||
.frame(width: 30, height: 30)
|
|
||||||
Text(String(describing: index))
|
|
||||||
.foregroundColor(.white)
|
|
||||||
.bold()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
VStack {
|
|
||||||
Text(text)
|
|
||||||
.opacity(completed ? 0.5 : 1)
|
|
||||||
.lineLimit(nil)
|
|
||||||
.frame(idealHeight: 0, maxHeight: .infinity)
|
|
||||||
if nestedView != nil {
|
|
||||||
Spacer()
|
|
||||||
nestedView!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
Button(action: {
|
|
||||||
self.completed = self.action()
|
|
||||||
}) {
|
|
||||||
Text(actionText)
|
|
||||||
}.disabled(completed)
|
|
||||||
.padding()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SetupStepCommandView: View {
|
|
||||||
|
|
||||||
let text: String
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Text(text)
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.lineLimit(nil)
|
|
||||||
.frame(idealHeight: 0, maxHeight: .infinity)
|
|
||||||
.padding()
|
|
||||||
.background(Color(white: 0, opacity: 0.10))
|
|
||||||
.cornerRadius(10)
|
|
||||||
.onDrag {
|
|
||||||
return NSItemProvider(item: NSData(data: self.text.data(using: .utf8)!), typeIdentifier: kUTTypeUTF8PlainText as String)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SetupView {
|
|
||||||
|
|
||||||
func installLaunchAgent() -> Bool {
|
|
||||||
SMLoginItemSetEnabled("com.maxgoedjen.Secretive.SecretAgent" as CFString, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
func markAsDone() -> Bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SetupView {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let socketPath = (NSHomeDirectory().replacingOccurrences(of: "com.maxgoedjen.Secretive.Host", with: "com.maxgoedjen.Secretive.SecretAgent") as NSString).appendingPathComponent("socket.ssh") as String
|
|
||||||
static let socketPrompt = "export SSH_AUTH_SOCK=\(socketPath)"
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
#if DEBUG
|
|
||||||
|
|
||||||
struct SetupView_Previews: PreviewProvider {
|
|
||||||
static var previews: some View {
|
|
||||||
SetupView()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
@ -1,22 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>CFBundleDevelopmentRegion</key>
|
|
||||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
|
||||||
<key>CFBundleExecutable</key>
|
|
||||||
<string>$(EXECUTABLE_NAME)</string>
|
|
||||||
<key>CFBundleIdentifier</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
|
||||||
<key>CFBundleInfoDictionaryVersion</key>
|
|
||||||
<string>6.0</string>
|
|
||||||
<key>CFBundleName</key>
|
|
||||||
<string>$(PRODUCT_NAME)</string>
|
|
||||||
<key>CFBundlePackageType</key>
|
|
||||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
|
||||||
<key>CFBundleShortVersionString</key>
|
|
||||||
<string>1.0</string>
|
|
||||||
<key>CFBundleVersion</key>
|
|
||||||
<string>1</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
2
Sources/Config/Config.xcconfig
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
CI_VERSION = GITHUB_CI_VERSION
|
||||||
|
CI_BUILD_NUMBER = GITHUB_BUILD_NUMBER
|
26
Sources/Config/Secretive.xctestplan
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"configurations" : [
|
||||||
|
{
|
||||||
|
"id" : "5896AE5A-6D5A-48D3-837B-668B646A3273",
|
||||||
|
"name" : "Configuration 1",
|
||||||
|
"options" : {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"defaultOptions" : {
|
||||||
|
|
||||||
|
},
|
||||||
|
"testTargets" : [
|
||||||
|
{
|
||||||
|
"enabled" : false,
|
||||||
|
"parallelizable" : true,
|
||||||
|
"target" : {
|
||||||
|
"containerPath" : "container:Secretive.xcodeproj",
|
||||||
|
"identifier" : "50617D9323FCE48E0099B055",
|
||||||
|
"name" : "SecretiveTests"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version" : 1
|
||||||
|
}
|
70
Sources/Packages/Package.swift
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
// swift-tools-version:5.5
|
||||||
|
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||||
|
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
|
let package = Package(
|
||||||
|
name: "SecretivePackages",
|
||||||
|
platforms: [
|
||||||
|
.macOS(.v11)
|
||||||
|
],
|
||||||
|
products: [
|
||||||
|
.library(
|
||||||
|
name: "SecretKit",
|
||||||
|
targets: ["SecretKit"]),
|
||||||
|
.library(
|
||||||
|
name: "SecureEnclaveSecretKit",
|
||||||
|
targets: ["SecureEnclaveSecretKit"]),
|
||||||
|
.library(
|
||||||
|
name: "SmartCardSecretKit",
|
||||||
|
targets: ["SmartCardSecretKit"]),
|
||||||
|
.library(
|
||||||
|
name: "SecretAgentKit",
|
||||||
|
targets: ["SecretAgentKit"]),
|
||||||
|
.library(
|
||||||
|
name: "SecretAgentKitHeaders",
|
||||||
|
targets: ["SecretAgentKitHeaders"]),
|
||||||
|
.library(
|
||||||
|
name: "Brief",
|
||||||
|
targets: ["Brief"]),
|
||||||
|
],
|
||||||
|
dependencies: [
|
||||||
|
],
|
||||||
|
targets: [
|
||||||
|
.target(
|
||||||
|
name: "SecretKit",
|
||||||
|
dependencies: []
|
||||||
|
),
|
||||||
|
.testTarget(
|
||||||
|
name: "SecretKitTests",
|
||||||
|
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"]
|
||||||
|
),
|
||||||
|
.target(
|
||||||
|
name: "SecureEnclaveSecretKit",
|
||||||
|
dependencies: ["SecretKit"]
|
||||||
|
),
|
||||||
|
.target(
|
||||||
|
name: "SmartCardSecretKit",
|
||||||
|
dependencies: ["SecretKit"]
|
||||||
|
),
|
||||||
|
.target(
|
||||||
|
name: "SecretAgentKit",
|
||||||
|
dependencies: ["SecretKit", "SecretAgentKitHeaders"]
|
||||||
|
),
|
||||||
|
.systemLibrary(
|
||||||
|
name: "SecretAgentKitHeaders"
|
||||||
|
),
|
||||||
|
.testTarget(
|
||||||
|
name: "SecretAgentKitTests",
|
||||||
|
dependencies: ["SecretAgentKit"])
|
||||||
|
,
|
||||||
|
.target(
|
||||||
|
name: "Brief",
|
||||||
|
dependencies: []
|
||||||
|
),
|
||||||
|
.testTarget(
|
||||||
|
name: "BriefTests",
|
||||||
|
dependencies: ["Brief"]
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
@ -0,0 +1,15 @@
|
|||||||
|
# ``Brief``
|
||||||
|
|
||||||
|
Brief is a collection of protocols and concrete implmentation describing updates.
|
||||||
|
|
||||||
|
## Topics
|
||||||
|
|
||||||
|
### Versioning
|
||||||
|
|
||||||
|
- ``SemVer``
|
||||||
|
- ``Release``
|
||||||
|
|
||||||
|
### Updater
|
||||||
|
|
||||||
|
- ``UpdaterProtocol``
|
||||||
|
- ``Updater``
|
80
Sources/Packages/Sources/Brief/Release.swift
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// A release is a representation of a downloadable update.
|
||||||
|
public struct Release: Codable {
|
||||||
|
|
||||||
|
/// The user-facing name of the release. Typically "Secretive 1.2.3"
|
||||||
|
public let name: String
|
||||||
|
|
||||||
|
/// A boolean describing whether or not the release is a prerelase build.
|
||||||
|
public let prerelease: Bool
|
||||||
|
|
||||||
|
/// A URL pointing to the HTML page for the release.
|
||||||
|
public let html_url: URL
|
||||||
|
|
||||||
|
/// A user-facing description of the contents of the update.
|
||||||
|
public let body: String
|
||||||
|
|
||||||
|
/// Initializes a Release.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - name: The user-facing name of the release.
|
||||||
|
/// - prerelease: A boolean describing whether or not the release is a prerelase build.
|
||||||
|
/// - html_url: A URL pointing to the HTML page for the release.
|
||||||
|
/// - body: A user-facing description of the contents of the update.
|
||||||
|
public init(name: String, prerelease: Bool, html_url: URL, body: String) {
|
||||||
|
self.name = name
|
||||||
|
self.prerelease = prerelease
|
||||||
|
self.html_url = html_url
|
||||||
|
self.body = body
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Release: Identifiable {
|
||||||
|
|
||||||
|
public var id: String {
|
||||||
|
html_url.absoluteString
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Release: Comparable {
|
||||||
|
|
||||||
|
public static func < (lhs: Release, rhs: Release) -> Bool {
|
||||||
|
lhs.version < rhs.version
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Release {
|
||||||
|
|
||||||
|
/// A boolean describing whether or not the release contains critical security content.
|
||||||
|
/// - Note: this is determined by the presence of the phrase "Critical Security Update" in the ``body``.
|
||||||
|
/// - Warning: If this property is true, the user will not be able to dismiss UI or reminders associated with the update.
|
||||||
|
public var critical: Bool {
|
||||||
|
body.contains(Constants.securityContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A ``SemVer`` representation of the version number of the release.
|
||||||
|
public var version: SemVer {
|
||||||
|
SemVer(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The minimum macOS version required to run the update.
|
||||||
|
public var minimumOSVersion: SemVer {
|
||||||
|
guard let range = body.range(of: "Minimum macOS Version"),
|
||||||
|
let numberStart = body.rangeOfCharacter(from: CharacterSet.decimalDigits, options: [], range: range.upperBound..<body.endIndex) else { return SemVer("11.0.0") }
|
||||||
|
let numbersEnd = body.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines, options: [], range: numberStart.upperBound..<body.endIndex)?.lowerBound ?? body.endIndex
|
||||||
|
let version = numberStart.lowerBound..<numbersEnd
|
||||||
|
return SemVer(String(body[version]))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Release {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
static let securityContent = "Critical Security Update"
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
43
Sources/Packages/Sources/Brief/SemVer.swift
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// A representation of a Semantic Version.
|
||||||
|
public struct SemVer {
|
||||||
|
|
||||||
|
/// The SemVer broken into an array of integers.
|
||||||
|
let versionNumbers: [Int]
|
||||||
|
|
||||||
|
/// Initializes a SemVer from a string representation.
|
||||||
|
/// - Parameter version: A string representation of the SemVer, formatted as "major.minor.patch".
|
||||||
|
public init(_ version: String) {
|
||||||
|
// Betas have the format 1.2.3_beta1
|
||||||
|
let strippedBeta = version.split(separator: "_").first!
|
||||||
|
var split = strippedBeta.split(separator: ".").compactMap { Int($0) }
|
||||||
|
while split.count < 3 {
|
||||||
|
split.append(0)
|
||||||
|
}
|
||||||
|
versionNumbers = split
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initializes a SemVer from an `OperatingSystemVersion` representation.
|
||||||
|
/// - Parameter version: An `OperatingSystemVersion` representation of the SemVer.
|
||||||
|
public init(_ version: OperatingSystemVersion) {
|
||||||
|
versionNumbers = [version.majorVersion, version.minorVersion, version.patchVersion]
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SemVer: Comparable {
|
||||||
|
|
||||||
|
public static func < (lhs: SemVer, rhs: SemVer) -> Bool {
|
||||||
|
for (latest, current) in zip(lhs.versionNumbers, rhs.versionNumbers) {
|
||||||
|
if latest < current {
|
||||||
|
return true
|
||||||
|
} else if latest > current {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
97
Sources/Packages/Sources/Brief/Updater.swift
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
import Foundation
|
||||||
|
import Combine
|
||||||
|
|
||||||
|
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
|
||||||
|
public class Updater: ObservableObject, UpdaterProtocol {
|
||||||
|
|
||||||
|
@Published public var update: Release?
|
||||||
|
public let testBuild: Bool
|
||||||
|
|
||||||
|
/// The current OS version.
|
||||||
|
private let osVersion: SemVer
|
||||||
|
/// The current version of the app that is running.
|
||||||
|
private let currentVersion: SemVer
|
||||||
|
|
||||||
|
/// Initializes an Updater.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - checkOnLaunch: A boolean describing whether the Updater should check for available updates on launch.
|
||||||
|
/// - checkFrequency: The interval at which the Updater should check for updates. Subject to a tolerance of 1 hour.
|
||||||
|
/// - osVersion: The current OS version.
|
||||||
|
/// - currentVersion: The current version of the app that is running.
|
||||||
|
public init(checkOnLaunch: Bool, checkFrequency: TimeInterval = Measurement(value: 24, unit: UnitDuration.hours).converted(to: .seconds).value, osVersion: SemVer = SemVer(ProcessInfo.processInfo.operatingSystemVersion), currentVersion: SemVer = SemVer(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0")) {
|
||||||
|
self.osVersion = osVersion
|
||||||
|
self.currentVersion = currentVersion
|
||||||
|
testBuild = currentVersion == SemVer("0.0.0")
|
||||||
|
if checkOnLaunch {
|
||||||
|
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
|
||||||
|
checkForUpdates()
|
||||||
|
}
|
||||||
|
let timer = Timer.scheduledTimer(withTimeInterval: checkFrequency, repeats: true) { _ in
|
||||||
|
self.checkForUpdates()
|
||||||
|
}
|
||||||
|
timer.tolerance = 60*60
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Manually trigger an update check.
|
||||||
|
public func checkForUpdates() {
|
||||||
|
URLSession.shared.dataTask(with: Constants.updateURL) { data, _, _ in
|
||||||
|
guard let data = data else { return }
|
||||||
|
guard let releases = try? JSONDecoder().decode([Release].self, from: data) else { return }
|
||||||
|
self.evaluate(releases: releases)
|
||||||
|
}.resume()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ignores a specified release. `update` will be nil if the user has ignored the latest available release.
|
||||||
|
/// - Parameter release: The release to ignore.
|
||||||
|
public func ignore(release: Release) {
|
||||||
|
guard !release.critical else { return }
|
||||||
|
defaults.set(true, forKey: release.name)
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.update = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Updater {
|
||||||
|
|
||||||
|
/// Evaluates the available downloadable releases, and selects the newest non-prerelease release that the user is able to run.
|
||||||
|
/// - Parameter releases: An array of ``Release`` objects.
|
||||||
|
func evaluate(releases: [Release]) {
|
||||||
|
guard let release = releases
|
||||||
|
.sorted()
|
||||||
|
.reversed()
|
||||||
|
.filter({ !$0.prerelease })
|
||||||
|
.first(where: { $0.minimumOSVersion <= osVersion }) else { return }
|
||||||
|
guard !userIgnored(release: release) else { return }
|
||||||
|
guard !release.prerelease else { return }
|
||||||
|
let latestVersion = SemVer(release.name)
|
||||||
|
if latestVersion > currentVersion {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.update = release
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks whether the user has ignored a release.
|
||||||
|
/// - Parameter release: The release to check.
|
||||||
|
/// - Returns: A boolean describing whether the user has ignored the release. Will always be false if the release is critical.
|
||||||
|
func userIgnored(release: Release) -> Bool {
|
||||||
|
guard !release.critical else { return false }
|
||||||
|
return defaults.bool(forKey: release.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user defaults used to store user ignore state.
|
||||||
|
var defaults: UserDefaults {
|
||||||
|
UserDefaults(suiteName: "com.maxgoedjen.Secretive.updater.ignorelist")!
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Updater {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases")!
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
12
Sources/Packages/Sources/Brief/UpdaterProtocol.swift
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// A protocol for retreiving the latest available version of an app.
|
||||||
|
public protocol UpdaterProtocol: ObservableObject {
|
||||||
|
|
||||||
|
/// The latest update
|
||||||
|
var update: Release? { get }
|
||||||
|
/// A boolean describing whether or not the current build of the app is a "test" build (ie, a debug build or otherwise special build)
|
||||||
|
var testBuild: Bool { get }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
205
Sources/Packages/Sources/SecretAgentKit/Agent.swift
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
import Foundation
|
||||||
|
import CryptoKit
|
||||||
|
import OSLog
|
||||||
|
import SecretKit
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
/// The `Agent` is an implementation of an SSH agent. It manages coordination and access between a socket, traces requests, notifies witnesses and passes requests to stores.
|
||||||
|
public class Agent {
|
||||||
|
|
||||||
|
private let storeList: SecretStoreList
|
||||||
|
private let witness: SigningWitness?
|
||||||
|
private let writer = OpenSSHKeyWriter()
|
||||||
|
private let requestTracer = SigningRequestTracer()
|
||||||
|
|
||||||
|
/// Initializes an agent with a store list and a witness.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - storeList: The `SecretStoreList` to make available.
|
||||||
|
/// - witness: A witness to notify of requests.
|
||||||
|
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
|
||||||
|
Logger().debug("Agent is running")
|
||||||
|
self.storeList = storeList
|
||||||
|
self.witness = witness
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Agent {
|
||||||
|
|
||||||
|
/// Handles an incoming request.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - reader: A ``FileHandleReader`` to read the content of the request.
|
||||||
|
/// - writer: A ``FileHandleWriter`` to write the response to.
|
||||||
|
/// - Return value:
|
||||||
|
/// - Boolean if data could be read
|
||||||
|
public func handle(reader: FileHandleReader, writer: FileHandleWriter) -> Bool {
|
||||||
|
Logger().debug("Agent handling new data")
|
||||||
|
let data = Data(reader.availableData)
|
||||||
|
guard data.count > 4 else { return false}
|
||||||
|
let requestTypeInt = data[4]
|
||||||
|
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else {
|
||||||
|
writer.write(OpenSSHKeyWriter().lengthAndData(of: SSHAgent.ResponseType.agentFailure.data))
|
||||||
|
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
Logger().debug("Agent handling request of type \(requestType.debugDescription)")
|
||||||
|
let subData = Data(data[5...])
|
||||||
|
let response = handle(requestType: requestType, data: subData, reader: reader)
|
||||||
|
writer.write(response)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
|
||||||
|
var response = Data()
|
||||||
|
do {
|
||||||
|
switch requestType {
|
||||||
|
case .requestIdentities:
|
||||||
|
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
|
||||||
|
response.append(identities())
|
||||||
|
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)")
|
||||||
|
case .signRequest:
|
||||||
|
let provenance = requestTracer.provenance(from: reader)
|
||||||
|
response.append(SSHAgent.ResponseType.agentSignResponse.data)
|
||||||
|
response.append(try sign(data: data, provenance: provenance))
|
||||||
|
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
response.removeAll()
|
||||||
|
response.append(SSHAgent.ResponseType.agentFailure.data)
|
||||||
|
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
||||||
|
}
|
||||||
|
let full = OpenSSHKeyWriter().lengthAndData(of: response)
|
||||||
|
return full
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Agent {
|
||||||
|
|
||||||
|
/// Lists the identities available for signing operations
|
||||||
|
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
|
||||||
|
func identities() -> Data {
|
||||||
|
let secrets = storeList.stores.flatMap(\.secrets)
|
||||||
|
var count = UInt32(secrets.count).bigEndian
|
||||||
|
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
||||||
|
var keyData = Data()
|
||||||
|
let writer = OpenSSHKeyWriter()
|
||||||
|
for secret in secrets {
|
||||||
|
let keyBlob = writer.data(secret: secret)
|
||||||
|
keyData.append(writer.lengthAndData(of: keyBlob))
|
||||||
|
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||||
|
keyData.append(writer.lengthAndData(of: curveData))
|
||||||
|
}
|
||||||
|
Logger().debug("Agent enumerated \(secrets.count) identities")
|
||||||
|
return countData + keyData
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Notifies witnesses of a pending signature request, and performs the signing operation if none object.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: The data to sign.
|
||||||
|
/// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request.
|
||||||
|
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
|
||||||
|
func sign(data: Data, provenance: SigningRequestProvenance) throws -> Data {
|
||||||
|
let reader = OpenSSHReader(data: data)
|
||||||
|
let hash = reader.readNextChunk()
|
||||||
|
guard let (store, secret) = secret(matching: hash) else {
|
||||||
|
Logger().debug("Agent did not have a key matching \(hash as NSData)")
|
||||||
|
throw AgentError.noMatchingKey
|
||||||
|
}
|
||||||
|
|
||||||
|
if let witness = witness {
|
||||||
|
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
||||||
|
}
|
||||||
|
|
||||||
|
let dataToSign = reader.readNextChunk()
|
||||||
|
let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
|
||||||
|
let derSignature = signed.data
|
||||||
|
|
||||||
|
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||||
|
|
||||||
|
// Convert from DER formatted rep to raw (r||s)
|
||||||
|
|
||||||
|
let rawRepresentation: Data
|
||||||
|
switch (secret.algorithm, secret.keySize) {
|
||||||
|
case (.ellipticCurve, 256):
|
||||||
|
rawRepresentation = try CryptoKit.P256.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
||||||
|
case (.ellipticCurve, 384):
|
||||||
|
rawRepresentation = try CryptoKit.P384.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
||||||
|
default:
|
||||||
|
throw AgentError.unsupportedKeyType
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
let rawLength = rawRepresentation.count/2
|
||||||
|
// Check if we need to pad with 0x00 to prevent certain
|
||||||
|
// ssh servers from thinking r or s is negative
|
||||||
|
let paddingRange: ClosedRange<UInt8> = 0x80...0xFF
|
||||||
|
var r = Data(rawRepresentation[0..<rawLength])
|
||||||
|
if paddingRange ~= r.first! {
|
||||||
|
r.insert(0x00, at: 0)
|
||||||
|
}
|
||||||
|
var s = Data(rawRepresentation[rawLength...])
|
||||||
|
if paddingRange ~= s.first! {
|
||||||
|
s.insert(0x00, at: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
var signatureChunk = Data()
|
||||||
|
signatureChunk.append(writer.lengthAndData(of: r))
|
||||||
|
signatureChunk.append(writer.lengthAndData(of: s))
|
||||||
|
|
||||||
|
var signedData = Data()
|
||||||
|
var sub = Data()
|
||||||
|
sub.append(writer.lengthAndData(of: curveData))
|
||||||
|
sub.append(writer.lengthAndData(of: signatureChunk))
|
||||||
|
signedData.append(writer.lengthAndData(of: sub))
|
||||||
|
|
||||||
|
if let witness = witness {
|
||||||
|
try witness.witness(accessTo: secret, from: store, by: provenance, requiredAuthentication: signed.requiredAuthentication)
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger().debug("Agent signed request")
|
||||||
|
|
||||||
|
return signedData
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Agent {
|
||||||
|
|
||||||
|
/// Finds a ``Secret`` matching a specified hash whos signature was requested.
|
||||||
|
/// - Parameter hash: The hash to match against.
|
||||||
|
/// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found.
|
||||||
|
func secret(matching hash: Data) -> (AnySecretStore, AnySecret)? {
|
||||||
|
storeList.stores.compactMap { store -> (AnySecretStore, AnySecret)? in
|
||||||
|
let allMatching = store.secrets.filter { secret in
|
||||||
|
hash == writer.data(secret: secret)
|
||||||
|
}
|
||||||
|
if let matching = allMatching.first {
|
||||||
|
return (store, matching)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}.first
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
extension Agent {
|
||||||
|
|
||||||
|
/// An error involving agent operations..
|
||||||
|
enum AgentError: Error {
|
||||||
|
case unhandledType
|
||||||
|
case noMatchingKey
|
||||||
|
case unsupportedKeyType
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SSHAgent.ResponseType {
|
||||||
|
|
||||||
|
var data: Data {
|
||||||
|
var raw = self.rawValue
|
||||||
|
return Data(bytes: &raw, count: UInt8.bitWidth/8)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
# ``SecretAgentKit``
|
||||||
|
|
||||||
|
SecretAgentKit is a collection of types that allow SecretAgent to conform to the SSH agent protocol.
|
||||||
|
|
||||||
|
## Topics
|
||||||
|
|
||||||
|
### Agent
|
||||||
|
|
||||||
|
- ``Agent``
|
||||||
|
|
||||||
|
### Protocol
|
||||||
|
|
||||||
|
- ``SSHAgent``
|
||||||
|
|
||||||
|
### Request Notification
|
||||||
|
|
||||||
|
- ``SigningWitness``
|
||||||
|
|
||||||
|
### Socket Operations
|
||||||
|
|
||||||
|
- ``SocketController``
|
||||||
|
- ``FileHandleReader``
|
||||||
|
- ``FileHandleWriter``
|
@ -0,0 +1,32 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Protocol abstraction of the reading aspects of FileHandle.
|
||||||
|
public protocol FileHandleReader {
|
||||||
|
|
||||||
|
/// Gets data that is available for reading.
|
||||||
|
var availableData: Data { get }
|
||||||
|
/// A file descriptor of the handle.
|
||||||
|
var fileDescriptor: Int32 { get }
|
||||||
|
/// The process ID of the process coonnected to the other end of the FileHandle.
|
||||||
|
var pidOfConnectedProcess: Int32 { get }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Protocol abstraction of the writing aspects of FileHandle.
|
||||||
|
public protocol FileHandleWriter {
|
||||||
|
|
||||||
|
/// Writes data to the handle.
|
||||||
|
func write(_ data: Data)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension FileHandle: FileHandleReader, FileHandleWriter {
|
||||||
|
|
||||||
|
public var pidOfConnectedProcess: Int32 {
|
||||||
|
let pidPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
|
||||||
|
var len = socklen_t(MemoryLayout<Int32>.size)
|
||||||
|
getsockopt(fileDescriptor, SOCK_STREAM, LOCAL_PEERPID, pidPointer, &len)
|
||||||
|
return pidPointer.load(as: Int32.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,10 +1,13 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
/// A namespace for the SSH Agent Protocol, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html
|
||||||
public enum SSHAgent {}
|
public enum SSHAgent {}
|
||||||
|
|
||||||
extension SSHAgent {
|
extension SSHAgent {
|
||||||
|
|
||||||
|
/// The type of the SSH Agent Request, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
|
||||||
public enum RequestType: UInt8, CustomDebugStringConvertible {
|
public enum RequestType: UInt8, CustomDebugStringConvertible {
|
||||||
|
|
||||||
case requestIdentities = 11
|
case requestIdentities = 11
|
||||||
case signRequest = 13
|
case signRequest = 13
|
||||||
|
|
||||||
@ -12,13 +15,15 @@ extension SSHAgent {
|
|||||||
switch self {
|
switch self {
|
||||||
case .requestIdentities:
|
case .requestIdentities:
|
||||||
return "RequestIdentities"
|
return "RequestIdentities"
|
||||||
default:
|
case .signRequest:
|
||||||
return "SignRequest"
|
return "SignRequest"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The type of the SSH Agent Response, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
|
||||||
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
||||||
|
|
||||||
case agentFailure = 5
|
case agentFailure = 5
|
||||||
case agentIdentitiesAnswer = 12
|
case agentIdentitiesAnswer = 12
|
||||||
case agentSignResponse = 14
|
case agentSignResponse = 14
|
@ -0,0 +1,77 @@
|
|||||||
|
import Foundation
|
||||||
|
import AppKit
|
||||||
|
import Security
|
||||||
|
import SecretKit
|
||||||
|
import SecretAgentKitHeaders
|
||||||
|
|
||||||
|
/// An object responsible for generating ``SecretKit.SigningRequestProvenance`` objects.
|
||||||
|
struct SigningRequestTracer {
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SigningRequestTracer {
|
||||||
|
|
||||||
|
/// Generates a ``SecretKit.SigningRequestProvenance`` from a ``FileHandleReader``.
|
||||||
|
/// - Parameter fileHandleReader: The reader involved in processing the request.
|
||||||
|
/// - Returns: A ``SecretKit.SigningRequestProvenance`` describing the origin of the request.
|
||||||
|
func provenance(from fileHandleReader: FileHandleReader) -> SigningRequestProvenance {
|
||||||
|
let firstInfo = process(from: fileHandleReader.pidOfConnectedProcess)
|
||||||
|
|
||||||
|
var provenance = SigningRequestProvenance(root: firstInfo)
|
||||||
|
while NSRunningApplication(processIdentifier: provenance.origin.pid) == nil && provenance.origin.parentPID != nil {
|
||||||
|
provenance.chain.append(process(from: provenance.origin.parentPID!))
|
||||||
|
}
|
||||||
|
return provenance
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates a `kinfo_proc` representation of the provided process ID.
|
||||||
|
/// - Parameter pid: The process ID to look up.
|
||||||
|
/// - Returns: a `kinfo_proc` struct describing the process ID.
|
||||||
|
func pidAndNameInfo(from pid: Int32) -> kinfo_proc {
|
||||||
|
var len = MemoryLayout<kinfo_proc>.size
|
||||||
|
let infoPointer = UnsafeMutableRawPointer.allocate(byteCount: len, alignment: 1)
|
||||||
|
var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]
|
||||||
|
sysctl(&name, UInt32(name.count), infoPointer, &len, nil, 0)
|
||||||
|
return infoPointer.load(as: kinfo_proc.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates a ``SecretKit.SigningRequestProvenance.Process`` from a provided process ID.
|
||||||
|
/// - Parameter pid: The process ID to look up.
|
||||||
|
/// - Returns: A ``SecretKit.SigningRequestProvenance.Process`` describing the process.
|
||||||
|
func process(from pid: Int32) -> SigningRequestProvenance.Process {
|
||||||
|
var pidAndNameInfo = self.pidAndNameInfo(from: pid)
|
||||||
|
let ppid = pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
|
||||||
|
let procName = String(cString: &pidAndNameInfo.kp_proc.p_comm.0)
|
||||||
|
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
|
||||||
|
_ = proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
|
||||||
|
let path = String(cString: pathPointer)
|
||||||
|
var secCode: Unmanaged<SecCode>!
|
||||||
|
let flags: SecCSFlags = [.considerExpiration, .enforceRevocationChecks]
|
||||||
|
SecCodeCreateWithPID(pid, SecCSFlags(), &secCode)
|
||||||
|
let valid = SecCodeCheckValidity(secCode.takeRetainedValue(), flags, nil) == errSecSuccess
|
||||||
|
return SigningRequestProvenance.Process(pid: pid, processName: procName, appName: appName(for: pid), iconURL: iconURL(for: pid), path: path, validSignature: valid, parentPID: ppid)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks up the URL for the icon of a process ID, if it has one.
|
||||||
|
/// - Parameter pid: The process ID to look up.
|
||||||
|
/// - Returns: A URL to the icon, if the process has one.
|
||||||
|
func iconURL(for pid: Int32) -> URL? {
|
||||||
|
do {
|
||||||
|
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
|
||||||
|
let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(UUID().uuidString).png"))
|
||||||
|
let bitmap = NSBitmapImageRep(data: icon)
|
||||||
|
try bitmap?.representation(using: .png, properties: [:])?.write(to: temporaryURL)
|
||||||
|
return temporaryURL
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks up the application name of a process ID, if it has one.
|
||||||
|
/// - Parameter pid: The process ID to look up.
|
||||||
|
/// - Returns: The process's display name, if the process has one.
|
||||||
|
func appName(for pid: Int32) -> String? {
|
||||||
|
NSRunningApplication(processIdentifier: pid)?.localizedName
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
23
Sources/Packages/Sources/SecretAgentKit/SigningWitness.swift
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import Foundation
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
|
/// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access.
|
||||||
|
public protocol SigningWitness {
|
||||||
|
|
||||||
|
/// A ridiculously named method that notifies the callee that a signing operation is about to be performed using a secret. The callee may `throw` an `Error` to prevent access from occurring.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The `Secret` that will be used to sign the request.
|
||||||
|
/// - store: The `Store` being asked to sign the request..
|
||||||
|
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
||||||
|
/// - Note: This method being called does not imply that the requst has been authorized. If a secret requires authentication, authentication will still need to be performed by the user before the request will be performed. If the user declines or fails to authenticate, the request will fail.
|
||||||
|
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
|
||||||
|
|
||||||
|
/// Notifies the callee that a signing operation has been performed for a given secret.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The `Secret` that will was used to sign the request.
|
||||||
|
/// - store: The `Store` that signed the request..
|
||||||
|
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
||||||
|
/// - requiredAuthentication: A boolean describing whether or not authentication was required for the request.
|
||||||
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,89 @@
|
|||||||
|
import Foundation
|
||||||
|
import OSLog
|
||||||
|
|
||||||
|
/// A controller that manages socket configuration and request dispatching.
|
||||||
|
public class SocketController {
|
||||||
|
|
||||||
|
/// The active FileHandle.
|
||||||
|
private var fileHandle: FileHandle?
|
||||||
|
/// The active SocketPort.
|
||||||
|
private var port: SocketPort?
|
||||||
|
/// A handler that will be notified when a new read/write handle is available.
|
||||||
|
/// False if no data could be read
|
||||||
|
public var handler: ((FileHandleReader, FileHandleWriter) -> Bool)?
|
||||||
|
|
||||||
|
|
||||||
|
/// Initializes a socket controller with a specified path.
|
||||||
|
/// - Parameter path: The path to use as a socket.
|
||||||
|
public init(path: String) {
|
||||||
|
Logger().debug("Socket controller setting up at \(path)")
|
||||||
|
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
||||||
|
Logger().debug("Socket controller removed existing socket")
|
||||||
|
}
|
||||||
|
let exists = FileManager.default.fileExists(atPath: path)
|
||||||
|
assert(!exists)
|
||||||
|
Logger().debug("Socket controller path is clear")
|
||||||
|
port = socketPort(at: path)
|
||||||
|
configureSocket(at: path)
|
||||||
|
Logger().debug("Socket listening at \(path)")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Configures the socket and a corresponding FileHandle.
|
||||||
|
/// - Parameter path: The path to use as a socket.
|
||||||
|
func configureSocket(at path: String) {
|
||||||
|
guard let port = port else { return }
|
||||||
|
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
||||||
|
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionAccept(notification:)), name: .NSFileHandleConnectionAccepted, object: nil)
|
||||||
|
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionDataAvailable(notification:)), name: .NSFileHandleDataAvailable, object: nil)
|
||||||
|
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a SocketPort for a path.
|
||||||
|
/// - Parameter path: The path to use as a socket.
|
||||||
|
/// - Returns: A configured SocketPort.
|
||||||
|
func socketPort(at path: String) -> SocketPort {
|
||||||
|
var addr = sockaddr_un()
|
||||||
|
addr.sun_family = sa_family_t(AF_UNIX)
|
||||||
|
|
||||||
|
var len: Int = 0
|
||||||
|
withUnsafeMutablePointer(to: &addr.sun_path.0) { pointer in
|
||||||
|
path.withCString { cstring in
|
||||||
|
len = strlen(cstring)
|
||||||
|
strncpy(pointer, cstring, len)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addr.sun_len = UInt8(len+2)
|
||||||
|
|
||||||
|
var data: Data!
|
||||||
|
withUnsafePointer(to: &addr) { pointer in
|
||||||
|
data = Data(bytes: pointer, count: MemoryLayout<sockaddr_un>.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
return SocketPort(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles a new connection being accepted, invokes the handler, and prepares to accept new connections.
|
||||||
|
/// - Parameter notification: A `Notification` that triggered the call.
|
||||||
|
@objc func handleConnectionAccept(notification: Notification) {
|
||||||
|
Logger().debug("Socket controller accepted connection")
|
||||||
|
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
||||||
|
_ = handler?(new, new)
|
||||||
|
new.waitForDataInBackgroundAndNotify()
|
||||||
|
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles a new connection providing data and invokes the handler callback.
|
||||||
|
/// - Parameter notification: A `Notification` that triggered the call.
|
||||||
|
@objc func handleConnectionDataAvailable(notification: Notification) {
|
||||||
|
Logger().debug("Socket controller has new data available")
|
||||||
|
guard let new = notification.object as? FileHandle else { return }
|
||||||
|
Logger().debug("Socket controller received new file handle")
|
||||||
|
if((handler?(new, new)) == true) {
|
||||||
|
Logger().debug("Socket controller handled data, wait for more data")
|
||||||
|
new.waitForDataInBackgroundAndNotify()
|
||||||
|
} else {
|
||||||
|
Logger().debug("Socket controller called with empty data, socked closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
|
@ -0,0 +1,19 @@
|
|||||||
|
#import <Foundation/Foundation.h>
|
||||||
|
#import <Security/Security.h>
|
||||||
|
|
||||||
|
|
||||||
|
// Forward declarations
|
||||||
|
|
||||||
|
// from libproc.h
|
||||||
|
int proc_pidpath(int pid, void * buffer, uint32_t buffersize);
|
||||||
|
|
||||||
|
// from SecTask.h
|
||||||
|
OSStatus SecCodeCreateWithPID(int32_t, SecCSFlags, SecCodeRef *);
|
||||||
|
|
||||||
|
//! Project version number for SecretAgentKit.
|
||||||
|
FOUNDATION_EXPORT double SecretAgentKitVersionNumber;
|
||||||
|
|
||||||
|
//! Project version string for SecretAgentKit.
|
||||||
|
FOUNDATION_EXPORT const unsigned char SecretAgentKitVersionString[];
|
||||||
|
|
||||||
|
|
@ -0,0 +1,4 @@
|
|||||||
|
module SecretAgentKitHeaders [system] {
|
||||||
|
header "include/SecretAgentKit.h"
|
||||||
|
export *
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
# ``SecretKit``
|
||||||
|
|
||||||
|
SecretKit is a collection of protocols describing secrets and stores.
|
||||||
|
|
||||||
|
## Topics
|
||||||
|
|
||||||
|
### Base Protocols
|
||||||
|
|
||||||
|
- ``Secret``
|
||||||
|
- ``SecretStore``
|
||||||
|
- ``SecretStoreModifiable``
|
||||||
|
|
||||||
|
### Store List
|
||||||
|
|
||||||
|
- ``SecretStoreList``
|
||||||
|
|
||||||
|
### Type Erasers
|
||||||
|
|
||||||
|
- ``AnySecret``
|
||||||
|
- ``AnySecretStore``
|
||||||
|
- ``AnySecretStoreModifiable``
|
||||||
|
|
||||||
|
### OpenSSH
|
||||||
|
|
||||||
|
- ``OpenSSHKeyWriter``
|
||||||
|
- ``OpenSSHReader``
|
||||||
|
|
||||||
|
### Signing Process
|
||||||
|
|
||||||
|
- ``SignedData``
|
||||||
|
- ``SigningRequestProvenance``
|
@ -1,14 +1,15 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
/// Type eraser for Secret.
|
||||||
public struct AnySecret: Secret {
|
public struct AnySecret: Secret {
|
||||||
|
|
||||||
let base: Any
|
let base: Any
|
||||||
fileprivate let hashable: AnyHashable
|
private let hashable: AnyHashable
|
||||||
fileprivate let _id: () -> AnyHashable
|
private let _id: () -> AnyHashable
|
||||||
fileprivate let _name: () -> String
|
private let _name: () -> String
|
||||||
fileprivate let _algorithm: () -> Algorithm
|
private let _algorithm: () -> Algorithm
|
||||||
fileprivate let _keySize: () -> Int
|
private let _keySize: () -> Int
|
||||||
fileprivate let _publicKey: () -> Data
|
private let _publicKey: () -> Data
|
||||||
|
|
||||||
public init<T>(_ secret: T) where T: Secret {
|
public init<T>(_ secret: T) where T: Secret {
|
||||||
if let secret = secret as? AnySecret {
|
if let secret = secret as? AnySecret {
|
@ -1,15 +1,18 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
import Combine
|
||||||
|
|
||||||
|
/// Type eraser for SecretStore.
|
||||||
public class AnySecretStore: SecretStore {
|
public class AnySecretStore: SecretStore {
|
||||||
|
|
||||||
let base: Any
|
let base: Any
|
||||||
fileprivate let _isAvailable: () -> Bool
|
private let _isAvailable: () -> Bool
|
||||||
fileprivate let _id: () -> UUID
|
private let _id: () -> UUID
|
||||||
fileprivate let _name: () -> String
|
private let _name: () -> String
|
||||||
fileprivate let _secrets: () -> [AnySecret]
|
private let _secrets: () -> [AnySecret]
|
||||||
fileprivate let _sign: (Data, AnySecret) throws -> Data
|
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> SignedData
|
||||||
fileprivate var sink: AnyCancellable?
|
private let _persistAuthentication: (AnySecret, TimeInterval) throws -> Void
|
||||||
|
|
||||||
|
private var sink: AnyCancellable?
|
||||||
|
|
||||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
||||||
base = secretStore
|
base = secretStore
|
||||||
@ -17,7 +20,8 @@ public class AnySecretStore: SecretStore {
|
|||||||
_name = { secretStore.name }
|
_name = { secretStore.name }
|
||||||
_id = { secretStore.id }
|
_id = { secretStore.id }
|
||||||
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
||||||
_sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType) }
|
_sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
|
||||||
|
_persistAuthentication = { try secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
||||||
sink = secretStore.objectWillChange.sink { _ in
|
sink = secretStore.objectWillChange.sink { _ in
|
||||||
self.objectWillChange.send()
|
self.objectWillChange.send()
|
||||||
}
|
}
|
||||||
@ -39,20 +43,26 @@ public class AnySecretStore: SecretStore {
|
|||||||
return _secrets()
|
return _secrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func sign(data: Data, with secret: AnySecret) throws -> Data {
|
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||||
try _sign(data, secret)
|
try _sign(data, secret, provenance)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) throws {
|
||||||
|
try _persistAuthentication(secret, duration)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
||||||
|
|
||||||
fileprivate let _create: (String, Bool) throws -> Void
|
private let _create: (String, Bool) throws -> Void
|
||||||
fileprivate let _delete: (AnySecret) throws -> Void
|
private let _delete: (AnySecret) throws -> Void
|
||||||
|
private let _update: (AnySecret, String) throws -> Void
|
||||||
|
|
||||||
public init<SecretStoreType>(modifiable secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable {
|
public init<SecretStoreType>(modifiable secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable {
|
||||||
_create = { try secretStore.create(name: $0, requiresAuthentication: $1) }
|
_create = { try secretStore.create(name: $0, requiresAuthentication: $1) }
|
||||||
_delete = { try secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
|
_delete = { try secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
|
||||||
|
_update = { try secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1) }
|
||||||
super.init(secretStore)
|
super.init(secretStore)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -64,4 +74,8 @@ public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
|||||||
try _delete(secret)
|
try _delete(secret)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public func update(secret: AnySecret, name: String) throws {
|
||||||
|
try _update(secret, name)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -0,0 +1,82 @@
|
|||||||
|
import Foundation
|
||||||
|
import CryptoKit
|
||||||
|
|
||||||
|
/// Generates OpenSSH representations of Secrets.
|
||||||
|
public struct OpenSSHKeyWriter {
|
||||||
|
|
||||||
|
/// Initializes the writer.
|
||||||
|
public init() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH data payload identifying the secret.
|
||||||
|
/// - Returns: OpenSSH data payload identifying the secret.
|
||||||
|
public func data<SecretType: Secret>(secret: SecretType) -> Data {
|
||||||
|
lengthAndData(of: curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
||||||
|
lengthAndData(of: curveIdentifier(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
||||||
|
lengthAndData(of: secret.publicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH string representation of the secret.
|
||||||
|
/// - Returns: OpenSSH string representation of the secret.
|
||||||
|
public func openSSHString<SecretType: Secret>(secret: SecretType, comment: String? = nil) -> String {
|
||||||
|
[curveType(for: secret.algorithm, length: secret.keySize), data(secret: secret).base64EncodedString(), comment]
|
||||||
|
.compactMap { $0 }
|
||||||
|
.joined(separator: " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH SHA256 fingerprint string.
|
||||||
|
/// - Returns: OpenSSH SHA256 fingerprint string.
|
||||||
|
public func openSSHSHA256Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||||
|
// OpenSSL format seems to strip the padding at the end.
|
||||||
|
let base64 = Data(SHA256.hash(data: data(secret: secret))).base64EncodedString()
|
||||||
|
let paddingRange = base64.index(base64.endIndex, offsetBy: -2)..<base64.endIndex
|
||||||
|
let cleaned = base64.replacingOccurrences(of: "=", with: "", range: paddingRange)
|
||||||
|
return "SHA256:\(cleaned)"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates an OpenSSH MD5 fingerprint string.
|
||||||
|
/// - Returns: OpenSSH MD5 fingerprint string.
|
||||||
|
public func openSSHMD5Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||||
|
Insecure.MD5.hash(data: data(secret: secret))
|
||||||
|
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
||||||
|
.joined(separator: ":")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHKeyWriter {
|
||||||
|
|
||||||
|
/// Creates an OpenSSH protocol style data object, which has a length header, followed by the data payload.
|
||||||
|
/// - Parameter data: The data payload.
|
||||||
|
/// - Returns: OpenSSH data.
|
||||||
|
public func lengthAndData(of data: Data) -> Data {
|
||||||
|
let rawLength = UInt32(data.count)
|
||||||
|
var endian = rawLength.bigEndian
|
||||||
|
return Data(bytes: &endian, count: UInt32.bitWidth/8) + data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fully qualified OpenSSH identifier for the algorithm.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - algorithm: The algorithm to identify.
|
||||||
|
/// - length: The key length of the algorithm.
|
||||||
|
/// - Returns: The OpenSSH identifier for the algorithm.
|
||||||
|
public func curveType(for algorithm: Algorithm, length: Int) -> String {
|
||||||
|
switch algorithm {
|
||||||
|
case .ellipticCurve:
|
||||||
|
return "ecdsa-sha2-nistp" + String(describing: length)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The OpenSSH identifier for an algorithm.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - algorithm: The algorithm to identify.
|
||||||
|
/// - length: The key length of the algorithm.
|
||||||
|
/// - Returns: The OpenSSH identifier for the algorithm.
|
||||||
|
private func curveIdentifier(for algorithm: Algorithm, length: Int) -> String {
|
||||||
|
switch algorithm {
|
||||||
|
case .ellipticCurve:
|
||||||
|
return "nistp" + String(describing: length)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,14 +1,19 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
/// Reads OpenSSH protocol data.
|
||||||
public class OpenSSHReader {
|
public class OpenSSHReader {
|
||||||
|
|
||||||
var remaining: Data
|
var remaining: Data
|
||||||
|
|
||||||
|
/// Initialize the reader with an OpenSSH data payload.
|
||||||
|
/// - Parameter data: The data to read.
|
||||||
public init(data: Data) {
|
public init(data: Data) {
|
||||||
remaining = Data(data)
|
remaining = Data(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func readNextChunk() throws -> Data {
|
/// Reads the next chunk of data from the playload.
|
||||||
|
/// - Returns: The next chunk of data.
|
||||||
|
public func readNextChunk() -> Data {
|
||||||
let lengthRange = 0..<(UInt32.bitWidth/8)
|
let lengthRange = 0..<(UInt32.bitWidth/8)
|
||||||
let lengthChunk = remaining[lengthRange]
|
let lengthChunk = remaining[lengthRange]
|
||||||
remaining.removeSubrange(lengthRange)
|
remaining.removeSubrange(lengthRange)
|
@ -0,0 +1,42 @@
|
|||||||
|
import Foundation
|
||||||
|
import OSLog
|
||||||
|
|
||||||
|
/// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts.
|
||||||
|
public class PublicKeyFileStoreController {
|
||||||
|
|
||||||
|
private let logger = Logger()
|
||||||
|
private let directory: String
|
||||||
|
private let keyWriter = OpenSSHKeyWriter()
|
||||||
|
|
||||||
|
/// Initializes a PublicKeyFileStoreController.
|
||||||
|
public init(homeDirectory: String) {
|
||||||
|
directory = homeDirectory.appending("/PublicKeys")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes out the keys specified to disk.
|
||||||
|
/// - Parameter secrets: The Secrets to generate keys for.
|
||||||
|
/// - Parameter clear: Whether or not the directory should be erased before writing keys.
|
||||||
|
public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws {
|
||||||
|
logger.log("Writing public keys to disk")
|
||||||
|
if clear {
|
||||||
|
try? FileManager.default.removeItem(at: URL(fileURLWithPath: directory))
|
||||||
|
}
|
||||||
|
try? FileManager.default.createDirectory(at: URL(fileURLWithPath: directory), withIntermediateDirectories: false, attributes: nil)
|
||||||
|
for secret in secrets {
|
||||||
|
let path = path(for: secret)
|
||||||
|
guard let data = keyWriter.openSSHString(secret: secret).data(using: .utf8) else { continue }
|
||||||
|
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
|
||||||
|
}
|
||||||
|
logger.log("Finished writing public keys")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path for a Secret's public key.
|
||||||
|
/// - Parameter secret: The Secret to return the path for.
|
||||||
|
/// - Returns: The path to the Secret's public key.
|
||||||
|
/// - Warning: This method returning a path does not imply that a key has been written to disk already. This method only describes where it will be written to.
|
||||||
|
public func path<SecretType: Secret>(for secret: SecretType) -> String {
|
||||||
|
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||||
|
return directory.appending("/").appending("\(minimalHex).pub")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,30 +1,41 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
import Combine
|
||||||
|
|
||||||
|
/// A "Store Store," which holds a list of type-erased stores.
|
||||||
public class SecretStoreList: ObservableObject {
|
public class SecretStoreList: ObservableObject {
|
||||||
|
|
||||||
|
/// The Stores managed by the SecretStoreList.
|
||||||
@Published public var stores: [AnySecretStore] = []
|
@Published public var stores: [AnySecretStore] = []
|
||||||
|
/// A modifiable store, if one is available.
|
||||||
@Published public var modifiableStore: AnySecretStoreModifiable?
|
@Published public var modifiableStore: AnySecretStoreModifiable?
|
||||||
fileprivate var sinks: [AnyCancellable] = []
|
private var sinks: [AnyCancellable] = []
|
||||||
|
|
||||||
|
/// Initializes a SecretStoreList.
|
||||||
public init() {
|
public init() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds a non-type-erased SecretStore to the list.
|
||||||
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
|
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
|
||||||
addInternal(store: AnySecretStore(store))
|
addInternal(store: AnySecretStore(store))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds a non-type-erased modifiable SecretStore.
|
||||||
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
|
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
|
||||||
let modifiable = AnySecretStoreModifiable(modifiable: store)
|
let modifiable = AnySecretStoreModifiable(modifiable: store)
|
||||||
modifiableStore = modifiable
|
modifiableStore = modifiable
|
||||||
addInternal(store: modifiable)
|
addInternal(store: modifiable)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A boolean describing whether there are any Stores available.
|
||||||
|
public var anyAvailable: Bool {
|
||||||
|
stores.reduce(false, { $0 || $1.isAvailable })
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SecretStoreList {
|
extension SecretStoreList {
|
||||||
|
|
||||||
fileprivate func addInternal(store: AnySecretStore) {
|
private func addInternal(store: AnySecretStore) {
|
||||||
stores.append(store)
|
stores.append(store)
|
||||||
let sink = store.objectWillChange.sink {
|
let sink = store.objectWillChange.sink {
|
||||||
self.objectWillChange.send()
|
self.objectWillChange.send()
|
33
Sources/Packages/Sources/SecretKit/Types/Secret.swift
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// The base protocol for describing a Secret
|
||||||
|
public protocol Secret: Identifiable, Hashable {
|
||||||
|
|
||||||
|
/// A user-facing string identifying the Secret.
|
||||||
|
var name: String { get }
|
||||||
|
/// The algorithm this secret uses.
|
||||||
|
var algorithm: Algorithm { get }
|
||||||
|
/// The key size for the secret.
|
||||||
|
var keySize: Int { get }
|
||||||
|
/// The public key data for the secret.
|
||||||
|
var publicKey: Data { get }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type of algorithm the Secret uses. Currently, only elliptic curve algorithms are supported.
|
||||||
|
public enum Algorithm: Hashable {
|
||||||
|
|
||||||
|
case ellipticCurve
|
||||||
|
|
||||||
|
/// Initializes the Algorithm with a secAttr representation of an algorithm.
|
||||||
|
/// - Parameter secAttr: the secAttr, represented as an NSNumber.
|
||||||
|
public init(secAttr: NSNumber) {
|
||||||
|
let secAttrString = secAttr.stringValue as CFString
|
||||||
|
switch secAttrString {
|
||||||
|
case kSecAttrKeyTypeEC:
|
||||||
|
self = .ellipticCurve
|
||||||
|
default:
|
||||||
|
fatalError()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
64
Sources/Packages/Sources/SecretKit/Types/SecretStore.swift
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import Foundation
|
||||||
|
import Combine
|
||||||
|
|
||||||
|
/// Manages access to Secrets, and performs signature operations on data using those Secrets.
|
||||||
|
public protocol SecretStore: ObservableObject, Identifiable {
|
||||||
|
|
||||||
|
associatedtype SecretType: Secret
|
||||||
|
|
||||||
|
/// A boolean indicating whether or not the store is available.
|
||||||
|
var isAvailable: Bool { get }
|
||||||
|
/// A unique identifier for the store.
|
||||||
|
var id: UUID { get }
|
||||||
|
/// A user-facing name for the store.
|
||||||
|
var name: String { get }
|
||||||
|
/// The secrets the store manages.
|
||||||
|
var secrets: [SecretType] { get }
|
||||||
|
|
||||||
|
/// Signs a data payload with a specified Secret.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: The data to sign.
|
||||||
|
/// - secret: The ``Secret`` to sign with.
|
||||||
|
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
|
||||||
|
/// - Returns: A ``SignedData`` object, containing the signature and metadata about the signature process.
|
||||||
|
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData
|
||||||
|
|
||||||
|
/// Persists user authorization for access to a secret.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The ``Secret`` to persist the authorization for.
|
||||||
|
/// - duration: The duration that the authorization should persist for.
|
||||||
|
/// - Note: This is used for temporarily unlocking access to a secret which would otherwise require authentication every single use. This is useful for situations where the user anticipates several rapid accesses to a authorization-guarded secret.
|
||||||
|
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) throws
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A SecretStore that the Secretive admin app can modify.
|
||||||
|
public protocol SecretStoreModifiable: SecretStore {
|
||||||
|
|
||||||
|
/// Creates a new ``Secret`` in the store.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - name: The user-facing name for the ``Secret``.
|
||||||
|
/// - requiresAuthentication: A boolean indicating whether or not the user will be required to authenticate before performing signature operations with the secret.
|
||||||
|
func create(name: String, requiresAuthentication: Bool) throws
|
||||||
|
|
||||||
|
/// Deletes a Secret in the store.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The ``Secret`` to delete.
|
||||||
|
func delete(secret: SecretType) throws
|
||||||
|
|
||||||
|
/// Updates the name of a Secret in the store.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The ``Secret`` to update.
|
||||||
|
/// - name: The new name for the Secret.
|
||||||
|
func update(secret: SecretType, name: String) throws
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension NSNotification.Name {
|
||||||
|
|
||||||
|
// Distributed notification that keys were modified out of process (ie, that the management tool added/removed secrets)
|
||||||
|
public static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
|
||||||
|
// Internal notification that keys were reloaded from the backing store.
|
||||||
|
public static let secretStoreReloaded = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.reloaded")
|
||||||
|
|
||||||
|
}
|
20
Sources/Packages/Sources/SecretKit/Types/SignedData.swift
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Describes the output of a sign request.
|
||||||
|
public struct SignedData {
|
||||||
|
|
||||||
|
/// The signed data.
|
||||||
|
public let data: Data
|
||||||
|
/// A boolean describing whether authentication was required during the signature process.
|
||||||
|
public let requiredAuthentication: Bool
|
||||||
|
|
||||||
|
/// Initializes a new SignedData.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: The signed data.
|
||||||
|
/// - requiredAuthentication: A boolean describing whether authentication was required during the signature process.
|
||||||
|
public init(data: Data, requiredAuthentication: Bool) {
|
||||||
|
self.data = data
|
||||||
|
self.requiredAuthentication = requiredAuthentication
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,76 @@
|
|||||||
|
import Foundation
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
/// Describes the chain of applications that requested a signature operation.
|
||||||
|
public struct SigningRequestProvenance: Equatable {
|
||||||
|
|
||||||
|
/// A list of processes involved in the request.
|
||||||
|
/// - Note: A chain will typically consist of many elements even for a simple request. For example, running `git fetch` in Terminal.app would generate a request chain of `ssh` -> `git` -> `zsh` -> `login` -> `Terminal.app`
|
||||||
|
public var chain: [Process]
|
||||||
|
public init(root: Process) {
|
||||||
|
self.chain = [root]
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SigningRequestProvenance {
|
||||||
|
|
||||||
|
/// The `Process` which initiated the signing request.
|
||||||
|
public var origin: Process {
|
||||||
|
chain.last!
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A boolean describing whether all processes in the request chain had a valid code signature.
|
||||||
|
public var intact: Bool {
|
||||||
|
chain.allSatisfy { $0.validSignature }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SigningRequestProvenance {
|
||||||
|
|
||||||
|
/// Describes a process in a `SigningRequestProvenance` chain.
|
||||||
|
public struct Process: Equatable {
|
||||||
|
|
||||||
|
/// The pid of the process.
|
||||||
|
public let pid: Int32
|
||||||
|
/// A user-facing name for the process.
|
||||||
|
public let processName: String
|
||||||
|
/// A user-facing name for the application, if one exists.
|
||||||
|
public let appName: String?
|
||||||
|
/// An icon representation of the application, if one exists.
|
||||||
|
public let iconURL: URL?
|
||||||
|
/// The path the process exists at.
|
||||||
|
public let path: String
|
||||||
|
/// A boolean describing whether or not the process has a valid code signature.
|
||||||
|
public let validSignature: Bool
|
||||||
|
/// The pid of the process's parent.
|
||||||
|
public let parentPID: Int32?
|
||||||
|
|
||||||
|
/// Initializes a Process.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - pid: The pid of the process.
|
||||||
|
/// - processName: A user-facing name for the process.
|
||||||
|
/// - appName: A user-facing name for the application, if one exists.
|
||||||
|
/// - iconURL: An icon representation of the application, if one exists.
|
||||||
|
/// - path: The path the process exists at.
|
||||||
|
/// - validSignature: A boolean describing whether or not the process has a valid code signature.
|
||||||
|
/// - parentPID: The pid of the process's parent.
|
||||||
|
public init(pid: Int32, processName: String, appName: String?, iconURL: URL?, path: String, validSignature: Bool, parentPID: Int32?) {
|
||||||
|
self.pid = pid
|
||||||
|
self.processName = processName
|
||||||
|
self.appName = appName
|
||||||
|
self.iconURL = iconURL
|
||||||
|
self.path = path
|
||||||
|
self.validSignature = validSignature
|
||||||
|
self.parentPID = parentPID
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The best user-facing name to display for the process.
|
||||||
|
public var displayName: String {
|
||||||
|
appName ?? processName
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
# ``SecureEnclaveSecretKit``
|
||||||
|
|
||||||
|
SecureEnclaveSecretKit contains implementations of SecretKit protocols backed by the Secure Enclave.
|
@ -0,0 +1,14 @@
|
|||||||
|
# ``SecureEnclaveSecretKit/SecureEnclave``
|
||||||
|
|
||||||
|
## Topics
|
||||||
|
|
||||||
|
### Implementations
|
||||||
|
|
||||||
|
- ``Secret``
|
||||||
|
- ``Store``
|
||||||
|
|
||||||
|
### Errors
|
||||||
|
|
||||||
|
- ``KeychainError``
|
||||||
|
- ``SigningError``
|
||||||
|
- ``SecurityError``
|
@ -0,0 +1,2 @@
|
|||||||
|
/// Namespace for the Secure Enclave implementations.
|
||||||
|
public enum SecureEnclave {}
|
@ -1,8 +1,10 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
import Combine
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
extension SecureEnclave {
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
/// An implementation of Secret backed by the Secure Enclave.
|
||||||
public struct Secret: SecretKit.Secret {
|
public struct Secret: SecretKit.Secret {
|
||||||
|
|
||||||
public let id: Data
|
public let id: Data
|
@ -0,0 +1,295 @@
|
|||||||
|
import Foundation
|
||||||
|
import Security
|
||||||
|
import CryptoTokenKit
|
||||||
|
import LocalAuthentication
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
/// An implementation of Store backed by the Secure Enclave.
|
||||||
|
public class Store: SecretStoreModifiable {
|
||||||
|
|
||||||
|
public var isAvailable: Bool {
|
||||||
|
// For some reason, as of build time, CryptoKit.SecureEnclave.isAvailable always returns false
|
||||||
|
// error msg "Received error sending GET UNIQUE DEVICE command"
|
||||||
|
// Verify it with TKTokenWatcher manually.
|
||||||
|
TKTokenWatcher().tokenIDs.contains("com.apple.setoken")
|
||||||
|
}
|
||||||
|
public let id = UUID()
|
||||||
|
public let name = NSLocalizedString("Secure Enclave", comment: "Secure Enclave")
|
||||||
|
@Published public private(set) var secrets: [Secret] = []
|
||||||
|
|
||||||
|
private var persistedAuthenticationContexts: [Secret: PersistentAuthenticationContext] = [:]
|
||||||
|
|
||||||
|
/// Initializes a Store.
|
||||||
|
public init() {
|
||||||
|
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
|
||||||
|
self.reloadSecrets(notifyAgent: false)
|
||||||
|
}
|
||||||
|
loadSecrets()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Public API
|
||||||
|
|
||||||
|
public func create(name: String, requiresAuthentication: Bool) throws {
|
||||||
|
var accessError: SecurityError?
|
||||||
|
let flags: SecAccessControlCreateFlags
|
||||||
|
if requiresAuthentication {
|
||||||
|
flags = [.privateKeyUsage, .userPresence]
|
||||||
|
} else {
|
||||||
|
flags = .privateKeyUsage
|
||||||
|
}
|
||||||
|
let access =
|
||||||
|
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
||||||
|
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||||
|
flags,
|
||||||
|
&accessError) as Any
|
||||||
|
if let error = accessError {
|
||||||
|
throw error.takeRetainedValue() as Error
|
||||||
|
}
|
||||||
|
|
||||||
|
let attributes = [
|
||||||
|
kSecAttrLabel: name,
|
||||||
|
kSecAttrKeyType: Constants.keyType,
|
||||||
|
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
||||||
|
kSecAttrApplicationTag: Constants.keyTag,
|
||||||
|
kSecPrivateKeyAttrs: [
|
||||||
|
kSecAttrIsPermanent: true,
|
||||||
|
kSecAttrAccessControl: access
|
||||||
|
]
|
||||||
|
] as CFDictionary
|
||||||
|
|
||||||
|
var createKeyError: SecurityError?
|
||||||
|
let keypair = SecKeyCreateRandomKey(attributes, &createKeyError)
|
||||||
|
if let error = createKeyError {
|
||||||
|
throw error.takeRetainedValue() as Error
|
||||||
|
}
|
||||||
|
guard let keypair = keypair, let publicKey = SecKeyCopyPublicKey(keypair) else {
|
||||||
|
throw KeychainError(statusCode: nil)
|
||||||
|
}
|
||||||
|
try savePublicKey(publicKey, name: name)
|
||||||
|
reloadSecrets()
|
||||||
|
}
|
||||||
|
|
||||||
|
public func delete(secret: Secret) throws {
|
||||||
|
let deleteAttributes = [
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrApplicationLabel: secret.id as CFData
|
||||||
|
] as CFDictionary
|
||||||
|
let status = SecItemDelete(deleteAttributes)
|
||||||
|
if status != errSecSuccess {
|
||||||
|
throw KeychainError(statusCode: status)
|
||||||
|
}
|
||||||
|
reloadSecrets()
|
||||||
|
}
|
||||||
|
|
||||||
|
public func update(secret: Secret, name: String) throws {
|
||||||
|
let updateQuery = [
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrApplicationLabel: secret.id as CFData
|
||||||
|
] as CFDictionary
|
||||||
|
|
||||||
|
let updatedAttributes = [
|
||||||
|
kSecAttrLabel: name,
|
||||||
|
] as CFDictionary
|
||||||
|
|
||||||
|
let status = SecItemUpdate(updateQuery, updatedAttributes)
|
||||||
|
if status != errSecSuccess {
|
||||||
|
throw KeychainError(statusCode: status)
|
||||||
|
}
|
||||||
|
reloadSecrets()
|
||||||
|
}
|
||||||
|
|
||||||
|
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||||
|
let context: LAContext
|
||||||
|
if let existing = persistedAuthenticationContexts[secret], existing.valid {
|
||||||
|
context = existing.context
|
||||||
|
} else {
|
||||||
|
let newContext = LAContext()
|
||||||
|
newContext.localizedCancelTitle = "Deny"
|
||||||
|
context = newContext
|
||||||
|
}
|
||||||
|
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
||||||
|
let attributes = [
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||||
|
kSecAttrApplicationLabel: secret.id as CFData,
|
||||||
|
kSecAttrKeyType: Constants.keyType,
|
||||||
|
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
||||||
|
kSecAttrApplicationTag: Constants.keyTag,
|
||||||
|
kSecUseAuthenticationContext: context,
|
||||||
|
kSecReturnRef: true
|
||||||
|
] as CFDictionary
|
||||||
|
var untyped: CFTypeRef?
|
||||||
|
let status = SecItemCopyMatching(attributes, &untyped)
|
||||||
|
if status != errSecSuccess {
|
||||||
|
throw KeychainError(statusCode: status)
|
||||||
|
}
|
||||||
|
guard let untypedSafe = untyped else {
|
||||||
|
throw KeychainError(statusCode: errSecSuccess)
|
||||||
|
}
|
||||||
|
let key = untypedSafe as! SecKey
|
||||||
|
var signError: SecurityError?
|
||||||
|
|
||||||
|
let signingStartTime = Date()
|
||||||
|
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
||||||
|
throw SigningError(error: signError)
|
||||||
|
}
|
||||||
|
let signatureDuration = Date().timeIntervalSince(signingStartTime)
|
||||||
|
// Hack to determine if the user had to authenticate to sign.
|
||||||
|
// Since there's now way to inspect SecAccessControl to determine (afaict).
|
||||||
|
let requiredAuthentication = signatureDuration > Constants.unauthenticatedThreshold
|
||||||
|
|
||||||
|
return SignedData(data: signature as Data, requiredAuthentication: requiredAuthentication)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) throws {
|
||||||
|
let newContext = LAContext()
|
||||||
|
newContext.touchIDAuthenticationAllowableReuseDuration = duration
|
||||||
|
newContext.localizedCancelTitle = "Deny"
|
||||||
|
|
||||||
|
let formatter = DateComponentsFormatter()
|
||||||
|
formatter.unitsStyle = .spellOut
|
||||||
|
formatter.allowedUnits = [.hour, .minute, .day]
|
||||||
|
|
||||||
|
if let durationString = formatter.string(from: duration) {
|
||||||
|
newContext.localizedReason = "unlock secret \"\(secret.name)\" for \(durationString)"
|
||||||
|
} else {
|
||||||
|
newContext.localizedReason = "unlock secret \"\(secret.name)\""
|
||||||
|
}
|
||||||
|
newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: newContext.localizedReason) { [weak self] success, _ in
|
||||||
|
guard success else { return }
|
||||||
|
let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration)
|
||||||
|
self?.persistedAuthenticationContexts[secret] = context
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SecureEnclave.Store {
|
||||||
|
|
||||||
|
/// Reloads all secrets from the store.
|
||||||
|
/// - Parameter notifyAgent: A boolean indicating whether a distributed notification should be posted, notifying other processes (ie, the SecretAgent) to reload their stores as well.
|
||||||
|
private func reloadSecrets(notifyAgent: Bool = true) {
|
||||||
|
secrets.removeAll()
|
||||||
|
loadSecrets()
|
||||||
|
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||||
|
if notifyAgent {
|
||||||
|
DistributedNotificationCenter.default().postNotificationName(.secretStoreUpdated, object: nil, deliverImmediately: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads all secrets from the store.
|
||||||
|
private func loadSecrets() {
|
||||||
|
let attributes = [
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||||
|
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||||
|
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
||||||
|
kSecReturnRef: true,
|
||||||
|
kSecMatchLimit: kSecMatchLimitAll,
|
||||||
|
kSecReturnAttributes: true
|
||||||
|
] as CFDictionary
|
||||||
|
var untyped: CFTypeRef?
|
||||||
|
SecItemCopyMatching(attributes, &untyped)
|
||||||
|
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||||
|
let wrapped: [SecureEnclave.Secret] = typed.map {
|
||||||
|
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
||||||
|
let id = $0[kSecAttrApplicationLabel] as! Data
|
||||||
|
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
||||||
|
let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any]
|
||||||
|
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
||||||
|
return SecureEnclave.Secret(id: id, name: name, publicKey: publicKey)
|
||||||
|
}
|
||||||
|
secrets.append(contentsOf: wrapped)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves a public key.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - publicKey: The public key to save.
|
||||||
|
/// - name: A user-facing name for the key.
|
||||||
|
private func savePublicKey(_ publicKey: SecKey, name: String) throws {
|
||||||
|
let attributes = [
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||||
|
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
||||||
|
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||||
|
kSecValueRef: publicKey,
|
||||||
|
kSecAttrIsPermanent: true,
|
||||||
|
kSecReturnData: true,
|
||||||
|
kSecAttrLabel: name
|
||||||
|
] as CFDictionary
|
||||||
|
let status = SecItemAdd(attributes, nil)
|
||||||
|
if status != errSecSuccess {
|
||||||
|
throw SecureEnclave.KeychainError(statusCode: status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
/// A wrapper around an error code reported by a Keychain API.
|
||||||
|
public struct KeychainError: Error {
|
||||||
|
/// The status code involved, if one was reported.
|
||||||
|
public let statusCode: OSStatus?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A signing-related error.
|
||||||
|
public struct SigningError: Error {
|
||||||
|
/// The underlying error reported by the API, if one was returned.
|
||||||
|
public let error: SecurityError?
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
public typealias SecurityError = Unmanaged<CFError>
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
|
||||||
|
static let keyType = kSecAttrKeyTypeECSECPrimeRandom
|
||||||
|
static let unauthenticatedThreshold: TimeInterval = 0.05
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SecureEnclave {
|
||||||
|
|
||||||
|
/// A context describing a persisted authentication.
|
||||||
|
private struct PersistentAuthenticationContext {
|
||||||
|
|
||||||
|
/// The Secret to persist authentication for.
|
||||||
|
let secret: Secret
|
||||||
|
/// The LAContext used to authorize the persistent context.
|
||||||
|
let context: LAContext
|
||||||
|
/// An expiration date for the context.
|
||||||
|
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
|
||||||
|
let expiration: UInt64
|
||||||
|
|
||||||
|
/// Initializes a context.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The Secret to persist authentication for.
|
||||||
|
/// - context: The LAContext used to authorize the persistent context.
|
||||||
|
/// - duration: The duration of the authorization context, in seconds.
|
||||||
|
init(secret: Secret, context: LAContext, duration: TimeInterval) {
|
||||||
|
self.secret = secret
|
||||||
|
self.context = context
|
||||||
|
let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: .nanoseconds).value
|
||||||
|
self.expiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A boolean describing whether or not the context is still valid.
|
||||||
|
var valid: Bool {
|
||||||
|
clock_gettime_nsec_np(CLOCK_MONOTONIC) < expiration
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
# ``SmartCardSecretKit``
|
||||||
|
|
||||||
|
SmartCardSecretKit contains implementations of SecretKit protocols backed by a Smart Card.
|
@ -0,0 +1,14 @@
|
|||||||
|
# ``SmartCardSecretKit/SmartCard``
|
||||||
|
|
||||||
|
## Topics
|
||||||
|
|
||||||
|
### Implementations
|
||||||
|
|
||||||
|
- ``Secret``
|
||||||
|
- ``Store``
|
||||||
|
|
||||||
|
### Errors
|
||||||
|
|
||||||
|
- ``KeychainError``
|
||||||
|
- ``SigningError``
|
||||||
|
- ``SecurityError``
|
@ -0,0 +1,2 @@
|
|||||||
|
/// Namespace for the Smart Card implementations.
|
||||||
|
public enum SmartCard {}
|
@ -1,8 +1,10 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Combine
|
import Combine
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
extension SmartCard {
|
extension SmartCard {
|
||||||
|
|
||||||
|
/// An implementation of Secret backed by a Smart Card.
|
||||||
public struct Secret: SecretKit.Secret {
|
public struct Secret: SecretKit.Secret {
|
||||||
|
|
||||||
public let id: Data
|
public let id: Data
|
@ -1,26 +1,28 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Security
|
import Security
|
||||||
import CryptoTokenKit
|
import CryptoTokenKit
|
||||||
|
import LocalAuthentication
|
||||||
|
import SecretKit
|
||||||
|
|
||||||
// TODO: Might need to split this up into "sub-stores?"
|
|
||||||
// ie, each token has its own Store.
|
|
||||||
extension SmartCard {
|
extension SmartCard {
|
||||||
|
|
||||||
|
/// An implementation of Store backed by a Smart Card.
|
||||||
public class Store: SecretStore {
|
public class Store: SecretStore {
|
||||||
|
|
||||||
// TODO: Read actual smart card name, eg "YubiKey 5c"
|
|
||||||
@Published public var isAvailable: Bool = false
|
@Published public var isAvailable: Bool = false
|
||||||
public let id = UUID()
|
public let id = UUID()
|
||||||
public let name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
public private(set) var name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||||
@Published public fileprivate(set) var secrets: [Secret] = []
|
@Published public private(set) var secrets: [Secret] = []
|
||||||
fileprivate let watcher = TKTokenWatcher()
|
private let watcher = TKTokenWatcher()
|
||||||
fileprivate var tokenID: String?
|
private var tokenID: String?
|
||||||
|
|
||||||
|
/// Initializes a Store.
|
||||||
public init() {
|
public init() {
|
||||||
tokenID = watcher.tokenIDs.filter { !$0.contains("setoken") }.first
|
tokenID = watcher.nonSecureEnclaveTokens.first
|
||||||
watcher.setInsertionHandler { string in
|
watcher.setInsertionHandler { string in
|
||||||
guard self.tokenID == nil else { return }
|
guard self.tokenID == nil else { return }
|
||||||
guard !string.contains("setoken") else { return }
|
guard !string.contains("setoken") else { return }
|
||||||
|
|
||||||
self.tokenID = string
|
self.tokenID = string
|
||||||
self.reloadSecrets()
|
self.reloadSecrets()
|
||||||
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
|
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
|
||||||
@ -42,15 +44,19 @@ extension SmartCard {
|
|||||||
fatalError("Keys must be deleted on the smart card.")
|
fatalError("Keys must be deleted on the smart card.")
|
||||||
}
|
}
|
||||||
|
|
||||||
public func sign(data: Data, with secret: SecretType) throws -> Data {
|
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||||
guard let tokenID = tokenID else { fatalError() }
|
guard let tokenID = tokenID else { fatalError() }
|
||||||
|
let context = LAContext()
|
||||||
|
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
||||||
|
context.localizedCancelTitle = "Deny"
|
||||||
let attributes = [
|
let attributes = [
|
||||||
kSecClass: kSecClassKey,
|
kSecClass: kSecClassKey,
|
||||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||||
kSecAttrApplicationLabel: secret.id as CFData,
|
kSecAttrApplicationLabel: secret.id as CFData,
|
||||||
kSecAttrTokenID: tokenID,
|
kSecAttrTokenID: tokenID,
|
||||||
|
kSecUseAuthenticationContext: context,
|
||||||
kSecReturnRef: true
|
kSecReturnRef: true
|
||||||
] as CFDictionary
|
] as CFDictionary
|
||||||
var untyped: CFTypeRef?
|
var untyped: CFTypeRef?
|
||||||
let status = SecItemCopyMatching(attributes, &untyped)
|
let status = SecItemCopyMatching(attributes, &untyped)
|
||||||
if status != errSecSuccess {
|
if status != errSecSuccess {
|
||||||
@ -73,7 +79,10 @@ extension SmartCard {
|
|||||||
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm, data as CFData, &signError) else {
|
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm, data as CFData, &signError) else {
|
||||||
throw SigningError(error: signError)
|
throw SigningError(error: signError)
|
||||||
}
|
}
|
||||||
return signature as Data
|
return SignedData(data: signature as Data, requiredAuthentication: false)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: SmartCard.Secret, forDuration: TimeInterval) throws {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -82,12 +91,15 @@ extension SmartCard {
|
|||||||
|
|
||||||
extension SmartCard.Store {
|
extension SmartCard.Store {
|
||||||
|
|
||||||
fileprivate func smartcardRemoved(for tokenID: String? = nil) {
|
/// Resets the token ID and reloads secrets.
|
||||||
|
/// - Parameter tokenID: The ID of the token that was removed.
|
||||||
|
private func smartcardRemoved(for tokenID: String? = nil) {
|
||||||
self.tokenID = nil
|
self.tokenID = nil
|
||||||
reloadSecrets()
|
reloadSecrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func reloadSecrets() {
|
/// Reloads all secrets from the store.
|
||||||
|
private func reloadSecrets() {
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.isAvailable = self.tokenID != nil
|
self.isAvailable = self.tokenID != nil
|
||||||
self.secrets.removeAll()
|
self.secrets.removeAll()
|
||||||
@ -95,8 +107,27 @@ extension SmartCard.Store {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func loadSecrets() {
|
/// Loads all secrets from the store.
|
||||||
|
private func loadSecrets() {
|
||||||
guard let tokenID = tokenID else { return }
|
guard let tokenID = tokenID else { return }
|
||||||
|
|
||||||
|
let fallbackName = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||||
|
if #available(macOS 12.0, *) {
|
||||||
|
if let driverName = watcher.tokenInfo(forTokenID: tokenID)?.driverName {
|
||||||
|
name = driverName
|
||||||
|
} else {
|
||||||
|
name = fallbackName
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Hack to read name if there's only one smart card
|
||||||
|
let slotNames = TKSmartCardSlotManager().slotNames
|
||||||
|
if watcher.nonSecureEnclaveTokens.count == 1 && slotNames.count == 1 {
|
||||||
|
name = slotNames.first!
|
||||||
|
} else {
|
||||||
|
name = fallbackName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let attributes = [
|
let attributes = [
|
||||||
kSecClass: kSecClassKey,
|
kSecClass: kSecClassKey,
|
||||||
kSecAttrTokenID: tokenID,
|
kSecAttrTokenID: tokenID,
|
||||||
@ -104,7 +135,7 @@ extension SmartCard.Store {
|
|||||||
kSecReturnRef: true,
|
kSecReturnRef: true,
|
||||||
kSecMatchLimit: kSecMatchLimitAll,
|
kSecMatchLimit: kSecMatchLimitAll,
|
||||||
kSecReturnAttributes: true
|
kSecReturnAttributes: true
|
||||||
] as CFDictionary
|
] as CFDictionary
|
||||||
var untyped: CFTypeRef?
|
var untyped: CFTypeRef?
|
||||||
SecItemCopyMatching(attributes, &untyped)
|
SecItemCopyMatching(attributes, &untyped)
|
||||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||||
@ -124,13 +155,26 @@ extension SmartCard.Store {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extension TKTokenWatcher {
|
||||||
|
|
||||||
|
/// All available tokens, excluding the Secure Enclave.
|
||||||
|
fileprivate var nonSecureEnclaveTokens: [String] {
|
||||||
|
tokenIDs.filter { !$0.contains("setoken") }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
extension SmartCard {
|
extension SmartCard {
|
||||||
|
|
||||||
|
/// A wrapper around an error code reported by a Keychain API.
|
||||||
public struct KeychainError: Error {
|
public struct KeychainError: Error {
|
||||||
|
/// The status code involved.
|
||||||
public let statusCode: OSStatus
|
public let statusCode: OSStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A signing-related error.
|
||||||
public struct SigningError: Error {
|
public struct SigningError: Error {
|
||||||
|
/// The underlying error reported by the API, if one was returned.
|
||||||
public let error: SecurityError?
|
public let error: SecurityError?
|
||||||
}
|
}
|
||||||
|
|
104
Sources/Packages/Tests/BriefTests/ReleaseParsingTests.swift
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import Brief
|
||||||
|
|
||||||
|
class ReleaseParsingTests: XCTestCase {
|
||||||
|
|
||||||
|
func testNonCritical() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release")
|
||||||
|
XCTAssert(release.critical == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCritical() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||||
|
XCTAssert(release.critical == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOSMissing() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||||
|
XCTAssert(release.minimumOSVersion == SemVer("11.0.0"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOSPresentWithContentBelow() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update ##Minimum macOS Version\n1.2.3\nBuild info")
|
||||||
|
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOSPresentAtEnd() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
||||||
|
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOSWithMacOSPrefix() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: macOS 1.2.3")
|
||||||
|
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOSGreaterThanMinimum() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
||||||
|
XCTAssert(release.minimumOSVersion < SemVer("11.0.0"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOSEqualToMinimum() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 11.2.3")
|
||||||
|
XCTAssert(release.minimumOSVersion <= SemVer("11.2.3"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOSLessThanMinimum() {
|
||||||
|
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
|
||||||
|
XCTAssert(release.minimumOSVersion > SemVer("1.0.0"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testGreatestSelectedIfOldPatchIsPublishedLater() {
|
||||||
|
// If 2.x.x series has been published, and a patch for 1.x.x is issued
|
||||||
|
// 2.x.x should still be selected if user can run it.
|
||||||
|
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("2.2.3"), currentVersion: SemVer("1.0.0"))
|
||||||
|
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3")
|
||||||
|
let releases = [
|
||||||
|
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"),
|
||||||
|
Release(name: "1.0.1", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Bug fixes Minimum macOS Version: 1.2.3"),
|
||||||
|
two,
|
||||||
|
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
||||||
|
]
|
||||||
|
|
||||||
|
let expectation = XCTestExpectation()
|
||||||
|
updater.evaluate(releases: releases)
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
XCTAssert(updater.update == two)
|
||||||
|
expectation.fulfill()
|
||||||
|
}
|
||||||
|
wait(for: [expectation], timeout: 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testLatestVersionIsRunnable() {
|
||||||
|
// If the 2.x.x series has been published but the user can't run it
|
||||||
|
// the last version the user can run should be selected.
|
||||||
|
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("1.2.3"), currentVersion: SemVer("1.0.0"))
|
||||||
|
let oneOhTwo = Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3")
|
||||||
|
let releases = [
|
||||||
|
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"),
|
||||||
|
Release(name: "1.0.1", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Bug fixes Minimum macOS Version: 1.2.3"),
|
||||||
|
Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3"),
|
||||||
|
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
||||||
|
]
|
||||||
|
let expectation = XCTestExpectation()
|
||||||
|
updater.evaluate(releases: releases)
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
XCTAssert(updater.update == oneOhTwo)
|
||||||
|
expectation.fulfill()
|
||||||
|
}
|
||||||
|
wait(for: [expectation], timeout: 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSorting() {
|
||||||
|
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available!")
|
||||||
|
let releases = [
|
||||||
|
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release"),
|
||||||
|
Release(name: "1.0.1", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Bug fixes"),
|
||||||
|
two,
|
||||||
|
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch!"),
|
||||||
|
]
|
||||||
|
let sorted = releases.sorted().reversed().first
|
||||||
|
XCTAssert(sorted == two)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
51
Sources/Packages/Tests/BriefTests/SemVerTests.swift
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import Brief
|
||||||
|
|
||||||
|
class SemVerTests: XCTestCase {
|
||||||
|
|
||||||
|
func testEqual() {
|
||||||
|
let current = SemVer("1.0.2")
|
||||||
|
let old = SemVer("1.0.2")
|
||||||
|
XCTAssert(!(current > old))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testPatchGreaterButMinorLess() {
|
||||||
|
let current = SemVer("1.1.0")
|
||||||
|
let old = SemVer("1.0.2")
|
||||||
|
XCTAssert(current > old)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMajorSameMinorGreater() {
|
||||||
|
let current = SemVer("1.0.2")
|
||||||
|
let new = SemVer("1.0.3")
|
||||||
|
XCTAssert(current < new)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMajorGreaterMinorLesser() {
|
||||||
|
let current = SemVer("1.0.2")
|
||||||
|
let new = SemVer("2.0.0")
|
||||||
|
XCTAssert(current < new)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testRegularParsing() {
|
||||||
|
let current = SemVer("1.0.2")
|
||||||
|
XCTAssert(current.versionNumbers == [1, 0, 2])
|
||||||
|
}
|
||||||
|
|
||||||
|
func testNoPatch() {
|
||||||
|
let current = SemVer("1.1")
|
||||||
|
XCTAssert(current.versionNumbers == [1, 1, 0])
|
||||||
|
}
|
||||||
|
|
||||||
|
func testGarbage() {
|
||||||
|
let current = SemVer("Test")
|
||||||
|
XCTAssert(current.versionNumbers == [0, 0, 0])
|
||||||
|
}
|
||||||
|
|
||||||
|
func testBeta() {
|
||||||
|
let current = SemVer("1.0.2")
|
||||||
|
let new = SemVer("1.1.0_beta1")
|
||||||
|
XCTAssert(current < new)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
169
Sources/Packages/Tests/SecretAgentKitTests/AgentTests.swift
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
import CryptoKit
|
||||||
|
@testable import SecretKit
|
||||||
|
@testable import SecretAgentKit
|
||||||
|
|
||||||
|
class AgentTests: XCTestCase {
|
||||||
|
|
||||||
|
let stubWriter = StubFileHandleWriter()
|
||||||
|
|
||||||
|
// MARK: Identity Listing
|
||||||
|
|
||||||
|
func testEmptyStores() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
|
||||||
|
let agent = Agent(storeList: SecretStoreList())
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testIdentitiesList() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
|
||||||
|
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
|
let agent = Agent(storeList: list)
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesMultiple)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Signatures
|
||||||
|
|
||||||
|
func testNoMatchingIdentities() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignatureWithNoneMatching)
|
||||||
|
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
|
let agent = Agent(storeList: list)
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
// XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSignature() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||||
|
let requestReader = OpenSSHReader(data: Constants.Requests.requestSignature[5...])
|
||||||
|
_ = requestReader.readNextChunk()
|
||||||
|
let dataToSign = requestReader.readNextChunk()
|
||||||
|
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
|
let agent = Agent(storeList: list)
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
let outer = OpenSSHReader(data: stubWriter.data[5...])
|
||||||
|
let payload = outer.readNextChunk()
|
||||||
|
let inner = OpenSSHReader(data: payload)
|
||||||
|
_ = inner.readNextChunk()
|
||||||
|
let signedData = inner.readNextChunk()
|
||||||
|
let rsData = OpenSSHReader(data: signedData)
|
||||||
|
var r = rsData.readNextChunk()
|
||||||
|
var s = rsData.readNextChunk()
|
||||||
|
// This is fine IRL, but it freaks out CryptoKit
|
||||||
|
if r[0] == 0 {
|
||||||
|
r.removeFirst()
|
||||||
|
}
|
||||||
|
if s[0] == 0 {
|
||||||
|
s.removeFirst()
|
||||||
|
}
|
||||||
|
var rs = r
|
||||||
|
rs.append(s)
|
||||||
|
let signature = try! P256.Signing.ECDSASignature(rawRepresentation: rs)
|
||||||
|
let valid = try! P256.Signing.PublicKey(x963Representation: Constants.Secrets.ecdsa256Secret.publicKey).isValidSignature(signature, for: dataToSign)
|
||||||
|
XCTAssertTrue(valid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Witness protocol
|
||||||
|
|
||||||
|
func testWitnessObjectionStopsRequest() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||||
|
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||||
|
let witness = StubWitness(speakNow: { _,_ in
|
||||||
|
return true
|
||||||
|
}, witness: { _, _ in })
|
||||||
|
let agent = Agent(storeList: list, witness: witness)
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testWitnessSignature() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||||
|
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||||
|
var witnessed = false
|
||||||
|
let witness = StubWitness(speakNow: { _, trace in
|
||||||
|
return false
|
||||||
|
}, witness: { _, trace in
|
||||||
|
witnessed = true
|
||||||
|
})
|
||||||
|
let agent = Agent(storeList: list, witness: witness)
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
XCTAssertTrue(witnessed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testRequestTracing() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||||
|
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||||
|
var speakNowTrace: SigningRequestProvenance! = nil
|
||||||
|
var witnessTrace: SigningRequestProvenance! = nil
|
||||||
|
let witness = StubWitness(speakNow: { _, trace in
|
||||||
|
speakNowTrace = trace
|
||||||
|
return false
|
||||||
|
}, witness: { _, trace in
|
||||||
|
witnessTrace = trace
|
||||||
|
})
|
||||||
|
let agent = Agent(storeList: list, witness: witness)
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
XCTAssertEqual(witnessTrace, speakNowTrace)
|
||||||
|
XCTAssertEqual(witnessTrace.origin.displayName, "Finder")
|
||||||
|
XCTAssertEqual(witnessTrace.origin.validSignature, true)
|
||||||
|
XCTAssertEqual(witnessTrace.origin.parentPID, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Exception Handling
|
||||||
|
|
||||||
|
func testSignatureException() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||||
|
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||||
|
let store = list.stores.first?.base as! Stub.Store
|
||||||
|
store.shouldThrow = true
|
||||||
|
let agent = Agent(storeList: list)
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Unsupported
|
||||||
|
|
||||||
|
func testUnhandledAdd() {
|
||||||
|
let stubReader = StubFileHandleReader(availableData: Constants.Requests.addIdentity)
|
||||||
|
let agent = Agent(storeList: SecretStoreList())
|
||||||
|
agent.handle(reader: stubReader, writer: stubWriter)
|
||||||
|
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension AgentTests {
|
||||||
|
|
||||||
|
func storeList(with secrets: [Stub.Secret]) -> SecretStoreList {
|
||||||
|
let store = Stub.Store()
|
||||||
|
store.secrets.append(contentsOf: secrets)
|
||||||
|
let storeList = SecretStoreList()
|
||||||
|
storeList.add(store: store)
|
||||||
|
return storeList
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
|
||||||
|
enum Requests {
|
||||||
|
static let requestIdentities = Data(base64Encoded: "AAAAAQs=")!
|
||||||
|
static let addIdentity = Data(base64Encoded: "AAAAARE=")!
|
||||||
|
static let requestSignatureWithNoneMatching = Data(base64Encoded: "AAABhA0AAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQAAAO8AAAAgbqmrqPUtJ8mmrtaSVexjMYyXWNqjHSnoto7zgv86xvcyAAAAA2dpdAAAAA5zc2gtY29ubmVjdGlvbgAAAAlwdWJsaWNrZXkBAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQAAAAA=")!
|
||||||
|
static let requestSignature = Data(base64Encoded: "AAABRA0AAABoAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKzOkUiVJEcACMtAd9X7xalbc0FYZyhbmv2dsWl4IP2GWIi+RcsaHQNw+nAIQ8CKEYmLnl0VLDp5Ef8KMhgIy08AAADPAAAAIBIFsbCZ4/dhBmLNGHm0GKj7EJ4N8k/jXRxlyg+LFIYzMgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSszpFIlSRHAAjLQHfV+8WpW3NBWGcoW5r9nbFpeCD9hliIvkXLGh0DcPpwCEPAihGJi55dFSw6eRH/CjIYCMtPAAAAAA==")!
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Responses {
|
||||||
|
static let requestIdentitiesEmpty = Data(base64Encoded: "AAAABQwAAAAA")!
|
||||||
|
static let requestIdentitiesMultiple = Data(base64Encoded: "AAABKwwAAAACAAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSszpFIlSRHAAjLQHfV+8WpW3NBWGcoW5r9nbFpeCD9hliIvkXLGh0DcPpwCEPAihGJi55dFSw6eRH/CjIYCMtPAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAACIAAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBLKSzA5q3jCb3q0JKigvcxfWVGrJ+bklpG0Zc9YzUwrbsh9SipvlSJi+sHQI+O0m88DOpRBAtuAHX60euD/Yv250tovN7/+MEFbXGZ/hLdd0BoFpWbLfJcQj806KJGlcDAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0")!
|
||||||
|
static let requestFailure = Data(base64Encoded: "AAAAAQU=")!
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Secrets {
|
||||||
|
static let ecdsa256Secret = Stub.Secret(keySize: 256, publicKey: Data(base64Encoded: "BKzOkUiVJEcACMtAd9X7xalbc0FYZyhbmv2dsWl4IP2GWIi+RcsaHQNw+nAIQ8CKEYmLnl0VLDp5Ef8KMhgIy08=")!, privateKey: Data(base64Encoded: "BKzOkUiVJEcACMtAd9X7xalbc0FYZyhbmv2dsWl4IP2GWIi+RcsaHQNw+nAIQ8CKEYmLnl0VLDp5Ef8KMhgIy09nw780wy/TSfUmzj15iJkV234AaCLNl+H8qFL6qK8VIg==")!)
|
||||||
|
static let ecdsa384Secret = Stub.Secret(keySize: 384, publicKey: Data(base64Encoded: "BLKSzA5q3jCb3q0JKigvcxfWVGrJ+bklpG0Zc9YzUwrbsh9SipvlSJi+sHQI+O0m88DOpRBAtuAHX60euD/Yv250tovN7/+MEFbXGZ/hLdd0BoFpWbLfJcQj806KJGlcDA==")!, privateKey: Data(base64Encoded: "BLKSzA5q3jCb3q0JKigvcxfWVGrJ+bklpG0Zc9YzUwrbsh9SipvlSJi+sHQI+O0m88DOpRBAtuAHX60euD/Yv250tovN7/+MEFbXGZ/hLdd0BoFpWbLfJcQj806KJGlcDHNapAOzrt9E+9QC4/KYoXS7Uw4pmdAz53uIj02tttiq3c0ZyIQ7XoscWWRqRrz8Kw==")!)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
import SecretAgentKit
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
struct StubFileHandleReader: FileHandleReader {
|
||||||
|
|
||||||
|
let availableData: Data
|
||||||
|
var fileDescriptor: Int32 {
|
||||||
|
NSWorkspace.shared.runningApplications.filter({ $0.localizedName == "Finder" }).first!.processIdentifier
|
||||||
|
}
|
||||||
|
var pidOfConnectedProcess: Int32 {
|
||||||
|
fileDescriptor
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
import Foundation
|
||||||
|
import SecretAgentKit
|
||||||
|
|
||||||
|
class StubFileHandleWriter: FileHandleWriter {
|
||||||
|
|
||||||
|
var data = Data()
|
||||||
|
|
||||||
|
func write(_ data: Data) {
|
||||||
|
self.data.append(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
117
Sources/Packages/Tests/SecretAgentKitTests/StubStore.swift
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
import Foundation
|
||||||
|
import SecretKit
|
||||||
|
import CryptoKit
|
||||||
|
|
||||||
|
struct Stub {}
|
||||||
|
|
||||||
|
extension Stub {
|
||||||
|
|
||||||
|
public class Store: SecretStore {
|
||||||
|
|
||||||
|
public let isAvailable = true
|
||||||
|
public let id = UUID()
|
||||||
|
public let name = "Stub"
|
||||||
|
public var secrets: [Secret] = []
|
||||||
|
public var shouldThrow = false
|
||||||
|
|
||||||
|
public init() {
|
||||||
|
// try! create(size: 256)
|
||||||
|
// try! create(size: 384)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func create(size: Int) throws {
|
||||||
|
let flags: SecAccessControlCreateFlags = []
|
||||||
|
let access =
|
||||||
|
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
||||||
|
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||||
|
flags,
|
||||||
|
nil) as Any
|
||||||
|
|
||||||
|
let attributes = [
|
||||||
|
kSecAttrLabel: name,
|
||||||
|
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
||||||
|
kSecAttrKeySizeInBits: size,
|
||||||
|
kSecPrivateKeyAttrs: [
|
||||||
|
kSecAttrIsPermanent: true,
|
||||||
|
kSecAttrAccessControl: access
|
||||||
|
]
|
||||||
|
] as CFDictionary
|
||||||
|
|
||||||
|
var privateKey: SecKey! = nil
|
||||||
|
var publicKey: SecKey! = nil
|
||||||
|
SecKeyGeneratePair(attributes, &publicKey, &privateKey)
|
||||||
|
let publicAttributes = SecKeyCopyAttributes(publicKey) as! [CFString: Any]
|
||||||
|
let privateAttributes = SecKeyCopyAttributes(privateKey) as! [CFString: Any]
|
||||||
|
let publicData = (publicAttributes[kSecValueData] as! Data)
|
||||||
|
let privateData = (privateAttributes[kSecValueData] as! Data)
|
||||||
|
let secret = Secret(keySize: size, publicKey: publicData, privateKey: privateData)
|
||||||
|
print(secret)
|
||||||
|
print("Public Key OpenSSH: \(OpenSSHKeyWriter().openSSHString(secret: secret))")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||||
|
guard !shouldThrow else {
|
||||||
|
throw NSError(domain: "test", code: 0, userInfo: nil)
|
||||||
|
}
|
||||||
|
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, [
|
||||||
|
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
||||||
|
kSecAttrKeySizeInBits: secret.keySize,
|
||||||
|
kSecAttrKeyClass: kSecAttrKeyClassPrivate
|
||||||
|
] as CFDictionary
|
||||||
|
, nil)!
|
||||||
|
let signatureAlgorithm: SecKeyAlgorithm
|
||||||
|
switch secret.keySize {
|
||||||
|
case 256:
|
||||||
|
signatureAlgorithm = .ecdsaSignatureMessageX962SHA256
|
||||||
|
case 384:
|
||||||
|
signatureAlgorithm = .ecdsaSignatureMessageX962SHA384
|
||||||
|
default:
|
||||||
|
fatalError()
|
||||||
|
}
|
||||||
|
return SignedData(data: SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data, requiredAuthentication: false)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Stub {
|
||||||
|
|
||||||
|
struct Secret: SecretKit.Secret, CustomDebugStringConvertible {
|
||||||
|
|
||||||
|
let id = UUID().uuidString.data(using: .utf8)!
|
||||||
|
let name = UUID().uuidString
|
||||||
|
let algorithm = Algorithm.ellipticCurve
|
||||||
|
|
||||||
|
let keySize: Int
|
||||||
|
let publicKey: Data
|
||||||
|
let privateKey: Data
|
||||||
|
|
||||||
|
init(keySize: Int, publicKey: Data, privateKey: Data) {
|
||||||
|
self.keySize = keySize
|
||||||
|
self.publicKey = publicKey
|
||||||
|
self.privateKey = privateKey
|
||||||
|
}
|
||||||
|
|
||||||
|
var debugDescription: String {
|
||||||
|
"""
|
||||||
|
Key Size \(keySize)
|
||||||
|
Private: \(privateKey.base64EncodedString())
|
||||||
|
Public: \(publicKey.base64EncodedString())
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
extension Stub.Store {
|
||||||
|
|
||||||
|
struct StubError: Error {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
32
Sources/Packages/Tests/SecretAgentKitTests/StubWitness.swift
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import SecretKit
|
||||||
|
import SecretAgentKit
|
||||||
|
|
||||||
|
struct StubWitness {
|
||||||
|
|
||||||
|
let speakNow: (AnySecret, SigningRequestProvenance) -> Bool
|
||||||
|
let witness: (AnySecret, SigningRequestProvenance) -> ()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension StubWitness: SigningWitness {
|
||||||
|
|
||||||
|
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||||
|
let objection = speakNow(secret, provenance)
|
||||||
|
if objection {
|
||||||
|
throw TheresMyChance()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
|
||||||
|
witness(secret, provenance)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension StubWitness {
|
||||||
|
|
||||||
|
struct TheresMyChance: Error {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
19
Sources/Packages/Tests/SecretKitTests/AnySecretTests.swift
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import SecretKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
|
class AnySecretTests: XCTestCase {
|
||||||
|
|
||||||
|
func testEraser() {
|
||||||
|
let secret = SmartCard.Secret(id: UUID().uuidString.data(using: .utf8)!, name: "Name", algorithm: .ellipticCurve, keySize: 256, publicKey: UUID().uuidString.data(using: .utf8)!)
|
||||||
|
let erased = AnySecret(secret)
|
||||||
|
XCTAssert(erased.id == secret.id as AnyHashable)
|
||||||
|
XCTAssert(erased.name == secret.name)
|
||||||
|
XCTAssert(erased.algorithm == secret.algorithm)
|
||||||
|
XCTAssert(erased.keySize == secret.keySize)
|
||||||
|
XCTAssert(erased.publicKey == secret.publicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import SecretKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
|
class OpenSSHReaderTests: XCTestCase {
|
||||||
|
|
||||||
|
func testSignatureRequest() {
|
||||||
|
let reader = OpenSSHReader(data: Constants.signatureRequest)
|
||||||
|
let hash = reader.readNextChunk()
|
||||||
|
XCTAssert(hash == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQ=="))
|
||||||
|
let dataToSign = reader.readNextChunk()
|
||||||
|
XCTAssert(dataToSign == Data(base64Encoded: "AAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QU="))
|
||||||
|
let empty = reader.readNextChunk()
|
||||||
|
XCTAssert(empty.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHReaderTests {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
static let signatureRequest = Data(base64Encoded: "AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QUAAADvAAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QUAAAAA")!
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import SecretKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
|
class OpenSSHWriterTests: XCTestCase {
|
||||||
|
|
||||||
|
let writer = OpenSSHKeyWriter()
|
||||||
|
|
||||||
|
func testECDSA256MD5Fingerprint() {
|
||||||
|
XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa256Secret), "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testECDSA256SHA256Fingerprint() {
|
||||||
|
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret), "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testECDSA256PublicKey() {
|
||||||
|
XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa256Secret),
|
||||||
|
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testECDSA256Hash() {
|
||||||
|
XCTAssertEqual(writer.data(secret: Constants.ecdsa256Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testECDSA384MD5Fingerprint() {
|
||||||
|
XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa384Secret), "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testECDSA384SHA256Fingerprint() {
|
||||||
|
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret), "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testECDSA384PublicKey() {
|
||||||
|
XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa384Secret),
|
||||||
|
"ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testECDSA384Hash() {
|
||||||
|
XCTAssertEqual(writer.data(secret: Constants.ecdsa384Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ=="))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHWriterTests {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
static let ecdsa256Secret = SmartCard.Secret(id: Data(), name: "Test Key (ECDSA 256)", algorithm: .ellipticCurve, keySize: 256, publicKey: Data(base64Encoded: "BOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")!)
|
||||||
|
static let ecdsa384Secret = SmartCard.Secret(id: Data(), name: "Test Key (ECDSA 384)", algorithm: .ellipticCurve, keySize: 384, publicKey: Data(base64Encoded: "BG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")!)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
48
Sources/SecretAgent/AppDelegate.swift
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
import Cocoa
|
||||||
|
import OSLog
|
||||||
|
import Combine
|
||||||
|
import SecretKit
|
||||||
|
import SecureEnclaveSecretKit
|
||||||
|
import SmartCardSecretKit
|
||||||
|
import SecretAgentKit
|
||||||
|
import Brief
|
||||||
|
|
||||||
|
@NSApplicationMain
|
||||||
|
class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
|
|
||||||
|
private let storeList: SecretStoreList = {
|
||||||
|
let list = SecretStoreList()
|
||||||
|
list.add(store: SecureEnclave.Store())
|
||||||
|
list.add(store: SmartCard.Store())
|
||||||
|
return list
|
||||||
|
}()
|
||||||
|
private let updater = Updater(checkOnLaunch: false)
|
||||||
|
private let notifier = Notifier()
|
||||||
|
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
|
||||||
|
private lazy var agent: Agent = {
|
||||||
|
Agent(storeList: storeList, witness: notifier)
|
||||||
|
}()
|
||||||
|
private lazy var socketController: SocketController = {
|
||||||
|
let path = (NSHomeDirectory() as NSString).appendingPathComponent("socket.ssh") as String
|
||||||
|
return SocketController(path: path)
|
||||||
|
}()
|
||||||
|
private var updateSink: AnyCancellable?
|
||||||
|
|
||||||
|
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||||
|
Logger().debug("SecretAgent finished launching")
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.socketController.handler = self.agent.handle(reader:writer:)
|
||||||
|
}
|
||||||
|
NotificationCenter.default.addObserver(forName: .secretStoreReloaded, object: nil, queue: .main) { [self] _ in
|
||||||
|
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
|
||||||
|
}
|
||||||
|
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
|
||||||
|
notifier.prompt()
|
||||||
|
updateSink = updater.$update.sink { update in
|
||||||
|
guard let update = update else { return }
|
||||||
|
self.notifier.notify(update: update, ignore: self.updater.ignore(release:))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|