Compare commits
78 Commits
Author | SHA1 | Date | |
---|---|---|---|
480ef5392d | |||
8679ca3da0 | |||
f43571baa3 | |||
acdf0baf3a | |||
1a362ef955 | |||
3b254d33a5 | |||
382913cb99 | |||
20cbaac6f6 | |||
47d736cb0d | |||
fa0e81cd8e | |||
e31db0f4fa | |||
403709ac83 | |||
5f055efa18 | |||
e77812c06c | |||
8744313ba1 | |||
26d6ced9ee | |||
71b4780488 | |||
84dd9403c3 | |||
0af7b803bc | |||
a1009d0dac | |||
ae7394f771 | |||
6ea0a3ebd2 | |||
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 |
BIN
.github/readme/app.png
vendored
Before Width: | Height: | Size: 338 KiB After Width: | Height: | Size: 580 KiB |
BIN
.github/readme/notification.png
vendored
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.0 MiB |
BIN
.github/readme/touchid.png
vendored
Before Width: | Height: | Size: 190 KiB After Width: | Height: | Size: 259 KiB |
7
.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
|
||||||
|
16
.github/workflows/add-to-project.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
name: Add bugs to bugs project
|
||||||
|
|
||||||
|
on:
|
||||||
|
issues:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
add-to-project:
|
||||||
|
name: Add issue to project
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/add-to-project@v0.0.3
|
||||||
|
with:
|
||||||
|
project-url: https://github.com/users/maxgoedjen/projects/1
|
||||||
|
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}
|
53
.github/workflows/nightly.yml
vendored
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
name: Nightly
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 8 * * *"
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: macOS-latest
|
||||||
|
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_14.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: |
|
||||||
|
echo "sha-512:"
|
||||||
|
shasum -a 512 Secretive.zip
|
||||||
|
shasum -a 512 Archive.zip
|
||||||
|
echo "sha-256:"
|
||||||
|
shasum -a 256 Secretive.zip
|
||||||
|
shasum -a 256 Archive.zip
|
||||||
|
- name: Upload App to Artifacts
|
||||||
|
uses: actions/upload-artifact@v1
|
||||||
|
with:
|
||||||
|
name: Secretive.zip
|
||||||
|
path: Secretive.zip
|
114
.github/workflows/release.yml
vendored
@ -6,7 +6,7 @@ on:
|
|||||||
- '*'
|
- '*'
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: macos-11.0
|
runs-on: macOS-latest
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v1
|
||||||
@ -16,16 +16,60 @@ jobs:
|
|||||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||||
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||||
AGENT_PROFILE_DATA: ${{ secrets.AGENT_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
|
run: ./.github/scripts/signing.sh
|
||||||
- name: Set Environment
|
- name: Set Environment
|
||||||
run: sudo xcrun xcode-select -s /Applications/Xcode_12.2.app
|
run: sudo xcrun xcode-select -s /Applications/Xcode_14.1.app
|
||||||
- name: Test
|
- name: Test
|
||||||
run: xcrun xcodebuild test -project Secretive.xcodeproj -scheme Secretive
|
run: |
|
||||||
|
pushd Sources/Packages
|
||||||
|
swift test
|
||||||
|
popd
|
||||||
build:
|
build:
|
||||||
runs-on: macos-11.0
|
runs-on: macOS-latest
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- 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_14.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: |
|
||||||
|
echo "sha-512:"
|
||||||
|
shasum -a 512 Secretive.zip
|
||||||
|
shasum -a 512 Archive.zip
|
||||||
|
echo "sha-256:"
|
||||||
|
shasum -a 256 Secretive.zip
|
||||||
|
shasum -a 256 Archive.zip
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: actions/create-release@v1
|
uses: actions/create-release@v1
|
||||||
@ -34,44 +78,24 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
tag_name: ${{ github.ref }}
|
tag_name: ${{ github.ref }}
|
||||||
release_name: ${{ github.ref }}
|
release_name: ${{ github.ref }}
|
||||||
body: "## Build\nhttps://github.com/maxgoedjen/secretive/actions/runs/${{ github.run_id }}"
|
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: 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 }}
|
|
||||||
run: ./.github/scripts/signing.sh
|
|
||||||
- name: Set Environment
|
|
||||||
run: sudo xcrun xcode-select -s /Applications/Xcode_12.2.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" Config/Config.xcconfig
|
|
||||||
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Config/Config.xcconfig
|
|
||||||
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Secretive/Credits.rtf
|
|
||||||
- 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 }}
|
||||||
@ -80,13 +104,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
|
||||||
|
9
.github/workflows/test.yml
vendored
@ -3,11 +3,14 @@ name: Test
|
|||||||
on: [push, pull_request]
|
on: [push, pull_request]
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: macos-11.0
|
runs-on: macOS-latest
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Set Environment
|
- name: Set Environment
|
||||||
run: sudo xcrun xcode-select -s /Applications/Xcode_12.2.app
|
run: sudo xcrun xcode-select -s /Applications/Xcode_14.1.app
|
||||||
- name: Test
|
- name: Test
|
||||||
run: xcrun xcodebuild test -project Secretive.xcodeproj -scheme Secretive
|
run: |
|
||||||
|
pushd Sources/Packages
|
||||||
|
swift test
|
||||||
|
popd
|
||||||
|
1
.gitignore
vendored
@ -92,3 +92,4 @@ iOSInjectionProject/
|
|||||||
# Build script products
|
# Build script products
|
||||||
Archive.xcarchive
|
Archive.xcarchive
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
contents.xcworkspacedata
|
||||||
|
@ -26,8 +26,91 @@ Host *
|
|||||||
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
|
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## nushell
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Mountain Duck
|
||||||
|
|
||||||
|
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 Mountain Duck.
|
||||||
|
|
||||||
|
## 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!
|
# 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 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.
|
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.
|
||||||
|
@ -1,19 +0,0 @@
|
|||||||
//
|
|
||||||
// Brief.h
|
|
||||||
// Brief
|
|
||||||
//
|
|
||||||
// Created by Max Goedjen on 3/21/20.
|
|
||||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
|
||||||
//
|
|
||||||
|
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
//! Project version number for Brief.
|
|
||||||
FOUNDATION_EXPORT double BriefVersionNumber;
|
|
||||||
|
|
||||||
//! Project version string for Brief.
|
|
||||||
FOUNDATION_EXPORT const unsigned char BriefVersionString[];
|
|
||||||
|
|
||||||
// In this header, you should import all the public headers of your framework using statements like #import <Brief/PublicHeader.h>
|
|
||||||
|
|
||||||
|
|
@ -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>$(PRODUCT_NAME) is MIT Licensed.</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,145 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import Combine
|
|
||||||
|
|
||||||
public protocol UpdaterProtocol: ObservableObject {
|
|
||||||
|
|
||||||
var update: Release? { get }
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Updater: ObservableObject, UpdaterProtocol {
|
|
||||||
|
|
||||||
@Published public var update: Release?
|
|
||||||
|
|
||||||
public init(checkOnLaunch: Bool) {
|
|
||||||
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: 60*60*24, repeats: true) { _ in
|
|
||||||
self.checkForUpdates()
|
|
||||||
}
|
|
||||||
timer.tolerance = 60*60
|
|
||||||
}
|
|
||||||
|
|
||||||
public func checkForUpdates() {
|
|
||||||
URLSession.shared.dataTask(with: Constants.updateURL) { data, _, _ in
|
|
||||||
guard let data = data else { return }
|
|
||||||
guard let release = try? JSONDecoder().decode(Release.self, from: data) else { return }
|
|
||||||
self.evaluate(release: release)
|
|
||||||
}.resume()
|
|
||||||
}
|
|
||||||
|
|
||||||
public func ignore(release: Release) {
|
|
||||||
guard !release.critical else { return }
|
|
||||||
defaults.set(true, forKey: release.name)
|
|
||||||
DispatchQueue.main.async {
|
|
||||||
self.update = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Updater {
|
|
||||||
|
|
||||||
func evaluate(release: Release) {
|
|
||||||
guard !userIgnored(release: release) else { return }
|
|
||||||
guard !release.prerelease else { return }
|
|
||||||
let latestVersion = SemVer(release.name)
|
|
||||||
let currentVersion = SemVer(Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String)
|
|
||||||
if latestVersion > currentVersion {
|
|
||||||
DispatchQueue.main.async {
|
|
||||||
self.update = release
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func userIgnored(release: Release) -> Bool {
|
|
||||||
guard !release.critical else { return false }
|
|
||||||
return defaults.bool(forKey: release.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
var defaults: UserDefaults {
|
|
||||||
UserDefaults(suiteName: "com.maxgoedjen.Secretive.updater.ignorelist")!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SemVer {
|
|
||||||
|
|
||||||
let versionNumbers: [Int]
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SemVer: Comparable {
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Updater {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases/latest")!
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct Release: Codable {
|
|
||||||
|
|
||||||
public let name: String
|
|
||||||
public let prerelease: Bool
|
|
||||||
public let html_url: URL
|
|
||||||
public let body: String
|
|
||||||
|
|
||||||
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 {
|
|
||||||
|
|
||||||
public var critical: Bool {
|
|
||||||
body.contains(Constants.securityContent)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Release {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let securityContent = "Critical Security Update"
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -14,6 +14,14 @@ Secretive is designed to be easily auditable by people who are considering using
|
|||||||
|
|
||||||
All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md)
|
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
|
## 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).
|
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).
|
||||||
|
@ -1,50 +0,0 @@
|
|||||||
{
|
|
||||||
"configurations" : [
|
|
||||||
{
|
|
||||||
"id" : "5896AE5A-6D5A-48D3-837B-668B646A3273",
|
|
||||||
"name" : "Configuration 1",
|
|
||||||
"options" : {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"defaultOptions" : {
|
|
||||||
|
|
||||||
},
|
|
||||||
"testTargets" : [
|
|
||||||
{
|
|
||||||
"parallelizable" : true,
|
|
||||||
"target" : {
|
|
||||||
"containerPath" : "container:Secretive.xcodeproj",
|
|
||||||
"identifier" : "50617DAF23FCE4AB0099B055",
|
|
||||||
"name" : "SecretKitTests"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parallelizable" : true,
|
|
||||||
"target" : {
|
|
||||||
"containerPath" : "container:Secretive.xcodeproj",
|
|
||||||
"identifier" : "5099A073240242BA0062B6F2",
|
|
||||||
"name" : "SecretAgentKitTests"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"enabled" : false,
|
|
||||||
"parallelizable" : true,
|
|
||||||
"target" : {
|
|
||||||
"containerPath" : "container:Secretive.xcodeproj",
|
|
||||||
"identifier" : "50617D9323FCE48E0099B055",
|
|
||||||
"name" : "SecretiveTests"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parallelizable" : true,
|
|
||||||
"target" : {
|
|
||||||
"containerPath" : "container:Secretive.xcodeproj",
|
|
||||||
"identifier" : "5091D31E2519D56D0049FD9B",
|
|
||||||
"name" : "BriefTests"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"version" : 1
|
|
||||||
}
|
|
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).
|
18
FAQ.md
@ -12,6 +12,10 @@ Secretive relies on the `SSH_AUTH_SOCK` environment variable being respected. Th
|
|||||||
|
|
||||||
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.
|
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 was working for me, but now it has stopped
|
||||||
|
|
||||||
|
Try running the "Setup Secretive" process by clicking on "Help", then "Setup Secretive." If that doesn't work, follow the process above.
|
||||||
|
|
||||||
### Secretive prompts me to type my password instead of using my Apple Watch
|
### 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:
|
1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy:
|
||||||
@ -24,6 +28,14 @@ Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [
|
|||||||

|

|
||||||

|

|
||||||
|
|
||||||
|
### How do I tell SSH to use a specific key?
|
||||||
|
|
||||||
|
Beginning with Secretive 2.2, every secret has an automatically generated public key file representation on disk, and the path to it is listed under "Public Key Path" in Secretive. You can 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.
|
||||||
|
|
||||||
|
### Can I use Secretive for SSH Agent Forwarding?
|
||||||
|
|
||||||
|
Yes, you can! Once you've set up Secretive, just add `ForwardAgent yes` to the hosts you want to forward to in your SSH config file. Afterwards, any use of one of your SSH keys on the remote host must be authenticated through Secretive.
|
||||||
|
|
||||||
### Why should I trust you?
|
### 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).
|
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).
|
||||||
@ -34,7 +46,11 @@ Awesome! Just bear in mind that because an app only has access to the keychain i
|
|||||||
|
|
||||||
### What's this network request to GitHub?
|
### 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/Brief/Updater.swift).
|
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
|
### I have a security issue
|
||||||
|
|
||||||
|
BIN
Icon.sketch
@ -16,13 +16,13 @@ The most common setup for SSH keys is just keeping them on disk, guarded by prop
|
|||||||
|
|
||||||
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.
|
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" width="400">
|
||||||
|
|
||||||
### Notifications
|
### Notifications
|
||||||
|
|
||||||
Secretive also notifies you whenever your keys are accessed, 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" width="600">
|
||||||
|
|
||||||
### Support for Smart Cards Too!
|
### Support for Smart Cards Too!
|
||||||
|
|
||||||
@ -38,7 +38,7 @@ You can download the latest release over on the [Releases Page](https://github.c
|
|||||||
|
|
||||||
#### Using Homebrew
|
#### Using Homebrew
|
||||||
|
|
||||||
brew cask install secretive
|
brew install secretive
|
||||||
|
|
||||||
### FAQ
|
### FAQ
|
||||||
|
|
||||||
|
@ -1,105 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import UserNotifications
|
|
||||||
import AppKit
|
|
||||||
import SecretKit
|
|
||||||
import SecretAgentKit
|
|
||||||
import Brief
|
|
||||||
|
|
||||||
class Notifier {
|
|
||||||
|
|
||||||
private let notificationDelegate = NotificationDelegate()
|
|
||||||
|
|
||||||
init() {
|
|
||||||
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: "Update", options: [])
|
|
||||||
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: "Ignore", options: [])
|
|
||||||
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
|
|
||||||
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
|
|
||||||
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory])
|
|
||||||
UNUserNotificationCenter.current().delegate = notificationDelegate
|
|
||||||
}
|
|
||||||
|
|
||||||
func prompt() {
|
|
||||||
let notificationCenter = UNUserNotificationCenter.current()
|
|
||||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
|
||||||
}
|
|
||||||
|
|
||||||
func notify(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) {
|
|
||||||
let notificationCenter = UNUserNotificationCenter.current()
|
|
||||||
let notificationContent = UNMutableNotificationContent()
|
|
||||||
notificationContent.title = "Signed Request from \(provenance.origin.displayName)"
|
|
||||||
notificationContent.subtitle = "Using secret \"\(secret.name)\""
|
|
||||||
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
|
||||||
notificationContent.attachments = [attachment]
|
|
||||||
}
|
|
||||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
|
||||||
notificationCenter.add(request, withCompletionHandler: nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
func notify(update: Release, ignore: ((Release) -> Void)?) {
|
|
||||||
notificationDelegate.release = update
|
|
||||||
notificationDelegate.ignore = ignore
|
|
||||||
let notificationCenter = UNUserNotificationCenter.current()
|
|
||||||
let notificationContent = UNMutableNotificationContent()
|
|
||||||
if update.critical {
|
|
||||||
notificationContent.title = "Critical Security Update - \(update.name)"
|
|
||||||
} else {
|
|
||||||
notificationContent.title = "Update Available - \(update.name)"
|
|
||||||
}
|
|
||||||
notificationContent.subtitle = "Click to Update"
|
|
||||||
notificationContent.body = update.body
|
|
||||||
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
|
|
||||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
|
||||||
notificationCenter.add(request, withCompletionHandler: nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Notifier: SigningWitness {
|
|
||||||
|
|
||||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
|
||||||
}
|
|
||||||
|
|
||||||
func witness(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
|
||||||
notify(accessTo: secret, by: provenance)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension Notifier {
|
|
||||||
|
|
||||||
enum Constants {
|
|
||||||
static let updateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update"
|
|
||||||
static let criticalUpdateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.critical"
|
|
||||||
static let updateActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.updateaction"
|
|
||||||
static let ignoreActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.ignoreaction"
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
|
|
||||||
|
|
||||||
fileprivate var release: Release?
|
|
||||||
fileprivate var ignore: ((Release) -> Void)?
|
|
||||||
|
|
||||||
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
|
|
||||||
guard let update = release else { return }
|
|
||||||
switch response.actionIdentifier {
|
|
||||||
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
|
|
||||||
NSWorkspace.shared.open(update.html_url)
|
|
||||||
case Notifier.Constants.ignoreActionIdentitifier:
|
|
||||||
ignore?(update)
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
completionHandler()
|
|
||||||
}
|
|
||||||
|
|
||||||
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
|
|
||||||
completionHandler([.list, .banner])
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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>$(CI_VERSION)</string>
|
|
||||||
<key>CFBundleVersion</key>
|
|
||||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
|
||||||
<key>NSHumanReadableCopyright</key>
|
|
||||||
<string>$(PRODUCT_NAME) is MIT Licensed.</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,9 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
public protocol SigningWitness {
|
|
||||||
|
|
||||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws
|
|
||||||
func witness(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws
|
|
||||||
|
|
||||||
}
|
|
@ -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,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,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: Hashable {
|
|
||||||
case ellipticCurve
|
|
||||||
public init(secAttr: NSNumber) {
|
|
||||||
let secAttrString = secAttr.stringValue as CFString
|
|
||||||
switch secAttrString {
|
|
||||||
case kSecAttrKeyTypeEC:
|
|
||||||
self = .ellipticCurve
|
|
||||||
default:
|
|
||||||
fatalError()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -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, for provenance: SigningRequestProvenance) 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,53 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import AppKit
|
|
||||||
|
|
||||||
public struct SigningRequestProvenance: Equatable {
|
|
||||||
|
|
||||||
public var chain: [Process]
|
|
||||||
public init(root: Process) {
|
|
||||||
self.chain = [root]
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SigningRequestProvenance {
|
|
||||||
|
|
||||||
public var origin: Process {
|
|
||||||
chain.last!
|
|
||||||
}
|
|
||||||
|
|
||||||
public var intact: Bool {
|
|
||||||
chain.allSatisfy { $0.validSignature }
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SigningRequestProvenance {
|
|
||||||
|
|
||||||
public struct Process: Equatable {
|
|
||||||
|
|
||||||
public let pid: Int32
|
|
||||||
public let processName: String
|
|
||||||
public let appName: String?
|
|
||||||
public let iconURL: URL?
|
|
||||||
public let path: String
|
|
||||||
public let validSignature: Bool
|
|
||||||
public let parentPID: Int32?
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
public var displayName: String {
|
|
||||||
appName ?? processName
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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>$(CI_VERSION)</string>
|
|
||||||
<key>CFBundleVersion</key>
|
|
||||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
|
||||||
<key>NSHumanReadableCopyright</key>
|
|
||||||
<string>$(PRODUCT_NAME) is MIT Licensed.</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,11 +0,0 @@
|
|||||||
#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 +0,0 @@
|
|||||||
public enum SecureEnclave {}
|
|
@ -1,190 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import Security
|
|
||||||
import CryptoTokenKit
|
|
||||||
import LocalAuthentication
|
|
||||||
|
|
||||||
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 private(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, for provenance: SigningRequestProvenance) throws -> Data {
|
|
||||||
let context = LAContext()
|
|
||||||
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
|
||||||
context.localizedCancelTitle = "Deny"
|
|
||||||
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?
|
|
||||||
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
|
||||||
throw SigningError(error: signError)
|
|
||||||
}
|
|
||||||
return signature as Data
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SecureEnclave.Store {
|
|
||||||
|
|
||||||
private func reloadSecrets(notify: Bool = true) {
|
|
||||||
secrets.removeAll()
|
|
||||||
loadSecrets()
|
|
||||||
if notify {
|
|
||||||
DistributedNotificationCenter.default().post(name: .secretStoreUpdated, object: nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
|
|
||||||
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 {
|
|
||||||
static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
|
|
||||||
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,85 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Scheme
|
|
||||||
LastUpgradeVersion = "1140"
|
|
||||||
version = "1.7">
|
|
||||||
<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 = "Test"
|
|
||||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
|
||||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
|
||||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
|
||||||
<TestPlans>
|
|
||||||
<TestPlanReference
|
|
||||||
reference = "container:Config/Secretive.xctestplan"
|
|
||||||
default = "YES">
|
|
||||||
</TestPlanReference>
|
|
||||||
</TestPlans>
|
|
||||||
<Testables>
|
|
||||||
<TestableReference
|
|
||||||
skipped = "NO"
|
|
||||||
parallelizable = "YES"
|
|
||||||
testExecutionOrdering = "random">
|
|
||||||
<BuildableReference
|
|
||||||
BuildableIdentifier = "primary"
|
|
||||||
BlueprintIdentifier = "5099A073240242BA0062B6F2"
|
|
||||||
BuildableName = "SecretAgentKitTests.xctest"
|
|
||||||
BlueprintName = "SecretAgentKitTests"
|
|
||||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
|
||||||
</BuildableReference>
|
|
||||||
</TestableReference>
|
|
||||||
</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,71 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Scheme
|
|
||||||
LastUpgradeVersion = "1140"
|
|
||||||
version = "1.7">
|
|
||||||
<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 = "Test"
|
|
||||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
|
||||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
|
||||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
|
||||||
<TestPlans>
|
|
||||||
<TestPlanReference
|
|
||||||
reference = "container:Config/Secretive.xctestplan"
|
|
||||||
default = "YES">
|
|
||||||
</TestPlanReference>
|
|
||||||
</TestPlans>
|
|
||||||
</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,193 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
import Brief
|
|
||||||
|
|
||||||
struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentStatusCheckerProtocol>: View {
|
|
||||||
|
|
||||||
@Binding var showingCreation: Bool
|
|
||||||
@Binding var runningSetup: Bool
|
|
||||||
@Binding var hasRunSetup: Bool
|
|
||||||
|
|
||||||
@EnvironmentObject private var storeList: SecretStoreList
|
|
||||||
@EnvironmentObject private var updater: UpdaterType
|
|
||||||
@EnvironmentObject private var agentStatusChecker: AgentStatusCheckerType
|
|
||||||
|
|
||||||
@State private var selectedUpdate: Release?
|
|
||||||
@State private var showingAppPathNotice = false
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
VStack {
|
|
||||||
if storeList.anyAvailable {
|
|
||||||
StoreListView(showingCreation: $showingCreation)
|
|
||||||
} else {
|
|
||||||
NoStoresView()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.frame(minWidth: 640, minHeight: 320)
|
|
||||||
.toolbar {
|
|
||||||
updateNotice
|
|
||||||
setupNotice
|
|
||||||
appPathNotice
|
|
||||||
newItem
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension ContentView {
|
|
||||||
|
|
||||||
var updateNotice: ToolbarItem<Void, AnyView> {
|
|
||||||
guard let update = updater.update else {
|
|
||||||
return ToolbarItem { AnyView(EmptyView()) }
|
|
||||||
}
|
|
||||||
let color: Color
|
|
||||||
let text: String
|
|
||||||
if update.critical {
|
|
||||||
text = "Critical Security Update Required"
|
|
||||||
color = .red
|
|
||||||
} else {
|
|
||||||
text = "Update Available"
|
|
||||||
color = .orange
|
|
||||||
}
|
|
||||||
return ToolbarItem {
|
|
||||||
AnyView(
|
|
||||||
Button(action: {
|
|
||||||
selectedUpdate = update
|
|
||||||
}, label: {
|
|
||||||
Text(text)
|
|
||||||
.font(.headline)
|
|
||||||
.foregroundColor(.white)
|
|
||||||
})
|
|
||||||
.background(color)
|
|
||||||
.cornerRadius(5)
|
|
||||||
.popover(item: $selectedUpdate, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) { update in
|
|
||||||
UpdateDetailView(update: update)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var newItem: ToolbarItem<Void, AnyView> {
|
|
||||||
guard storeList.modifiableStore?.isAvailable ?? false else {
|
|
||||||
return ToolbarItem { AnyView(EmptyView()) }
|
|
||||||
}
|
|
||||||
return ToolbarItem {
|
|
||||||
AnyView(
|
|
||||||
Button(action: {
|
|
||||||
showingCreation = true
|
|
||||||
}, label: {
|
|
||||||
Image(systemName: "plus")
|
|
||||||
})
|
|
||||||
.popover(isPresented: $showingCreation, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
|
|
||||||
if let modifiable = storeList.modifiableStore {
|
|
||||||
CreateSecretView(store: modifiable, showing: $showingCreation)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var setupNotice: ToolbarItem<Void, AnyView> {
|
|
||||||
return ToolbarItem {
|
|
||||||
AnyView(
|
|
||||||
Group {
|
|
||||||
if runningSetup || !hasRunSetup || !agentStatusChecker.running {
|
|
||||||
Button(action: {
|
|
||||||
runningSetup = true
|
|
||||||
}, label: {
|
|
||||||
Group {
|
|
||||||
if hasRunSetup && !agentStatusChecker.running {
|
|
||||||
Text("Secret Agent Is Not Running")
|
|
||||||
} else {
|
|
||||||
Text("Setup Secretive")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.font(.headline)
|
|
||||||
.foregroundColor(.white)
|
|
||||||
})
|
|
||||||
.background(Color.orange)
|
|
||||||
.cornerRadius(5)
|
|
||||||
} else {
|
|
||||||
EmptyView()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.sheet(isPresented: $runningSetup) {
|
|
||||||
SetupView(visible: $runningSetup, setupComplete: $hasRunSetup)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var appPathNotice: ToolbarItem<Void, AnyView> {
|
|
||||||
let controller = ApplicationDirectoryController()
|
|
||||||
guard !controller.isInApplicationsDirectory else {
|
|
||||||
return ToolbarItem { AnyView(EmptyView()) }
|
|
||||||
}
|
|
||||||
return ToolbarItem {
|
|
||||||
AnyView(
|
|
||||||
Button(action: {
|
|
||||||
showingAppPathNotice = true
|
|
||||||
}, label: {
|
|
||||||
Group {
|
|
||||||
Text("Secretive Is Not in Applications Folder")
|
|
||||||
}
|
|
||||||
.font(.headline)
|
|
||||||
.foregroundColor(.white)
|
|
||||||
})
|
|
||||||
.background(Color.orange)
|
|
||||||
.cornerRadius(5)
|
|
||||||
.popover(isPresented: $showingAppPathNotice, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
|
|
||||||
VStack {
|
|
||||||
Image(systemName: "exclamationmark.triangle")
|
|
||||||
.resizable()
|
|
||||||
.aspectRatio(contentMode: .fit)
|
|
||||||
.frame(width: 64)
|
|
||||||
Text("Secretive needs to be in your Applications folder to work properly. Please move it and relaunch.")
|
|
||||||
.frame(maxWidth: 300)
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
#if DEBUG
|
|
||||||
|
|
||||||
struct ContentView_Previews: PreviewProvider {
|
|
||||||
|
|
||||||
private static let storeList: SecretStoreList = {
|
|
||||||
let list = SecretStoreList()
|
|
||||||
list.add(store: SecureEnclave.Store())
|
|
||||||
list.add(store: SmartCard.Store())
|
|
||||||
return list
|
|
||||||
}()
|
|
||||||
private static let agentStatusChecker = AgentStatusChecker()
|
|
||||||
private static let justUpdatedChecker = JustUpdatedChecker()
|
|
||||||
|
|
||||||
@State var hasRunSetup = false
|
|
||||||
@State private var showingSetup = false
|
|
||||||
@State private var showingCreation = false
|
|
||||||
|
|
||||||
static var previews: some View {
|
|
||||||
Group {
|
|
||||||
// Empty on modifiable and nonmodifiable
|
|
||||||
ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
|
|
||||||
.environmentObject(Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]))
|
|
||||||
.environmentObject(PreviewUpdater())
|
|
||||||
.environmentObject(agentStatusChecker)
|
|
||||||
|
|
||||||
// 5 items on modifiable and nonmodifiable
|
|
||||||
ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
|
|
||||||
.environmentObject(Preview.storeList(stores: [Preview.Store()], modifiableStores: [Preview.StoreModifiable()]))
|
|
||||||
.environmentObject(PreviewUpdater())
|
|
||||||
.environmentObject(agentStatusChecker)
|
|
||||||
}
|
|
||||||
.environmentObject(agentStatusChecker)
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
@ -1,53 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
|
|
||||||
|
|
||||||
@ObservedObject var store: StoreType
|
|
||||||
@Binding var showing: Bool
|
|
||||||
|
|
||||||
@State private var name = ""
|
|
||||||
@State private var requiresAuthentication = true
|
|
||||||
|
|
||||||
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).focusable()
|
|
||||||
}
|
|
||||||
HStack {
|
|
||||||
Toggle(isOn: $requiresAuthentication) {
|
|
||||||
Text("Requires Authentication (Biometrics or Password)")
|
|
||||||
}
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
HStack {
|
|
||||||
Spacer()
|
|
||||||
Button("Cancel") {
|
|
||||||
showing = false
|
|
||||||
}
|
|
||||||
.keyboardShortcut(.cancelAction)
|
|
||||||
Button("Create", action: save)
|
|
||||||
.disabled(name.isEmpty)
|
|
||||||
.keyboardShortcut(.defaultAction)
|
|
||||||
}
|
|
||||||
}.padding()
|
|
||||||
}
|
|
||||||
|
|
||||||
func save() {
|
|
||||||
try! store.create(name: name, requiresAuthentication: requiresAuthentication)
|
|
||||||
showing = false
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,43 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
struct SecretDetailView<SecretType: Secret>: View {
|
|
||||||
|
|
||||||
@State var secret: SecretType
|
|
||||||
|
|
||||||
private let keyWriter = OpenSSHKeyWriter()
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Form {
|
|
||||||
Section {
|
|
||||||
CopyableView(title: "Fingerprint", image: Image(systemName: "touchid"), text: keyWriter.openSSHFingerprint(secret: secret))
|
|
||||||
Spacer()
|
|
||||||
.frame(height: 20)
|
|
||||||
CopyableView(title: "Public Key", image: Image(systemName: "key"), text: keyWriter.openSSHString(secret: secret))
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
.frame(minHeight: 200, 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,41 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
import SecretKit
|
|
||||||
|
|
||||||
struct SecretListView: View {
|
|
||||||
|
|
||||||
@ObservedObject var store: AnySecretStore
|
|
||||||
@Binding var activeSecret: AnySecret.ID?
|
|
||||||
@Binding var deletingSecret: AnySecret?
|
|
||||||
|
|
||||||
var deletedSecret: (AnySecret) -> Void
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
ForEach(store.secrets) { secret in
|
|
||||||
NavigationLink(destination: SecretDetailView(secret: secret), tag: secret.id, selection: $activeSecret) {
|
|
||||||
Text(secret.name)
|
|
||||||
}.contextMenu {
|
|
||||||
if store is AnySecretStoreModifiable {
|
|
||||||
Button(action: { delete(secret: secret) }) {
|
|
||||||
Text("Delete")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.popover(isPresented: .constant(deletingSecret == secret)) {
|
|
||||||
if let modifiable = store as? AnySecretStoreModifiable {
|
|
||||||
DeleteSecretView(store: modifiable, secret: secret) { deleted in
|
|
||||||
deletingSecret = nil
|
|
||||||
if deleted {
|
|
||||||
deletedSecret(AnySecret(secret))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func delete<SecretType: Secret>(secret: SecretType) {
|
|
||||||
deletingSecret = AnySecret(secret)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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>
|
|
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 }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -4,57 +4,74 @@ import OSLog
|
|||||||
import SecretKit
|
import SecretKit
|
||||||
import AppKit
|
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 {
|
public class Agent {
|
||||||
|
|
||||||
private let storeList: SecretStoreList
|
private let storeList: SecretStoreList
|
||||||
private let witness: SigningWitness?
|
private let witness: SigningWitness?
|
||||||
private let writer = OpenSSHKeyWriter()
|
private let writer = OpenSSHKeyWriter()
|
||||||
private let requestTracer = SigningRequestTracer()
|
private let requestTracer = SigningRequestTracer()
|
||||||
|
private let certificateHandler = OpenSSHCertificateHandler()
|
||||||
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent.agent", category: "")
|
||||||
|
|
||||||
|
/// 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) {
|
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
|
||||||
Logger().debug("Agent is running")
|
logger.debug("Agent is running")
|
||||||
self.storeList = storeList
|
self.storeList = storeList
|
||||||
self.witness = witness
|
self.witness = witness
|
||||||
|
certificateHandler.reloadCertificates(for: storeList.allSecrets)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Agent {
|
extension Agent {
|
||||||
|
|
||||||
public func handle(reader: FileHandleReader, writer: FileHandleWriter) {
|
/// Handles an incoming request.
|
||||||
Logger().debug("Agent handling new data")
|
/// - Parameters:
|
||||||
let data = reader.availableData
|
/// - reader: A ``FileHandleReader`` to read the content of the request.
|
||||||
guard !data.isEmpty else { return }
|
/// - writer: A ``FileHandleWriter`` to write the response to.
|
||||||
|
/// - Return value:
|
||||||
|
/// - Boolean if data could be read
|
||||||
|
@discardableResult 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]
|
let requestTypeInt = data[4]
|
||||||
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else {
|
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else {
|
||||||
writer.write(OpenSSHKeyWriter().lengthAndData(of: SSHAgent.ResponseType.agentFailure.data))
|
writer.write(OpenSSHKeyWriter().lengthAndData(of: SSHAgent.ResponseType.agentFailure.data))
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
logger.debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
||||||
return
|
return true
|
||||||
}
|
}
|
||||||
Logger().debug("Agent handling request of type \(requestType.debugDescription)")
|
logger.debug("Agent handling request of type \(requestType.debugDescription)")
|
||||||
let subData = Data(data[5...])
|
let subData = Data(data[5...])
|
||||||
let response = handle(requestType: requestType, data: subData, reader: reader)
|
let response = handle(requestType: requestType, data: subData, reader: reader)
|
||||||
writer.write(response)
|
writer.write(response)
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
|
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
|
||||||
|
// Depending on the launch context (such as after macOS update), the agent may need to reload secrets before acting
|
||||||
|
reloadSecretsIfNeccessary()
|
||||||
var response = Data()
|
var response = Data()
|
||||||
do {
|
do {
|
||||||
switch requestType {
|
switch requestType {
|
||||||
case .requestIdentities:
|
case .requestIdentities:
|
||||||
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
|
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
|
||||||
response.append(identities())
|
response.append(identities())
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)")
|
logger.debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)")
|
||||||
case .signRequest:
|
case .signRequest:
|
||||||
let provenance = requestTracer.provenance(from: reader)
|
let provenance = requestTracer.provenance(from: reader)
|
||||||
response.append(SSHAgent.ResponseType.agentSignResponse.data)
|
response.append(SSHAgent.ResponseType.agentSignResponse.data)
|
||||||
response.append(try sign(data: data, provenance: provenance))
|
response.append(try sign(data: data, provenance: provenance))
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
|
logger.debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
response.removeAll()
|
response.removeAll()
|
||||||
response.append(SSHAgent.ResponseType.agentFailure.data)
|
response.append(SSHAgent.ResponseType.agentFailure.data)
|
||||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
logger.debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
||||||
}
|
}
|
||||||
let full = OpenSSHKeyWriter().lengthAndData(of: response)
|
let full = OpenSSHKeyWriter().lengthAndData(of: response)
|
||||||
return full
|
return full
|
||||||
@ -64,36 +81,63 @@ extension Agent {
|
|||||||
|
|
||||||
extension Agent {
|
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 {
|
func identities() -> Data {
|
||||||
let secrets = storeList.stores.flatMap(\.secrets)
|
let secrets = storeList.allSecrets
|
||||||
|
certificateHandler.reloadCertificates(for: secrets)
|
||||||
var count = UInt32(secrets.count).bigEndian
|
var count = UInt32(secrets.count).bigEndian
|
||||||
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
||||||
var keyData = Data()
|
var keyData = Data()
|
||||||
let writer = OpenSSHKeyWriter()
|
|
||||||
for secret in secrets {
|
for secret in secrets {
|
||||||
let keyBlob = writer.data(secret: secret)
|
let keyBlob: Data
|
||||||
|
let curveData: Data
|
||||||
|
|
||||||
|
if let (certificateData, name) = try? certificateHandler.keyBlobAndName(for: secret) {
|
||||||
|
keyBlob = certificateData
|
||||||
|
curveData = name
|
||||||
|
} else {
|
||||||
|
keyBlob = writer.data(secret: secret)
|
||||||
|
curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||||
|
}
|
||||||
|
|
||||||
keyData.append(writer.lengthAndData(of: keyBlob))
|
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))
|
keyData.append(writer.lengthAndData(of: curveData))
|
||||||
|
|
||||||
}
|
}
|
||||||
Logger().debug("Agent enumerated \(secrets.count) identities")
|
logger.log("Agent enumerated \(secrets.count) identities")
|
||||||
return countData + keyData
|
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 {
|
func sign(data: Data, provenance: SigningRequestProvenance) throws -> Data {
|
||||||
let reader = OpenSSHReader(data: data)
|
let reader = OpenSSHReader(data: data)
|
||||||
let hash = reader.readNextChunk()
|
let payloadHash = reader.readNextChunk()
|
||||||
|
let hash: Data
|
||||||
|
// Check if hash is actually an openssh certificate and reconstruct the public key if it is
|
||||||
|
if let certificatePublicKey = certificateHandler.publicKeyHash(from: payloadHash) {
|
||||||
|
hash = certificatePublicKey
|
||||||
|
} else {
|
||||||
|
hash = payloadHash
|
||||||
|
}
|
||||||
|
|
||||||
guard let (store, secret) = secret(matching: hash) else {
|
guard let (store, secret) = secret(matching: hash) else {
|
||||||
Logger().debug("Agent did not have a key matching \(hash as NSData)")
|
logger.debug("Agent did not have a key matching \(hash as NSData)")
|
||||||
throw AgentError.noMatchingKey
|
throw AgentError.noMatchingKey
|
||||||
}
|
}
|
||||||
|
|
||||||
if let witness = witness {
|
if let witness = witness {
|
||||||
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, by: provenance)
|
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
||||||
}
|
}
|
||||||
|
|
||||||
let dataToSign = reader.readNextChunk()
|
let dataToSign = reader.readNextChunk()
|
||||||
let derSignature = try store.sign(data: dataToSign, with: secret, for: provenance)
|
let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
|
||||||
|
let derSignature = signed
|
||||||
|
|
||||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||||
|
|
||||||
@ -134,10 +178,10 @@ extension Agent {
|
|||||||
signedData.append(writer.lengthAndData(of: sub))
|
signedData.append(writer.lengthAndData(of: sub))
|
||||||
|
|
||||||
if let witness = witness {
|
if let witness = witness {
|
||||||
try witness.witness(accessTo: secret, by: provenance)
|
try witness.witness(accessTo: secret, from: store, by: provenance)
|
||||||
}
|
}
|
||||||
|
|
||||||
Logger().debug("Agent signed request")
|
logger.debug("Agent signed request")
|
||||||
|
|
||||||
return signedData
|
return signedData
|
||||||
}
|
}
|
||||||
@ -146,6 +190,19 @@ extension Agent {
|
|||||||
|
|
||||||
extension Agent {
|
extension Agent {
|
||||||
|
|
||||||
|
/// Gives any store with no loaded secrets a chance to reload.
|
||||||
|
func reloadSecretsIfNeccessary() {
|
||||||
|
for store in storeList.stores {
|
||||||
|
if store.secrets.isEmpty {
|
||||||
|
logger.debug("Store \(store.name, privacy: .public) has no loaded secrets. Reloading.")
|
||||||
|
store.reloadSecrets()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)? {
|
func secret(matching hash: Data) -> (AnySecretStore, AnySecret)? {
|
||||||
storeList.stores.compactMap { store -> (AnySecretStore, AnySecret)? in
|
storeList.stores.compactMap { store -> (AnySecretStore, AnySecret)? in
|
||||||
let allMatching = store.secrets.filter { secret in
|
let allMatching = store.secrets.filter { secret in
|
||||||
@ -163,10 +220,12 @@ extension Agent {
|
|||||||
|
|
||||||
extension Agent {
|
extension Agent {
|
||||||
|
|
||||||
|
/// An error involving agent operations..
|
||||||
enum AgentError: Error {
|
enum AgentError: Error {
|
||||||
case unhandledType
|
case unhandledType
|
||||||
case noMatchingKey
|
case noMatchingKey
|
||||||
case unsupportedKeyType
|
case unsupportedKeyType
|
||||||
|
case notOpenSSHCertificate
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -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``
|
@ -1,15 +1,21 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
/// Protocol abstraction of the reading aspects of FileHandle.
|
||||||
public protocol FileHandleReader {
|
public protocol FileHandleReader {
|
||||||
|
|
||||||
|
/// Gets data that is available for reading.
|
||||||
var availableData: Data { get }
|
var availableData: Data { get }
|
||||||
|
/// A file descriptor of the handle.
|
||||||
var fileDescriptor: Int32 { get }
|
var fileDescriptor: Int32 { get }
|
||||||
|
/// The process ID of the process coonnected to the other end of the FileHandle.
|
||||||
var pidOfConnectedProcess: Int32 { get }
|
var pidOfConnectedProcess: Int32 { get }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Protocol abstraction of the writing aspects of FileHandle.
|
||||||
public protocol FileHandleWriter {
|
public protocol FileHandleWriter {
|
||||||
|
|
||||||
|
/// Writes data to the handle.
|
||||||
func write(_ data: Data)
|
func write(_ data: Data)
|
||||||
|
|
||||||
}
|
}
|
@ -1,10 +1,13 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
/// A namespace for the SSH Agent Protocol, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||||
public enum SSHAgent {}
|
public enum SSHAgent {}
|
||||||
|
|
||||||
extension SSHAgent {
|
extension SSHAgent {
|
||||||
|
|
||||||
|
/// The type of the SSH Agent Request, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#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
|
||||||
|
|
||||||
@ -18,8 +21,11 @@ extension SSHAgent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The type of the SSH Agent Response, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||||
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
||||||
|
|
||||||
case agentFailure = 5
|
case agentFailure = 5
|
||||||
|
case agentSuccess = 6
|
||||||
case agentIdentitiesAnswer = 12
|
case agentIdentitiesAnswer = 12
|
||||||
case agentSignResponse = 14
|
case agentSignResponse = 14
|
||||||
|
|
||||||
@ -27,6 +33,8 @@ extension SSHAgent {
|
|||||||
switch self {
|
switch self {
|
||||||
case .agentFailure:
|
case .agentFailure:
|
||||||
return "AgentFailure"
|
return "AgentFailure"
|
||||||
|
case .agentSuccess:
|
||||||
|
return "AgentSuccess"
|
||||||
case .agentIdentitiesAnswer:
|
case .agentIdentitiesAnswer:
|
||||||
return "AgentIdentitiesAnswer"
|
return "AgentIdentitiesAnswer"
|
||||||
case .agentSignResponse:
|
case .agentSignResponse:
|
@ -2,12 +2,17 @@ import Foundation
|
|||||||
import AppKit
|
import AppKit
|
||||||
import Security
|
import Security
|
||||||
import SecretKit
|
import SecretKit
|
||||||
|
import SecretAgentKitHeaders
|
||||||
|
|
||||||
|
/// An object responsible for generating ``SecretKit.SigningRequestProvenance`` objects.
|
||||||
struct SigningRequestTracer {
|
struct SigningRequestTracer {
|
||||||
}
|
}
|
||||||
|
|
||||||
extension 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 {
|
func provenance(from fileHandleReader: FileHandleReader) -> SigningRequestProvenance {
|
||||||
let firstInfo = process(from: fileHandleReader.pidOfConnectedProcess)
|
let firstInfo = process(from: fileHandleReader.pidOfConnectedProcess)
|
||||||
|
|
||||||
@ -18,6 +23,9 @@ extension SigningRequestTracer {
|
|||||||
return provenance
|
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 {
|
func pidAndNameInfo(from pid: Int32) -> kinfo_proc {
|
||||||
var len = MemoryLayout<kinfo_proc>.size
|
var len = MemoryLayout<kinfo_proc>.size
|
||||||
let infoPointer = UnsafeMutableRawPointer.allocate(byteCount: len, alignment: 1)
|
let infoPointer = UnsafeMutableRawPointer.allocate(byteCount: len, alignment: 1)
|
||||||
@ -26,10 +34,16 @@ extension SigningRequestTracer {
|
|||||||
return infoPointer.load(as: kinfo_proc.self)
|
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 {
|
func process(from pid: Int32) -> SigningRequestProvenance.Process {
|
||||||
var pidAndNameInfo = self.pidAndNameInfo(from: pid)
|
var pidAndNameInfo = self.pidAndNameInfo(from: pid)
|
||||||
let ppid = pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
|
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 procName = withUnsafeMutablePointer(to: &pidAndNameInfo.kp_proc.p_comm.0) { pointer in
|
||||||
|
String(cString: pointer)
|
||||||
|
}
|
||||||
|
|
||||||
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
|
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
|
||||||
_ = proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
|
_ = proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
|
||||||
let path = String(cString: pathPointer)
|
let path = String(cString: pathPointer)
|
||||||
@ -40,6 +54,9 @@ extension SigningRequestTracer {
|
|||||||
return SigningRequestProvenance.Process(pid: pid, processName: procName, appName: appName(for: pid), iconURL: iconURL(for: pid), path: path, validSignature: valid, parentPID: ppid)
|
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? {
|
func iconURL(for pid: Int32) -> URL? {
|
||||||
do {
|
do {
|
||||||
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
|
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
|
||||||
@ -53,6 +70,9 @@ extension SigningRequestTracer {
|
|||||||
return nil
|
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? {
|
func appName(for pid: Int32) -> String? {
|
||||||
NSRunningApplication(processIdentifier: pid)?.localizedName
|
NSRunningApplication(processIdentifier: pid)?.localizedName
|
||||||
}
|
}
|
22
Sources/Packages/Sources/SecretAgentKit/SigningWitness.swift
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
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.
|
||||||
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
|
||||||
|
|
||||||
|
}
|
@ -1,12 +1,20 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import OSLog
|
import OSLog
|
||||||
|
|
||||||
|
/// A controller that manages socket configuration and request dispatching.
|
||||||
public class SocketController {
|
public class SocketController {
|
||||||
|
|
||||||
|
/// The active FileHandle.
|
||||||
private var fileHandle: FileHandle?
|
private var fileHandle: FileHandle?
|
||||||
|
/// The active SocketPort.
|
||||||
private var port: SocketPort?
|
private var port: SocketPort?
|
||||||
public var handler: ((FileHandleReader, FileHandleWriter) -> Void)?
|
/// 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) {
|
public init(path: String) {
|
||||||
Logger().debug("Socket controller setting up at \(path)")
|
Logger().debug("Socket controller setting up at \(path)")
|
||||||
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
||||||
@ -20,6 +28,8 @@ public class SocketController {
|
|||||||
Logger().debug("Socket listening 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) {
|
func configureSocket(at path: String) {
|
||||||
guard let port = port else { return }
|
guard let port = port else { return }
|
||||||
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
||||||
@ -28,6 +38,9 @@ public class SocketController {
|
|||||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
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 {
|
func socketPort(at path: String) -> SocketPort {
|
||||||
var addr = sockaddr_un()
|
var addr = sockaddr_un()
|
||||||
addr.sun_family = sa_family_t(AF_UNIX)
|
addr.sun_family = sa_family_t(AF_UNIX)
|
||||||
@ -49,19 +62,28 @@ public class SocketController {
|
|||||||
return SocketPort(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
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) {
|
@objc func handleConnectionAccept(notification: Notification) {
|
||||||
Logger().debug("Socket controller accepted connection")
|
Logger().debug("Socket controller accepted connection")
|
||||||
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
||||||
handler?(new, new)
|
_ = handler?(new, new)
|
||||||
new.waitForDataInBackgroundAndNotify()
|
new.waitForDataInBackgroundAndNotify()
|
||||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
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) {
|
@objc func handleConnectionDataAvailable(notification: Notification) {
|
||||||
Logger().debug("Socket controller has new data available")
|
Logger().debug("Socket controller has new data available")
|
||||||
guard let new = notification.object as? FileHandle else { return }
|
guard let new = notification.object as? FileHandle else { return }
|
||||||
Logger().debug("Socket controller received new file handle")
|
Logger().debug("Socket controller received new file handle")
|
||||||
handler?(new, new)
|
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,4 @@
|
|||||||
|
module SecretAgentKitHeaders [system] {
|
||||||
|
header "include/SecretAgentKit.h"
|
||||||
|
export *
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
# ``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
|
||||||
|
|
||||||
|
- ``SigningRequestProvenance``
|
||||||
|
|
||||||
|
### Authentication Persistence
|
||||||
|
|
||||||
|
- ``PersistedAuthenticationContext``
|
@ -1,5 +1,6 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
/// Type eraser for Secret.
|
||||||
public struct AnySecret: Secret {
|
public struct AnySecret: Secret {
|
||||||
|
|
||||||
let base: Any
|
let base: Any
|
||||||
@ -8,6 +9,7 @@ public struct AnySecret: Secret {
|
|||||||
private let _name: () -> String
|
private let _name: () -> String
|
||||||
private let _algorithm: () -> Algorithm
|
private let _algorithm: () -> Algorithm
|
||||||
private let _keySize: () -> Int
|
private let _keySize: () -> Int
|
||||||
|
private let _requiresAuthentication: () -> Bool
|
||||||
private let _publicKey: () -> Data
|
private let _publicKey: () -> Data
|
||||||
|
|
||||||
public init<T>(_ secret: T) where T: Secret {
|
public init<T>(_ secret: T) where T: Secret {
|
||||||
@ -18,6 +20,7 @@ public struct AnySecret: Secret {
|
|||||||
_name = secret._name
|
_name = secret._name
|
||||||
_algorithm = secret._algorithm
|
_algorithm = secret._algorithm
|
||||||
_keySize = secret._keySize
|
_keySize = secret._keySize
|
||||||
|
_requiresAuthentication = secret._requiresAuthentication
|
||||||
_publicKey = secret._publicKey
|
_publicKey = secret._publicKey
|
||||||
} else {
|
} else {
|
||||||
base = secret as Any
|
base = secret as Any
|
||||||
@ -26,6 +29,7 @@ public struct AnySecret: Secret {
|
|||||||
_name = { secret.name }
|
_name = { secret.name }
|
||||||
_algorithm = { secret.algorithm }
|
_algorithm = { secret.algorithm }
|
||||||
_keySize = { secret.keySize }
|
_keySize = { secret.keySize }
|
||||||
|
_requiresAuthentication = { secret.requiresAuthentication }
|
||||||
_publicKey = { secret.publicKey }
|
_publicKey = { secret.publicKey }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -46,6 +50,10 @@ public struct AnySecret: Secret {
|
|||||||
_keySize()
|
_keySize()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public var requiresAuthentication: Bool {
|
||||||
|
_requiresAuthentication()
|
||||||
|
}
|
||||||
|
|
||||||
public var publicKey: Data {
|
public var publicKey: Data {
|
||||||
_publicKey()
|
_publicKey()
|
||||||
}
|
}
|
@ -1,6 +1,7 @@
|
|||||||
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
|
||||||
@ -9,6 +10,10 @@ public class AnySecretStore: SecretStore {
|
|||||||
private let _name: () -> String
|
private let _name: () -> String
|
||||||
private let _secrets: () -> [AnySecret]
|
private let _secrets: () -> [AnySecret]
|
||||||
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> Data
|
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> Data
|
||||||
|
private let _existingPersistedAuthenticationContext: (AnySecret) -> PersistedAuthenticationContext?
|
||||||
|
private let _persistAuthentication: (AnySecret, TimeInterval) throws -> Void
|
||||||
|
private let _reloadSecrets: () -> Void
|
||||||
|
|
||||||
private var sink: AnyCancellable?
|
private var sink: AnyCancellable?
|
||||||
|
|
||||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
||||||
@ -18,6 +23,9 @@ public class AnySecretStore: SecretStore {
|
|||||||
_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, for: $2) }
|
_sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
|
||||||
|
_existingPersistedAuthenticationContext = { secretStore.existingPersistedAuthenticationContext(secret: $0.base as! SecretStoreType.SecretType) }
|
||||||
|
_persistAuthentication = { try secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
||||||
|
_reloadSecrets = { secretStore.reloadSecrets() }
|
||||||
sink = secretStore.objectWillChange.sink { _ in
|
sink = secretStore.objectWillChange.sink { _ in
|
||||||
self.objectWillChange.send()
|
self.objectWillChange.send()
|
||||||
}
|
}
|
||||||
@ -43,16 +51,30 @@ public class AnySecretStore: SecretStore {
|
|||||||
try _sign(data, secret, provenance)
|
try _sign(data, secret, provenance)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public func existingPersistedAuthenticationContext(secret: AnySecret) -> PersistedAuthenticationContext? {
|
||||||
|
_existingPersistedAuthenticationContext(secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) throws {
|
||||||
|
try _persistAuthentication(secret, duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func reloadSecrets() {
|
||||||
|
_reloadSecrets()
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
||||||
|
|
||||||
private let _create: (String, Bool) throws -> Void
|
private let _create: (String, Bool) throws -> Void
|
||||||
private 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 +86,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,120 @@
|
|||||||
|
import Foundation
|
||||||
|
import OSLog
|
||||||
|
|
||||||
|
/// Manages storage and lookup for OpenSSH certificates.
|
||||||
|
public class OpenSSHCertificateHandler {
|
||||||
|
|
||||||
|
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
|
||||||
|
private let logger = Logger()
|
||||||
|
private let writer = OpenSSHKeyWriter()
|
||||||
|
private var keyBlobsAndNames: [AnySecret: (Data, Data)] = [:]
|
||||||
|
|
||||||
|
/// Initializes an OpenSSHCertificateHandler.
|
||||||
|
public init() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reloads any certificates in the PublicKeys folder.
|
||||||
|
/// - Parameter secrets: the secrets to look up corresponding certificates for.
|
||||||
|
public func reloadCertificates(for secrets: [AnySecret]) {
|
||||||
|
guard publicKeyFileStoreController.hasAnyCertificates else {
|
||||||
|
logger.log("No certificates, short circuiting")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
keyBlobsAndNames = secrets.reduce(into: [:]) { partialResult, next in
|
||||||
|
partialResult[next] = try? loadKeyblobAndName(for: next)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether or not the certificate handler has a certifiicate associated with a given secret.
|
||||||
|
/// - Parameter secret: The secret to check for a certificate.
|
||||||
|
/// - Returns: A boolean describing whether or not the certificate handler has a certifiicate associated with a given secret
|
||||||
|
public func hasCertificate<SecretType: Secret>(for secret: SecretType) -> Bool {
|
||||||
|
keyBlobsAndNames[AnySecret(secret)] != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Reconstructs a public key from a ``Data``, if that ``Data`` contains an OpenSSH certificate hash. Currently only ecdsa certificates are supported
|
||||||
|
/// - Parameter certBlock: The openssh certificate to extract the public key from
|
||||||
|
/// - Returns: A ``Data`` object containing the public key in OpenSSH wire format if the ``Data`` is an OpenSSH certificate hash, otherwise nil.
|
||||||
|
public func publicKeyHash(from hash: Data) -> Data? {
|
||||||
|
let reader = OpenSSHReader(data: hash)
|
||||||
|
let certType = String(decoding: reader.readNextChunk(), as: UTF8.self)
|
||||||
|
|
||||||
|
switch certType {
|
||||||
|
case "ecdsa-sha2-nistp256-cert-v01@openssh.com",
|
||||||
|
"ecdsa-sha2-nistp384-cert-v01@openssh.com",
|
||||||
|
"ecdsa-sha2-nistp521-cert-v01@openssh.com":
|
||||||
|
_ = reader.readNextChunk() // nonce
|
||||||
|
let curveIdentifier = reader.readNextChunk()
|
||||||
|
let publicKey = reader.readNextChunk()
|
||||||
|
|
||||||
|
let curveType = certType.replacingOccurrences(of: "-cert-v01@openssh.com", with: "").data(using: .utf8)!
|
||||||
|
return writer.lengthAndData(of: curveType) +
|
||||||
|
writer.lengthAndData(of: curveIdentifier) +
|
||||||
|
writer.lengthAndData(of: publicKey)
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||||
|
/// - Parameter secret: The secret to search for a certificate with
|
||||||
|
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||||
|
public func keyBlobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||||
|
keyBlobsAndNames[AnySecret(secret)]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||||
|
/// - Parameter secret: The secret to search for a certificate with
|
||||||
|
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||||
|
private func loadKeyblobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||||
|
let certificatePath = publicKeyFileStoreController.sshCertificatePath(for: secret)
|
||||||
|
guard FileManager.default.fileExists(atPath: certificatePath) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug("Found certificate for \(secret.name)")
|
||||||
|
let certContent = try String(contentsOfFile:certificatePath, encoding: .utf8)
|
||||||
|
let certElements = certContent.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
|
||||||
|
|
||||||
|
guard certElements.count >= 2 else {
|
||||||
|
logger.warning("Certificate found for \(secret.name) but failed to load")
|
||||||
|
throw OpenSSHCertificateError.parsingFailed
|
||||||
|
}
|
||||||
|
guard let certDecoded = Data(base64Encoded: certElements[1] as String) else {
|
||||||
|
logger.warning("Certificate found for \(secret.name) but failed to decode base64 key")
|
||||||
|
throw OpenSSHCertificateError.parsingFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
if certElements.count >= 3, let certName = certElements[2].data(using: .utf8) {
|
||||||
|
return (certDecoded, certName)
|
||||||
|
} else if let certName = secret.name.data(using: .utf8) {
|
||||||
|
logger.info("Certificate for \(secret.name) does not have a name tag, using secret name instead")
|
||||||
|
return (certDecoded, certName)
|
||||||
|
} else {
|
||||||
|
throw OpenSSHCertificateError.parsingFailed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OpenSSHCertificateHandler {
|
||||||
|
|
||||||
|
enum OpenSSHCertificateError: LocalizedError {
|
||||||
|
case unsupportedType
|
||||||
|
case parsingFailed
|
||||||
|
case doesNotExist
|
||||||
|
|
||||||
|
public var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .unsupportedType:
|
||||||
|
return "The key type was unsupported"
|
||||||
|
case .parsingFailed:
|
||||||
|
return "Failed to properly parse the SSH certificate"
|
||||||
|
case .doesNotExist:
|
||||||
|
return "Certificate does not exist"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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,13 +1,18 @@
|
|||||||
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reads the next chunk of data from the playload.
|
||||||
|
/// - Returns: The next chunk of data.
|
||||||
public func readNextChunk() -> 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]
|
@ -0,0 +1,69 @@
|
|||||||
|
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 any untracked files in the directory should be removed.
|
||||||
|
public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws {
|
||||||
|
logger.log("Writing public keys to disk")
|
||||||
|
if clear {
|
||||||
|
let validPaths = Set(secrets.map { publicKeyPath(for: $0) }).union(Set(secrets.map { sshCertificatePath(for: $0) }))
|
||||||
|
let untracked = Set(try FileManager.default.contentsOfDirectory(atPath: directory)
|
||||||
|
.map { "\(directory)/\($0)" })
|
||||||
|
.subtracting(validPaths)
|
||||||
|
for path in untracked {
|
||||||
|
try? FileManager.default.removeItem(at: URL(fileURLWithPath: path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try? FileManager.default.createDirectory(at: URL(fileURLWithPath: directory), withIntermediateDirectories: false, attributes: nil)
|
||||||
|
for secret in secrets {
|
||||||
|
let path = publicKeyPath(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 publicKeyPath<SecretType: Secret>(for secret: SecretType) -> String {
|
||||||
|
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||||
|
return directory.appending("/").appending("\(minimalHex).pub")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short-circuit check to ship enumerating a bunch of paths if there's nothing in the cert directory.
|
||||||
|
public var hasAnyCertificates: Bool {
|
||||||
|
do {
|
||||||
|
return try FileManager.default
|
||||||
|
.contentsOfDirectory(atPath: directory)
|
||||||
|
.filter { $0.hasSuffix("-cert.pub") }
|
||||||
|
.isEmpty == false
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path for a Secret's SSH Certificate public key.
|
||||||
|
/// - Parameter secret: The Secret to return the path for.
|
||||||
|
/// - Returns: The path to the SSH Certificate public key.
|
||||||
|
/// - Warning: This method returning a path does not imply that a key has a SSH certificates. This method only describes where it will be.
|
||||||
|
public func sshCertificatePath<SecretType: Secret>(for secret: SecretType) -> String {
|
||||||
|
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||||
|
return directory.appending("/").appending("\(minimalHex)-cert.pub")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,39 +1,49 @@
|
|||||||
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?
|
||||||
private var sinks: [AnyCancellable] = []
|
private var cancellables: Set<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 {
|
public var anyAvailable: Bool {
|
||||||
stores.reduce(false, { $0 || $1.isAvailable })
|
stores.reduce(false, { $0 || $1.isAvailable })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public var allSecrets: [AnySecret] {
|
||||||
|
stores.flatMap(\.secrets)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SecretStoreList {
|
extension SecretStoreList {
|
||||||
|
|
||||||
private func addInternal(store: AnySecretStore) {
|
private func addInternal(store: AnySecretStore) {
|
||||||
stores.append(store)
|
stores.append(store)
|
||||||
let sink = store.objectWillChange.sink {
|
store.objectWillChange.sink {
|
||||||
self.objectWillChange.send()
|
self.objectWillChange.send()
|
||||||
}
|
}.store(in: &cancellables)
|
||||||
sinks.append(sink)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Protocol describing a persisted authentication context. This is an authorization that can be reused for multiple access to a secret that requires authentication for a specific period of time.
|
||||||
|
public protocol PersistedAuthenticationContext {
|
||||||
|
/// Whether the context remains valid.
|
||||||
|
var valid: Bool { get }
|
||||||
|
/// The date at which the authorization expires and the context becomes invalid.
|
||||||
|
var expiration: Date { get }
|
||||||
|
}
|
35
Sources/Packages/Sources/SecretKit/Types/Secret.swift
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
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 }
|
||||||
|
/// Whether the secret requires authentication before use.
|
||||||
|
var requiresAuthentication: Bool { 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
73
Sources/Packages/Sources/SecretKit/Types/SecretStore.swift
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
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: The signed data.
|
||||||
|
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data
|
||||||
|
|
||||||
|
/// Checks to see if there is currently a valid persisted authentication for a given secret.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - secret: The ``Secret`` to check if there is a persisted authentication for.
|
||||||
|
/// - Returns: A persisted authentication context, if a valid one exists.
|
||||||
|
func existingPersistedAuthenticationContext(secret: SecretType) -> PersistedAuthenticationContext?
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
|
||||||
|
/// Requests that the store reload secrets from any backing store, if neccessary.
|
||||||
|
func reloadSecrets()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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")
|
||||||
|
|
||||||
|
}
|
@ -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,14 +1,17 @@
|
|||||||
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
|
||||||
public let name: String
|
public let name: String
|
||||||
public let algorithm = Algorithm.ellipticCurve
|
public let algorithm = Algorithm.ellipticCurve
|
||||||
public let keySize = 256
|
public let keySize = 256
|
||||||
|
public let requiresAuthentication: Bool
|
||||||
public let publicKey: Data
|
public let publicKey: Data
|
||||||
|
|
||||||
}
|
}
|
@ -0,0 +1,337 @@
|
|||||||
|
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.reloadSecretsInternal(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)
|
||||||
|
reloadSecretsInternal()
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
reloadSecretsInternal()
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
reloadSecretsInternal()
|
||||||
|
}
|
||||||
|
|
||||||
|
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data {
|
||||||
|
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?
|
||||||
|
|
||||||
|
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
||||||
|
throw SigningError(error: signError)
|
||||||
|
}
|
||||||
|
return signature as Data
|
||||||
|
}
|
||||||
|
|
||||||
|
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? {
|
||||||
|
guard let persisted = persistedAuthenticationContexts[secret], persisted.valid else { return nil }
|
||||||
|
return persisted
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public func reloadSecrets() {
|
||||||
|
reloadSecretsInternal(notifyAgent: false)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
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 reloadSecretsInternal(notifyAgent: Bool = true) {
|
||||||
|
let before = secrets
|
||||||
|
secrets.removeAll()
|
||||||
|
loadSecrets()
|
||||||
|
if secrets != before {
|
||||||
|
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 publicAttributes = [
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||||
|
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||||
|
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
||||||
|
kSecReturnRef: true,
|
||||||
|
kSecMatchLimit: kSecMatchLimitAll,
|
||||||
|
kSecReturnAttributes: true
|
||||||
|
] as CFDictionary
|
||||||
|
var publicUntyped: CFTypeRef?
|
||||||
|
SecItemCopyMatching(publicAttributes, &publicUntyped)
|
||||||
|
guard let publicTyped = publicUntyped as? [[CFString: Any]] else { return }
|
||||||
|
let privateAttributes = [
|
||||||
|
kSecClass: kSecClassKey,
|
||||||
|
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||||
|
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||||
|
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||||
|
kSecReturnRef: true,
|
||||||
|
kSecMatchLimit: kSecMatchLimitAll,
|
||||||
|
kSecReturnAttributes: true
|
||||||
|
] as CFDictionary
|
||||||
|
var privateUntyped: CFTypeRef?
|
||||||
|
SecItemCopyMatching(privateAttributes, &privateUntyped)
|
||||||
|
guard let privateTyped = privateUntyped as? [[CFString: Any]] else { return }
|
||||||
|
let privateMapped = privateTyped.reduce(into: [:] as [Data: [CFString: Any]]) { partialResult, next in
|
||||||
|
let id = next[kSecAttrApplicationLabel] as! Data
|
||||||
|
partialResult[id] = next
|
||||||
|
}
|
||||||
|
let authNotRequiredAccessControl: SecAccessControl =
|
||||||
|
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
||||||
|
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||||
|
[.privateKeyUsage],
|
||||||
|
nil)!
|
||||||
|
|
||||||
|
let wrapped: [SecureEnclave.Secret] = publicTyped.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
|
||||||
|
let privateKey = privateMapped[id]
|
||||||
|
let requiresAuth: Bool
|
||||||
|
if let authRequirements = privateKey?[kSecAttrAccessControl] {
|
||||||
|
// Unfortunately we can't inspect the access control object directly, but it does behave predicatable with equality.
|
||||||
|
requiresAuth = authRequirements as! SecAccessControl != authNotRequiredAccessControl
|
||||||
|
} else {
|
||||||
|
requiresAuth = false
|
||||||
|
}
|
||||||
|
return SecureEnclave.Secret(id: id, name: name, requiresAuthentication: requiresAuth, 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: PersistedAuthenticationContext {
|
||||||
|
|
||||||
|
/// 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 monotonicExpiration: 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.monotonicExpiration = 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) < monotonicExpiration
|
||||||
|
}
|
||||||
|
|
||||||
|
var expiration: Date {
|
||||||
|
let remainingNanoseconds = monotonicExpiration - clock_gettime_nsec_np(CLOCK_MONOTONIC)
|
||||||
|
let remainingInSeconds = Measurement(value: Double(remainingNanoseconds), unit: UnitDuration.nanoseconds).converted(to: .seconds).value
|
||||||
|
return Date(timeIntervalSinceNow: remainingInSeconds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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,14 +1,17 @@
|
|||||||
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
|
||||||
public let name: String
|
public let name: String
|
||||||
public let algorithm: Algorithm
|
public let algorithm: Algorithm
|
||||||
public let keySize: Int
|
public let keySize: Int
|
||||||
|
public let requiresAuthentication: Bool = false
|
||||||
public let publicKey: Data
|
public let publicKey: Data
|
||||||
|
|
||||||
}
|
}
|
@ -2,14 +2,13 @@ import Foundation
|
|||||||
import Security
|
import Security
|
||||||
import CryptoTokenKit
|
import CryptoTokenKit
|
||||||
import LocalAuthentication
|
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 private(set) var name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
public private(set) var name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||||
@ -17,6 +16,7 @@ extension SmartCard {
|
|||||||
private let watcher = TKTokenWatcher()
|
private let watcher = TKTokenWatcher()
|
||||||
private var tokenID: String?
|
private var tokenID: String?
|
||||||
|
|
||||||
|
/// Initializes a Store.
|
||||||
public init() {
|
public init() {
|
||||||
tokenID = watcher.nonSecureEnclaveTokens.first
|
tokenID = watcher.nonSecureEnclaveTokens.first
|
||||||
watcher.setInsertionHandler { string in
|
watcher.setInsertionHandler { string in
|
||||||
@ -56,7 +56,7 @@ extension SmartCard {
|
|||||||
kSecAttrTokenID: tokenID,
|
kSecAttrTokenID: tokenID,
|
||||||
kSecUseAuthenticationContext: context,
|
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 {
|
||||||
@ -82,33 +82,58 @@ extension SmartCard {
|
|||||||
return signature as Data
|
return signature as Data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public func existingPersistedAuthenticationContext(secret: SmartCard.Secret) -> PersistedAuthenticationContext? {
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: SmartCard.Secret, forDuration: TimeInterval) throws {
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reloads all secrets from the store.
|
||||||
|
public func reloadSecrets() {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.isAvailable = self.tokenID != nil
|
||||||
|
let before = self.secrets
|
||||||
|
self.secrets.removeAll()
|
||||||
|
self.loadSecrets()
|
||||||
|
if self.secrets != before {
|
||||||
|
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SmartCard.Store {
|
extension SmartCard.Store {
|
||||||
|
|
||||||
|
/// Resets the token ID and reloads secrets.
|
||||||
|
/// - Parameter tokenID: The ID of the token that was removed.
|
||||||
private func smartcardRemoved(for tokenID: String? = nil) {
|
private func smartcardRemoved(for tokenID: String? = nil) {
|
||||||
self.tokenID = nil
|
self.tokenID = nil
|
||||||
reloadSecrets()
|
reloadSecrets()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func reloadSecrets() {
|
/// Loads all secrets from the store.
|
||||||
DispatchQueue.main.async {
|
|
||||||
self.isAvailable = self.tokenID != nil
|
|
||||||
self.secrets.removeAll()
|
|
||||||
self.loadSecrets()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func loadSecrets() {
|
private func loadSecrets() {
|
||||||
guard let tokenID = tokenID else { return }
|
guard let tokenID = tokenID else { return }
|
||||||
// Hack to read name if there's only one smart card
|
|
||||||
let slotNames = TKSmartCardSlotManager().slotNames
|
let fallbackName = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||||
if watcher.nonSecureEnclaveTokens.count == 1 && slotNames.count == 1 {
|
if #available(macOS 12.0, *) {
|
||||||
name = slotNames.first!
|
if let driverName = watcher.tokenInfo(forTokenID: tokenID)?.driverName {
|
||||||
|
name = driverName
|
||||||
|
} else {
|
||||||
|
name = fallbackName
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
// 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 = [
|
||||||
@ -118,7 +143,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 }
|
||||||
@ -140,6 +165,7 @@ extension SmartCard.Store {
|
|||||||
|
|
||||||
extension TKTokenWatcher {
|
extension TKTokenWatcher {
|
||||||
|
|
||||||
|
/// All available tokens, excluding the Secure Enclave.
|
||||||
fileprivate var nonSecureEnclaveTokens: [String] {
|
fileprivate var nonSecureEnclaveTokens: [String] {
|
||||||
tokenIDs.filter { !$0.contains("setoken") }
|
tokenIDs.filter { !$0.contains("setoken") }
|
||||||
}
|
}
|
||||||
@ -148,11 +174,15 @@ extension TKTokenWatcher {
|
|||||||
|
|
||||||
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -27,6 +27,21 @@ class SemVerTests: XCTestCase {
|
|||||||
XCTAssert(current < new)
|
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() {
|
func testBeta() {
|
||||||
let current = SemVer("1.0.2")
|
let current = SemVer("1.0.2")
|
||||||
let new = SemVer("1.1.0_beta1")
|
let new = SemVer("1.1.0_beta1")
|
@ -1,3 +1,4 @@
|
|||||||
|
import Foundation
|
||||||
import SecretAgentKit
|
import SecretAgentKit
|
||||||
|
|
||||||
class StubFileHandleWriter: FileHandleWriter {
|
class StubFileHandleWriter: FileHandleWriter {
|
@ -1,3 +1,4 @@
|
|||||||
|
import Foundation
|
||||||
import SecretKit
|
import SecretKit
|
||||||
import CryptoKit
|
import CryptoKit
|
||||||
|
|
||||||
@ -50,7 +51,7 @@ extension Stub {
|
|||||||
|
|
||||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||||
guard !shouldThrow else {
|
guard !shouldThrow else {
|
||||||
throw NSError()
|
throw NSError(domain: "test", code: 0, userInfo: nil)
|
||||||
}
|
}
|
||||||
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, [
|
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, [
|
||||||
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
||||||
@ -70,6 +71,16 @@ extension Stub {
|
|||||||
return SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data
|
return SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public func existingPersistedAuthenticationContext(secret: Stub.Secret) -> PersistedAuthenticationContext? {
|
||||||
|
nil
|
||||||
|
}
|
||||||
|
|
||||||
|
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
|
||||||
|
}
|
||||||
|
|
||||||
|
public func reloadSecrets() {
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -84,6 +95,7 @@ extension Stub {
|
|||||||
|
|
||||||
let keySize: Int
|
let keySize: Int
|
||||||
let publicKey: Data
|
let publicKey: Data
|
||||||
|
let requiresAuthentication = false
|
||||||
let privateKey: Data
|
let privateKey: Data
|
||||||
|
|
||||||
init(keySize: Int, publicKey: Data, privateKey: Data) {
|
init(keySize: Int, publicKey: Data, privateKey: Data) {
|
@ -10,14 +10,14 @@ struct StubWitness {
|
|||||||
|
|
||||||
extension StubWitness: SigningWitness {
|
extension StubWitness: SigningWitness {
|
||||||
|
|
||||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||||
let objection = speakNow(secret, provenance)
|
let objection = speakNow(secret, provenance)
|
||||||
if objection {
|
if objection {
|
||||||
throw TheresMyChance()
|
throw TheresMyChance()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func witness(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||||
witness(secret, provenance)
|
witness(secret, provenance)
|
||||||
}
|
}
|
||||||
|
|
@ -1,6 +1,8 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import XCTest
|
import XCTest
|
||||||
@testable import SecretKit
|
@testable import SecretKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
class AnySecretTests: XCTestCase {
|
class AnySecretTests: XCTestCase {
|
||||||
|
|
@ -1,6 +1,8 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import XCTest
|
import XCTest
|
||||||
@testable import SecretKit
|
@testable import SecretKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
class OpenSSHReaderTests: XCTestCase {
|
class OpenSSHReaderTests: XCTestCase {
|
||||||
|
|
@ -1,13 +1,19 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import XCTest
|
import XCTest
|
||||||
@testable import SecretKit
|
@testable import SecretKit
|
||||||
|
@testable import SecureEnclaveSecretKit
|
||||||
|
@testable import SmartCardSecretKit
|
||||||
|
|
||||||
class OpenSSHWriterTests: XCTestCase {
|
class OpenSSHWriterTests: XCTestCase {
|
||||||
|
|
||||||
let writer = OpenSSHKeyWriter()
|
let writer = OpenSSHKeyWriter()
|
||||||
|
|
||||||
func testECDSA256Fingerprint() {
|
func testECDSA256MD5Fingerprint() {
|
||||||
XCTAssertEqual(writer.openSSHFingerprint(secret: Constants.ecdsa256Secret), "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5")
|
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() {
|
func testECDSA256PublicKey() {
|
||||||
@ -19,8 +25,12 @@ class OpenSSHWriterTests: XCTestCase {
|
|||||||
XCTAssertEqual(writer.data(secret: Constants.ecdsa256Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
XCTAssertEqual(writer.data(secret: Constants.ecdsa256Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testECDSA384Fingerprint() {
|
func testECDSA384MD5Fingerprint() {
|
||||||
XCTAssertEqual(writer.openSSHFingerprint(secret: Constants.ecdsa384Secret), "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e")
|
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() {
|
func testECDSA384PublicKey() {
|
@ -2,6 +2,8 @@ import Cocoa
|
|||||||
import OSLog
|
import OSLog
|
||||||
import Combine
|
import Combine
|
||||||
import SecretKit
|
import SecretKit
|
||||||
|
import SecureEnclaveSecretKit
|
||||||
|
import SmartCardSecretKit
|
||||||
import SecretAgentKit
|
import SecretAgentKit
|
||||||
import Brief
|
import Brief
|
||||||
|
|
||||||
@ -16,6 +18,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
}()
|
}()
|
||||||
private let updater = Updater(checkOnLaunch: false)
|
private let updater = Updater(checkOnLaunch: false)
|
||||||
private let notifier = Notifier()
|
private let notifier = Notifier()
|
||||||
|
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
|
||||||
private lazy var agent: Agent = {
|
private lazy var agent: Agent = {
|
||||||
Agent(storeList: storeList, witness: notifier)
|
Agent(storeList: storeList, witness: notifier)
|
||||||
}()
|
}()
|
||||||
@ -30,6 +33,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.socketController.handler = self.agent.handle(reader:writer:)
|
self.socketController.handler = self.agent.handle(reader:writer:)
|
||||||
}
|
}
|
||||||
|
NotificationCenter.default.addObserver(forName: .secretStoreReloaded, object: nil, queue: .main) { [self] _ in
|
||||||
|
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true)
|
||||||
|
}
|
||||||
|
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true)
|
||||||
notifier.prompt()
|
notifier.prompt()
|
||||||
updateSink = updater.$update.sink { update in
|
updateSink = updater.$update.sink { update in
|
||||||
guard let update = update else { return }
|
guard let update = update else { return }
|
||||||
@ -37,6 +44,5 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 40 KiB |
31
Sources/SecretAgent/InternetAccessPolicy.plist
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
<?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>ApplicationDescription</key>
|
||||||
|
<string>Secretive is an app for storing and managing SSH keys in the Secure Enclave. SecretAgent is a helper process that runs in the background to sign requests, so that you don't always have to keep the main Secretive app open.</string>
|
||||||
|
<key>DeveloperName</key>
|
||||||
|
<string>Max Goedjen</string>
|
||||||
|
<key>Website</key>
|
||||||
|
<string>https://github.com/maxgoedjen/secretive</string>
|
||||||
|
<key>Connections</key>
|
||||||
|
<array>
|
||||||
|
<dict>
|
||||||
|
<key>IsIncoming</key>
|
||||||
|
<false/>
|
||||||
|
<key>Host</key>
|
||||||
|
<string>api.github.com</string>
|
||||||
|
<key>NetworkProtocol</key>
|
||||||
|
<string>TCP</string>
|
||||||
|
<key>Port</key>
|
||||||
|
<string>443</string>
|
||||||
|
<key>Purpose</key>
|
||||||
|
<string>Secretive checks GitHub for new versions and security updates.</string>
|
||||||
|
<key>DenyConsequences</key>
|
||||||
|
<string>If you deny these connections, you will not be notified about new versions and critical security updates.</string>
|
||||||
|
</dict>
|
||||||
|
</array>
|
||||||
|
<key>Services</key>
|
||||||
|
<array/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
187
Sources/SecretAgent/Notifier.swift
Normal file
@ -0,0 +1,187 @@
|
|||||||
|
import Foundation
|
||||||
|
import UserNotifications
|
||||||
|
import AppKit
|
||||||
|
import SecretKit
|
||||||
|
import SecretAgentKit
|
||||||
|
import Brief
|
||||||
|
|
||||||
|
class Notifier {
|
||||||
|
|
||||||
|
private let notificationDelegate = NotificationDelegate()
|
||||||
|
|
||||||
|
init() {
|
||||||
|
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: "Update", options: [])
|
||||||
|
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: "Ignore", options: [])
|
||||||
|
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
|
||||||
|
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
|
||||||
|
|
||||||
|
let rawDurations = [
|
||||||
|
Measurement(value: 1, unit: UnitDuration.minutes),
|
||||||
|
Measurement(value: 5, unit: UnitDuration.minutes),
|
||||||
|
Measurement(value: 1, unit: UnitDuration.hours),
|
||||||
|
Measurement(value: 24, unit: UnitDuration.hours)
|
||||||
|
]
|
||||||
|
|
||||||
|
let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: "Do Not Unlock", options: [])
|
||||||
|
var allPersistenceActions = [doNotPersistAction]
|
||||||
|
|
||||||
|
let formatter = DateComponentsFormatter()
|
||||||
|
formatter.unitsStyle = .spellOut
|
||||||
|
formatter.allowedUnits = [.hour, .minute, .day]
|
||||||
|
|
||||||
|
for duration in rawDurations {
|
||||||
|
let seconds = duration.converted(to: .seconds).value
|
||||||
|
guard let string = formatter.string(from: seconds)?.capitalized else { continue }
|
||||||
|
let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)")
|
||||||
|
let action = UNNotificationAction(identifier: identifier, title: string, options: [])
|
||||||
|
notificationDelegate.persistOptions[identifier] = seconds
|
||||||
|
allPersistenceActions.append(action)
|
||||||
|
}
|
||||||
|
|
||||||
|
let persistAuthenticationCategory = UNNotificationCategory(identifier: Constants.persistAuthenticationCategoryIdentitifier, actions: allPersistenceActions, intentIdentifiers: [], options: [])
|
||||||
|
if persistAuthenticationCategory.responds(to: Selector(("actionsMenuTitle"))) {
|
||||||
|
persistAuthenticationCategory.setValue("Leave Unlocked", forKey: "_actionsMenuTitle")
|
||||||
|
}
|
||||||
|
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory])
|
||||||
|
UNUserNotificationCenter.current().delegate = notificationDelegate
|
||||||
|
|
||||||
|
notificationDelegate.persistAuthentication = { secret, store, duration in
|
||||||
|
guard let duration = duration else { return }
|
||||||
|
try? store.persistAuthentication(secret: secret, forDuration: duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func prompt() {
|
||||||
|
let notificationCenter = UNUserNotificationCenter.current()
|
||||||
|
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
||||||
|
}
|
||||||
|
|
||||||
|
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) {
|
||||||
|
notificationDelegate.pendingPersistableSecrets[secret.id.description] = secret
|
||||||
|
notificationDelegate.pendingPersistableStores[store.id.description] = store
|
||||||
|
let notificationCenter = UNUserNotificationCenter.current()
|
||||||
|
let notificationContent = UNMutableNotificationContent()
|
||||||
|
notificationContent.title = "Signed Request from \(provenance.origin.displayName)"
|
||||||
|
notificationContent.subtitle = "Using secret \"\(secret.name)\""
|
||||||
|
notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description
|
||||||
|
notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description
|
||||||
|
if #available(macOS 12.0, *) {
|
||||||
|
notificationContent.interruptionLevel = .timeSensitive
|
||||||
|
}
|
||||||
|
if secret.requiresAuthentication && store.existingPersistedAuthenticationContext(secret: secret) == nil {
|
||||||
|
notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier
|
||||||
|
}
|
||||||
|
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
||||||
|
notificationContent.attachments = [attachment]
|
||||||
|
}
|
||||||
|
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||||
|
notificationCenter.add(request, withCompletionHandler: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func notify(update: Release, ignore: ((Release) -> Void)?) {
|
||||||
|
notificationDelegate.release = update
|
||||||
|
notificationDelegate.ignore = ignore
|
||||||
|
let notificationCenter = UNUserNotificationCenter.current()
|
||||||
|
let notificationContent = UNMutableNotificationContent()
|
||||||
|
if update.critical {
|
||||||
|
if #available(macOS 12.0, *) {
|
||||||
|
notificationContent.interruptionLevel = .critical
|
||||||
|
}
|
||||||
|
notificationContent.title = "Critical Security Update - \(update.name)"
|
||||||
|
} else {
|
||||||
|
notificationContent.title = "Update Available - \(update.name)"
|
||||||
|
}
|
||||||
|
notificationContent.subtitle = "Click to Update"
|
||||||
|
notificationContent.body = update.body
|
||||||
|
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
|
||||||
|
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||||
|
notificationCenter.add(request, withCompletionHandler: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Notifier: SigningWitness {
|
||||||
|
|
||||||
|
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||||
|
}
|
||||||
|
|
||||||
|
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||||
|
notify(accessTo: secret, from: store, by: provenance)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Notifier {
|
||||||
|
|
||||||
|
enum Constants {
|
||||||
|
|
||||||
|
// Update notifications
|
||||||
|
static let updateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update"
|
||||||
|
static let criticalUpdateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.critical"
|
||||||
|
static let updateActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.updateaction"
|
||||||
|
static let ignoreActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.ignoreaction"
|
||||||
|
|
||||||
|
// Authorization persistence notificatoins
|
||||||
|
static let persistAuthenticationCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication"
|
||||||
|
static let doNotPersistActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.donotpersist"
|
||||||
|
static let persistForActionIdentitifierPrefix = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.persist."
|
||||||
|
|
||||||
|
static let persistSecretIDKey = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.secretidkey"
|
||||||
|
static let persistStoreIDKey = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.storeidkey"
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
|
||||||
|
|
||||||
|
fileprivate var release: Release?
|
||||||
|
fileprivate var ignore: ((Release) -> Void)?
|
||||||
|
fileprivate var persistAuthentication: ((AnySecret, AnySecretStore, TimeInterval?) -> Void)?
|
||||||
|
fileprivate var persistOptions: [String: TimeInterval] = [:]
|
||||||
|
fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
|
||||||
|
fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
|
||||||
|
|
||||||
|
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
|
||||||
|
let category = response.notification.request.content.categoryIdentifier
|
||||||
|
switch category {
|
||||||
|
case Notifier.Constants.updateCategoryIdentitifier:
|
||||||
|
handleUpdateResponse(response: response)
|
||||||
|
case Notifier.Constants.persistAuthenticationCategoryIdentitifier:
|
||||||
|
handlePersistAuthenticationResponse(response: response)
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
completionHandler()
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleUpdateResponse(response: UNNotificationResponse) {
|
||||||
|
guard let update = release else { return }
|
||||||
|
switch response.actionIdentifier {
|
||||||
|
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
|
||||||
|
NSWorkspace.shared.open(update.html_url)
|
||||||
|
case Notifier.Constants.ignoreActionIdentitifier:
|
||||||
|
ignore?(update)
|
||||||
|
default:
|
||||||
|
fatalError()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func handlePersistAuthenticationResponse(response: UNNotificationResponse) {
|
||||||
|
guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String, let secret = pendingPersistableSecrets[secretID],
|
||||||
|
let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = pendingPersistableStores[storeID]
|
||||||
|
else { return }
|
||||||
|
pendingPersistableSecrets[secretID] = nil
|
||||||
|
persistAuthentication?(secret, store, persistOptions[response.actionIdentifier])
|
||||||
|
}
|
||||||
|
|
||||||
|
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
|
||||||
|
completionHandler([.list, .banner])
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|