Compare commits
154 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 23a1f61e5a | |||
| eb945b2849 | |||
| bf081835c4 | |||
| 9503f406ae | |||
| e77f00ff48 | |||
| 3d8a5e9076 | |||
| 00db2d1948 | |||
| d7111594a7 | |||
| 20b84b9d4e | |||
| 1182f472dd | |||
| 62f237f859 | |||
| 22fd00bd22 | |||
| b6030ec4bd | |||
| 9730e3da74 | |||
| 95657fd844 | |||
| a7bfeb9c3f | |||
| ac04615219 | |||
| cddb00ab95 | |||
| 7c532639d4 | |||
| d2a856dd48 | |||
| d5395ea4e5 | |||
| 0d0f64ff1b | |||
| edf4c5a45d | |||
| ae39e136de | |||
| defc1c1131 | |||
| af71a17f51 | |||
| 02a81adfeb | |||
| 956d3bf28a | |||
| d9c5abaa15 | |||
| c5ca61a37c | |||
| e86cd8113c | |||
| e037c1c883 | |||
| 051cace1fd | |||
| 4e053b5efc | |||
| 762adfe098 | |||
| 70c109aa1d | |||
| 355ce1cfde | |||
| 3408998283 | |||
| bf437663af | |||
| 665aedbbba | |||
| 307f5396a8 | |||
| cd03e7bda3 | |||
| 54ad666c73 | |||
| d2132b4ac2 | |||
| 80e8072624 | |||
| ff3e8e37c9 | |||
| a5178bb16e | |||
| b1710e8d69 | |||
| 8483010393 | |||
| 55bfa5dafb | |||
| 90b61682bd | |||
| 97ddfc3bea | |||
| f34c534e84 | |||
| 681cd06087 | |||
| 45f6580be4 | |||
| f5c8f7a559 | |||
| e26ed3a163 | |||
| 04c0418c02 | |||
| 00ab2c756e | |||
| 9418921dab | |||
| 87541510ad | |||
| 9ac72cd66f | |||
| 093a35733f | |||
| 082a4f976c | |||
| 3e1f3b45f5 | |||
| a6a5ad109e | |||
| 25fcd353f3 | |||
| d8ab6e373e | |||
| 0490dd3529 | |||
| f45ff653b8 | |||
| e78871d6f3 | |||
| ec83a8c9cc | |||
| fc2081c216 | |||
| 367a081eea | |||
| cfb1e5e3d5 | |||
| 1dfadc7e27 | |||
| fc66d9f6fd | |||
| d8eb198e97 | |||
| c8f9df1b45 | |||
| 3597d96332 | |||
| 1913838f8e | |||
| 6e47448560 | |||
| 4d4d8cc183 | |||
| ac7b04a61d | |||
| 493479344c | |||
| d4f8993988 | |||
| 876afecc5c | |||
| 539111c30c | |||
| 647a620a9c | |||
| 0eee944c64 | |||
| e4ef700263 | |||
| 492612fc8b | |||
| 15c53e42df | |||
| 5d6b618d5f | |||
| 0ee618cdfd | |||
| ed6273d781 | |||
| d38743a2fc | |||
| aaa445c4ac | |||
| e415ce4ae9 | |||
| 145237003e | |||
| 9338b320a4 | |||
| aae48c4f6c | |||
| 08ba0aa1ec | |||
| 71bd3b1afb | |||
| 8199a7bcfc | |||
| b825956bf8 | |||
| fb5a1060bd | |||
| b9842213da | |||
| f8314c5d6d | |||
| 3b0da8bd25 | |||
| 345c155bb4 | |||
| 1ad79cb577 | |||
| a92a843e14 | |||
| c4fe3f6b1a | |||
| 9db9c65bf7 | |||
| 1b5db6f871 | |||
| 5f07cb318d | |||
| 71227314f4 | |||
| f2f0b40af8 | |||
| fe5bab1277 | |||
| 5afec288c9 | |||
| 7d2e3a6829 | |||
| 74b76d3f5e | |||
| 6fd6a205ca | |||
| 0b930efc49 | |||
| 2fd5af8538 | |||
| 5814f5f1a0 | |||
| 37c813e0a7 | |||
| 60b36e39c8 | |||
| da9212c135 | |||
| dcdf306d3a | |||
| f0ba5724bf | |||
| f1bb46d274 | |||
| b3590f4ce1 | |||
| 2fc2dcd1c3 | |||
| 68ac19017e | |||
| e5bdffa5cc | |||
| 51910edfab | |||
| 4f30e2e6f6 | |||
| 37f1a07b60 | |||
| 822a10f8f6 | |||
| b486276421 | |||
| c7ad7a671b | |||
| f2237ed2a7 | |||
| 399f0b4c11 | |||
| 22dfc3ee89 | |||
| 72d5682454 | |||
| 77bd7aa3a3 | |||
| 5c8a7cced8 | |||
| 6042d5266f | |||
| f5f140d172 | |||
| 2c90195f99 | |||
| 30f4d00902 | |||
| 7f43d15942 |
@@ -0,0 +1,12 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: github-actions
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: daily
|
||||||
|
timezone: Etc/UTC
|
||||||
|
open-pull-requests-limit: 10
|
||||||
|
reviewers:
|
||||||
|
- str4d
|
||||||
|
assignees:
|
||||||
|
- str4d
|
||||||
+18
-99
@@ -22,130 +22,49 @@ jobs:
|
|||||||
os: macos-latest
|
os: macos-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: 1.51.0
|
|
||||||
override: true
|
|
||||||
- name: Install build dependencies
|
- name: Install build dependencies
|
||||||
run: sudo apt install ${{ matrix.build_deps }}
|
run: sudo apt install ${{ matrix.build_deps }}
|
||||||
if: matrix.build_deps != ''
|
if: matrix.build_deps != ''
|
||||||
- name: cargo fetch
|
- name: Install test dependencies
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo install rage
|
||||||
with:
|
- run: cargo fetch
|
||||||
command: fetch
|
|
||||||
- name: Build tests
|
- name: Build tests
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo build --verbose --tests
|
||||||
with:
|
|
||||||
command: build
|
|
||||||
args: --verbose --tests
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo test --verbose
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --verbose
|
|
||||||
|
|
||||||
clippy:
|
|
||||||
name: Clippy (1.51.0)
|
|
||||||
timeout-minutes: 30
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
- uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: 1.51.0
|
|
||||||
components: clippy
|
|
||||||
override: true
|
|
||||||
- name: Install build dependencies
|
|
||||||
run: sudo apt install libpcsclite-dev
|
|
||||||
- name: Run clippy
|
|
||||||
uses: actions-rs/clippy-check@v1
|
|
||||||
with:
|
|
||||||
name: Clippy (1.51.0)
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
args: --all-features --all-targets -- -D warnings
|
|
||||||
|
|
||||||
clippy-nightly:
|
|
||||||
name: Clippy (nightly)
|
|
||||||
timeout-minutes: 30
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
continue-on-error: true
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
- uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: nightly
|
|
||||||
components: clippy
|
|
||||||
override: true
|
|
||||||
- name: Install build dependencies
|
|
||||||
run: sudo apt install libpcsclite-dev
|
|
||||||
- name: Run Clippy (nightly)
|
|
||||||
uses: actions-rs/clippy-check@v1
|
|
||||||
continue-on-error: true
|
|
||||||
with:
|
|
||||||
name: Clippy (nightly)
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
args: --all-features --all-targets
|
|
||||||
|
|
||||||
codecov:
|
codecov:
|
||||||
name: Code coverage
|
name: Code coverage
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
# Use stable for this to ensure that cargo-tarpaulin can be built.
|
|
||||||
- uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: stable
|
|
||||||
override: true
|
|
||||||
- name: Install build dependencies
|
- name: Install build dependencies
|
||||||
run: sudo apt install libpcsclite-dev
|
run: sudo apt install libpcsclite-dev
|
||||||
|
- name: Install coverage dependencies
|
||||||
|
run: cargo install cargo-tarpaulin
|
||||||
- name: Generate coverage report
|
- name: Generate coverage report
|
||||||
uses: actions-rs/tarpaulin@v0.1
|
run: cargo tarpaulin --engine llvm --all-features --release --timeout 600 --out Xml
|
||||||
with:
|
|
||||||
args: --release --timeout 180 --out Xml
|
|
||||||
- name: Upload coverage to Codecov
|
- name: Upload coverage to Codecov
|
||||||
uses: codecov/codecov-action@v1.0.3
|
uses: codecov/codecov-action@v3.1.1
|
||||||
with:
|
|
||||||
token: ${{secrets.CODECOV_TOKEN}}
|
|
||||||
|
|
||||||
doc-links:
|
doc-links:
|
||||||
name: Intra-doc links
|
name: Intra-doc links
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: 1.51.0
|
|
||||||
override: true
|
|
||||||
- name: Install build dependencies
|
- name: Install build dependencies
|
||||||
run: sudo apt install libpcsclite-dev
|
run: sudo apt install libpcsclite-dev
|
||||||
- name: cargo fetch
|
- run: cargo fetch
|
||||||
uses: actions-rs/cargo@v1
|
# Requires #![deny(rustdoc::broken_intra_doc_links)] in crates.
|
||||||
with:
|
|
||||||
command: fetch
|
|
||||||
|
|
||||||
# Ensure intra-documentation links all resolve correctly
|
|
||||||
# Requires #![deny(intra_doc_link_resolution_failure)] in crates.
|
|
||||||
- name: Check intra-doc links
|
- name: Check intra-doc links
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo doc --document-private-items
|
||||||
with:
|
|
||||||
command: doc
|
|
||||||
args: --document-private-items
|
|
||||||
|
|
||||||
fmt:
|
fmt:
|
||||||
name: Rustfmt
|
name: Rustfmt
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- uses: actions-rs/toolchain@v1
|
- name: Check formatting
|
||||||
with:
|
run: cargo fmt -- --check
|
||||||
toolchain: 1.51.0
|
|
||||||
override: true
|
|
||||||
- run: rustup component add rustfmt
|
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: fmt
|
|
||||||
args: -- --check
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
name: Beta lints
|
||||||
|
|
||||||
|
# We only run these lints on trial-merges of PRs to reduce noise.
|
||||||
|
on: pull_request
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
clippy-beta:
|
||||||
|
name: Clippy (beta)
|
||||||
|
timeout-minutes: 30
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: dtolnay/rust-toolchain@beta
|
||||||
|
id: toolchain
|
||||||
|
- run: rustup override set ${{steps.toolchain.outputs.name}}
|
||||||
|
- name: Install build dependencies
|
||||||
|
run: sudo apt install libpcsclite-dev
|
||||||
|
- name: Clippy (beta)
|
||||||
|
uses: actions-rs/clippy-check@v1
|
||||||
|
with:
|
||||||
|
name: Clippy (beta)
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
args: --all-features --all-targets -- -W clippy::all
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
name: Stable lints
|
||||||
|
|
||||||
|
# We only run these lints on trial-merges of PRs to reduce noise.
|
||||||
|
on: pull_request
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
clippy:
|
||||||
|
name: Clippy (MSRV)
|
||||||
|
timeout-minutes: 30
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Install build dependencies
|
||||||
|
run: sudo apt install libpcsclite-dev
|
||||||
|
- name: Run clippy
|
||||||
|
uses: actions-rs/clippy-check@v1
|
||||||
|
with:
|
||||||
|
name: Clippy (MSRV)
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
args: --all-features --all-targets -- -D warnings
|
||||||
@@ -17,10 +17,14 @@ jobs:
|
|||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
name: [linux, windows, macos]
|
name:
|
||||||
|
- linux
|
||||||
|
- macos-arm64
|
||||||
|
- macos-x86_64
|
||||||
|
- windows
|
||||||
include:
|
include:
|
||||||
- name: linux
|
- name: linux
|
||||||
os: ubuntu-16.04
|
os: ubuntu-18.04
|
||||||
build_deps: >
|
build_deps: >
|
||||||
libpcsclite-dev
|
libpcsclite-dev
|
||||||
archive_name: age-plugin-yubikey.tar.gz
|
archive_name: age-plugin-yubikey.tar.gz
|
||||||
@@ -31,13 +35,20 @@ jobs:
|
|||||||
archive_name: age-plugin-yubikey.zip
|
archive_name: age-plugin-yubikey.zip
|
||||||
asset_suffix: x86_64-windows.zip
|
asset_suffix: x86_64-windows.zip
|
||||||
|
|
||||||
- name: macos
|
- name: macos-arm64
|
||||||
|
os: macos-latest
|
||||||
|
target: aarch64-apple-darwin
|
||||||
|
build_flags: --target aarch64-apple-darwin
|
||||||
|
archive_name: age-plugin-yubikey.tar.gz
|
||||||
|
asset_suffix: arm64-darwin.tar.gz
|
||||||
|
|
||||||
|
- name: macos-x86_64
|
||||||
os: macos-latest
|
os: macos-latest
|
||||||
archive_name: age-plugin-yubikey.tar.gz
|
archive_name: age-plugin-yubikey.tar.gz
|
||||||
asset_suffix: x86_64-darwin.tar.gz
|
asset_suffix: x86_64-darwin.tar.gz
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
@@ -76,12 +87,10 @@ jobs:
|
|||||||
if: matrix.name == 'windows'
|
if: matrix.name == 'windows'
|
||||||
|
|
||||||
- name: Upload archive to release
|
- name: Upload archive to release
|
||||||
uses: svenstaro/upload-release-action@2.2.0
|
uses: svenstaro/upload-release-action@2.5.0
|
||||||
with:
|
with:
|
||||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
file: ${{ matrix.archive_name }}
|
file: ${{ matrix.archive_name }}
|
||||||
asset_name: age-plugin-yubikey-$tag-${{ matrix.asset_suffix }}
|
asset_name: age-plugin-yubikey-$tag-${{ matrix.asset_suffix }}
|
||||||
tag: ${{ github.ref }}
|
|
||||||
prerelease: true
|
prerelease: true
|
||||||
if: github.event.inputs.test != 'true'
|
if: github.event.inputs.test != 'true'
|
||||||
|
|
||||||
@@ -98,7 +107,7 @@ jobs:
|
|||||||
libpcsclite-dev
|
libpcsclite-dev
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
@@ -137,11 +146,9 @@ jobs:
|
|||||||
args: --package age-plugin-yubikey --no-build --target ${{ matrix.target }}
|
args: --package age-plugin-yubikey --no-build --target ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Upload Debian package to release
|
- name: Upload Debian package to release
|
||||||
uses: svenstaro/upload-release-action@2.2.0
|
uses: svenstaro/upload-release-action@2.5.0
|
||||||
with:
|
with:
|
||||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
file: target/${{ matrix.target }}/debian/*.deb
|
file: target/${{ matrix.target }}/debian/*.deb
|
||||||
tag: ${{ github.ref }}
|
|
||||||
file_glob: true
|
file_glob: true
|
||||||
prerelease: true
|
prerelease: true
|
||||||
if: github.event.inputs.test != 'true'
|
if: github.event.inputs.test != 'true'
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Changelog
|
||||||
|
All notable changes to this crate will be documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
|
and this project adheres to Rust's notion of
|
||||||
|
[Semantic Versioning](https://semver.org/spec/v2.0.0.html). All versions prior
|
||||||
|
to 0.3.0 are beta releases.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.3.4], [0.4.1] - 2026-04-08
|
||||||
|
### Fixed
|
||||||
|
- `age-plugin-yubikey` now completely ignores any identity that has unrecognised
|
||||||
|
critical extensions in its certificate, to ensure it doesn't misuse a newer
|
||||||
|
identity type.
|
||||||
|
|
||||||
|
## [0.4.0] - 2023-04-09
|
||||||
|
### Changed
|
||||||
|
- MSRV is now 1.65.0.
|
||||||
|
- The YubiKey PIV PIN and touch caches are now preserved across processes in
|
||||||
|
most cases. See [README.md](README.md#agent-support) for exceptions. This has
|
||||||
|
several usability effects (not applicable to YubiKey 4 series):
|
||||||
|
- If a YubiKey's PIN is cached by an agent like `yubikey-agent`, and then
|
||||||
|
`age-plugin-yubikey` is run (either directly or as a plugin), the agent
|
||||||
|
won't request a PIN entry on its next use.
|
||||||
|
- If a YubiKey's PIN was requested by either a previous invocation of
|
||||||
|
`age-plugin-yubikey` or an agent like `yubikey-agent`, subsequent calls to
|
||||||
|
`age-plugin-yubikey` won't request a PIN entry to decrypt a file with an
|
||||||
|
identity that has a PIN policy of `once`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Identities can now be generated with a PIN policy of "always" (in previous
|
||||||
|
versions of `age-plugin-yubikey` this would cause an error).
|
||||||
|
|
||||||
|
## [0.3.3] - 2023-02-11
|
||||||
|
### Fixed
|
||||||
|
- When `age-plugin-yubikey` assists the user in changing their PIN from the
|
||||||
|
default PIN, it no longer tells the user that PINs shorter than 6 characters
|
||||||
|
are allowed, and instead loops until the user enters a PIN of valid length.
|
||||||
|
It also now prevents the user from setting their PIN to the default PIN, to
|
||||||
|
avoid creating a cycle.
|
||||||
|
- More kinds of SmartCard readers are ignored when they have no SmartCard
|
||||||
|
inserted.
|
||||||
|
|
||||||
|
## [0.3.2] - 2023-01-01
|
||||||
|
### Changed
|
||||||
|
- The "sharing violation" logic now also sends SIGHUP to any `yubikey-agent`
|
||||||
|
that is running, to have them release any YubiKey locks they are holding.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The "sharing violation" logic now runs during plugin mode as intended. In the
|
||||||
|
previous release it only ran during direct `age-plugin-yubikey` usage.
|
||||||
|
|
||||||
|
## [0.3.1] - 2022-12-30
|
||||||
|
### Changed
|
||||||
|
- If a "sharing violation" error is encountered while opening a connection to a
|
||||||
|
YubiKey, and `scdaemon` is running (which can hold exclusive access to a
|
||||||
|
YubiKey indefinitely), `age-plugin-yubikey` now attempts to stop `scdaemon` by
|
||||||
|
interrupting it (or killing it on Windows), and then tries again to open the
|
||||||
|
connection.
|
||||||
|
- Several error messages were enhanced with guidance on how to resolve their
|
||||||
|
respective issue.
|
||||||
|
|
||||||
|
## [0.3.0] - 2022-05-02
|
||||||
|
First non-beta release!
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- MSRV is now 1.56.0.
|
||||||
|
- During decryption, when asked to insert a YubiKey, you can now choose to skip
|
||||||
|
it, allowing the client to move on to the next identity instead of returning
|
||||||
|
an error.
|
||||||
|
- Certain kinds of PIN invalidity will now cause the plugin to re-request the
|
||||||
|
PIN instead of aborting: if the PIN is too short or too long, or if the user
|
||||||
|
touched the YubiKey early and "typed" an OTP.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The "default" identity (provided by clients that invoke `age-plugin-yubikey`
|
||||||
|
using `-j yubikey`) previously caused a panic. It is now correctly treated as
|
||||||
|
an invalid identity (because this plugin does not support default identities).
|
||||||
|
|
||||||
|
## [0.2.0] - 2021-11-22
|
||||||
|
### Fixed
|
||||||
|
- Attempts-before-blocked counter is now returned as part of the invalid PIN
|
||||||
|
error string.
|
||||||
|
- PIN is no longer requested when fetching the recipient for a slot, or when
|
||||||
|
decrypting with a slot that has a PIN policy of Never.
|
||||||
|
- Migrated to `yubikey 0.5` to fix `cargo install age-plugin-yubikey` error
|
||||||
|
(caused by the `yubikey-piv` crate being yanked after it was renamed).
|
||||||
|
|
||||||
|
## [0.1.0] - 2021-05-02
|
||||||
|
|
||||||
|
Initial beta release.
|
||||||
Generated
+2093
-491
File diff suppressed because it is too large
Load Diff
+29
-18
@@ -1,19 +1,19 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "age-plugin-yubikey"
|
name = "age-plugin-yubikey"
|
||||||
description = "[BETA] YubiKey plugin for age clients"
|
description = "YubiKey plugin for age clients"
|
||||||
version = "0.1.0"
|
version = "0.4.1"
|
||||||
authors = ["Jack Grigg <thestr4d@gmail.com>"]
|
authors = ["Jack Grigg <thestr4d@gmail.com>"]
|
||||||
repository = "https://github.com/str4d/age-plugin-yubikey"
|
repository = "https://github.com/str4d/age-plugin-yubikey"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
keywords = ["age", "cli", "encryption", "yubikey"]
|
keywords = ["age", "cli", "encryption", "yubikey"]
|
||||||
categories = ["command-line-utilities", "cryptography"]
|
categories = ["command-line-utilities", "cryptography"]
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2021"
|
||||||
|
rust-version = "1.65" # MSRV
|
||||||
|
|
||||||
[package.metadata.deb]
|
[package.metadata.deb]
|
||||||
extended-description = """\
|
extended-description = """\
|
||||||
An age plugin adding support for YubiKeys and other PIV hardware tokens. \
|
An age plugin adding support for YubiKeys and other PIV hardware tokens."""
|
||||||
Currently in BETA; we strongly recommend using this with a new YubiKey."""
|
|
||||||
section = "utils"
|
section = "utils"
|
||||||
assets = [
|
assets = [
|
||||||
["target/release/age-plugin-yubikey", "usr/bin/", "755"],
|
["target/release/age-plugin-yubikey", "usr/bin/", "755"],
|
||||||
@@ -22,26 +22,37 @@ assets = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
age-core = "0.6"
|
age-core = "0.9"
|
||||||
age-plugin = "0.1"
|
age-plugin = "0.4"
|
||||||
base64 = "0.13"
|
base64 = "0.21"
|
||||||
bech32 = "0.8"
|
bech32 = "0.9"
|
||||||
console = "0.14"
|
console = { version = "0.15", default-features = false }
|
||||||
dialoguer = "0.8"
|
dialoguer = { version = "0.10", default-features = false, features = ["password"] }
|
||||||
env_logger = "0.8"
|
env_logger = "0.10"
|
||||||
gumdrop = "0.8"
|
gumdrop = "0.8"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
p256 = { version = "0.7", features = ["ecdh"] }
|
p256 = { version = "0.13", features = ["ecdh"] }
|
||||||
pcsc = "2.4"
|
pcsc = "2.4"
|
||||||
rand = "0.7"
|
rand = "0.8"
|
||||||
secrecy = "0.7"
|
sha2 = "0.10"
|
||||||
sha2 = "0.9"
|
|
||||||
which = "4.1"
|
which = "4.1"
|
||||||
x509 = "0.2"
|
x509 = "0.2"
|
||||||
x509-parser = "0.9"
|
x509-parser = "0.14"
|
||||||
yubikey-piv = { version = "0.3", features = ["untested"] }
|
yubikey = { version = "=0.8.0-pre.0", features = ["untested"] }
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
i18n-embed = { version = "0.13", features = ["desktop-requester", "fluent-system"] }
|
||||||
|
i18n-embed-fl = "0.6"
|
||||||
|
lazy_static = "1"
|
||||||
|
rust-embed = "6"
|
||||||
|
|
||||||
|
# GnuPG coexistence
|
||||||
|
sysinfo = "0.28"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
flate2 = "1"
|
flate2 = "1"
|
||||||
man = "0.3"
|
man = "0.3"
|
||||||
|
tempfile = "3"
|
||||||
|
test-with = "0.9"
|
||||||
|
which = "4"
|
||||||
|
|||||||
@@ -4,23 +4,37 @@
|
|||||||
like [`age`](https://age-encryption.org) and [`rage`](https://str4d.xyz/rage),
|
like [`age`](https://age-encryption.org) and [`rage`](https://str4d.xyz/rage),
|
||||||
which enables files to be encrypted to age identities stored on YubiKeys.
|
which enables files to be encrypted to age identities stored on YubiKeys.
|
||||||
|
|
||||||
This plugin is in **BETA**; we strongly recommend using this with a new YubiKey,
|
|
||||||
or one that you do not care about.
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
| Environment | CLI command |
|
||||||
|
|-------------|-------------|
|
||||||
|
| Cargo (Rust 1.65+) | `cargo install age-plugin-yubikey` |
|
||||||
|
| Homebrew (macOS or Linux) | `brew install age-plugin-yubikey` |
|
||||||
|
|
||||||
On Windows, Linux, and macOS, you can use the
|
On Windows, Linux, and macOS, you can use the
|
||||||
[pre-built binaries](https://github.com/str4d/age-plugin-yubikey/releases).
|
[pre-built binaries](https://github.com/str4d/age-plugin-yubikey/releases).
|
||||||
|
|
||||||
If your system has Rust 1.51+ installed (either via `rustup` or a system
|
|
||||||
package), you can build directly from source:
|
|
||||||
|
|
||||||
```
|
|
||||||
cargo install age-plugin-yubikey
|
|
||||||
```
|
|
||||||
|
|
||||||
Help from new packagers is very welcome.
|
Help from new packagers is very welcome.
|
||||||
|
|
||||||
|
### Linux, BSD, etc.
|
||||||
|
|
||||||
|
On non-Windows, non-macOS systems, you need to ensure that the `pcscd` service
|
||||||
|
is installed and running.
|
||||||
|
|
||||||
|
| Environment | CLI command |
|
||||||
|
|-------------|-------------|
|
||||||
|
| Debian or Ubuntu | `sudo apt-get install pcscd` |
|
||||||
|
| OpenBSD | As ```root``` do:<br>`pkg_add pcsc-lite ccid`<br>`rcctl enable pcscd`<br>`rcctl start pcscd` |
|
||||||
|
| FreeBSD | As ```root``` do:<br>`pkg install pcsc-lite libccid`<br>`service pcscd enable`<br>`service pcscd start` |
|
||||||
|
|
||||||
|
When installing via Cargo, you also need to ensure that the development headers
|
||||||
|
for the `pcsc-lite` library are available, so that the `pcsc-sys` crate can be
|
||||||
|
compiled.
|
||||||
|
|
||||||
|
| Environment | CLI command |
|
||||||
|
|-------------|-------------|
|
||||||
|
| Debian or Ubuntu | `sudo apt-get install libpcsclite-dev` |
|
||||||
|
|
||||||
### Windows Subsystem for Linux (WSL)
|
### Windows Subsystem for Linux (WSL)
|
||||||
|
|
||||||
WSL does not currently provide native support for USB devices. However, Windows
|
WSL does not currently provide native support for USB devices. However, Windows
|
||||||
@@ -38,7 +52,12 @@ YubiKey:
|
|||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
There are two ways to configure a YubiKey as an `age` identity. You can run the
|
`age-plugin-yubikey` identities have two parts:
|
||||||
|
- The secret key material, which is stored inside a YubiKey.
|
||||||
|
- An age identity file, which contains information that an age client can use to
|
||||||
|
figure out which YubiKey secret key should be used.
|
||||||
|
|
||||||
|
There are two ways to configure a YubiKey as an age identity. You can run the
|
||||||
plugin binary directly to use a simple text interface, which will create an age
|
plugin binary directly to use a simple text interface, which will create an age
|
||||||
identity file:
|
identity file:
|
||||||
|
|
||||||
@@ -64,6 +83,14 @@ Once an identity has been created, you can regenerate it later:
|
|||||||
$ age-plugin-yubikey --identity [--serial SERIAL] --slot SLOT
|
$ age-plugin-yubikey --identity [--serial SERIAL] --slot SLOT
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To use the identity with an age client, it needs to be stored in a file. When
|
||||||
|
using the above programmatic flags, you can do this by redirecting standard
|
||||||
|
output to a file. On a Unix system like macOS or Ubuntu:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ age-plugin-yubikey --identity --slot SLOT > yubikey-identity.txt
|
||||||
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
The age recipients contained in all connected YubiKeys can be printed on
|
The age recipients contained in all connected YubiKeys can be printed on
|
||||||
@@ -88,18 +115,39 @@ age client as normal (e.g. `rage -d -i yubikey-identity.txt`).
|
|||||||
### Agent support
|
### Agent support
|
||||||
|
|
||||||
`age-plugin-yubikey` does not provide or interact with an agent for decryption.
|
`age-plugin-yubikey` does not provide or interact with an agent for decryption.
|
||||||
As age plugin binaries have short lifetimes (they only run while the age client
|
It does however attempt to preserve the PIN cache by not soft-resetting the
|
||||||
is running), this means that YubiKey identities configured with a PIN policy of
|
YubiKey after a decryption or read-only operation, which enables YubiKey
|
||||||
`once` will actually prompt for the PIN on every decryption.
|
identities configured with a PIN policy of `once` to not prompt for the PIN on
|
||||||
|
every decryption. **This does not work for YubiKey 4 series.**
|
||||||
|
|
||||||
A decryption agent will most likely be implemented as a separate age plugin that
|
The session that corresponds to the `once` policy can be ended in several ways,
|
||||||
interacts with [`yubikey-agent`](https://github.com/FiloSottile/yubikey-agent),
|
not all of which are necessarily intuitive:
|
||||||
enabling YubiKeys to be used simultaneously with age and SSH.
|
|
||||||
|
- Unplugging the YubiKey (the obvious way).
|
||||||
|
- Using a different applet (e.g. FIDO2). This causes the PIV applet to be closed
|
||||||
|
which clears its state.
|
||||||
|
- This is why the YubiKey 4 series does not support PIN cache preservation:
|
||||||
|
their serial can only be obtained by switching to the OTP applet.
|
||||||
|
- Generating a new age identity via `age-plugin-yubikey --generate` or the CLI
|
||||||
|
interface. This is to avoid leaving the YubiKey authenticated with the
|
||||||
|
management key.
|
||||||
|
|
||||||
|
If the current PIN UX proves to be insufficient, a decryption agent will most
|
||||||
|
likely be implemented as a separate age plugin that interacts with
|
||||||
|
[`yubikey-agent`](https://github.com/FiloSottile/yubikey-agent), enabling
|
||||||
|
YubiKeys to be used simultaneously with age and SSH.
|
||||||
|
|
||||||
### Manual setup and technical details
|
### Manual setup and technical details
|
||||||
|
|
||||||
`age-plugin-yubikey` only officially supports YubiKeys set up either via the
|
`age-plugin-yubikey` only officially supports the following YubiKey variants,
|
||||||
text interface or the `--generate` flag.
|
set up either via the text interface or the `--generate` flag:
|
||||||
|
|
||||||
|
- YubiKey 4 series
|
||||||
|
- YubiKey 5 series
|
||||||
|
|
||||||
|
NOTE: Nano and USB-C variants of the above are also supported. The pre-YK4
|
||||||
|
YubiKey NEO series is **NOT** supported. The blue "Security Key by Yubico" will
|
||||||
|
also not work (as it doesn't support PIV).
|
||||||
|
|
||||||
In practice, any PIV token with an ECDSA P-256 key and certificate in one of the
|
In practice, any PIV token with an ECDSA P-256 key and certificate in one of the
|
||||||
20 "retired" slots should work. You can list all age-compatible keys with:
|
20 "retired" slots should work. You can list all age-compatible keys with:
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
# Copyright 2022 Jack Grigg
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||||
|
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||||
|
# option. This file may not be copied, modified, or distributed
|
||||||
|
# except according to those terms.
|
||||||
|
|
||||||
|
### Localization for strings in age-plugin-yubikey
|
||||||
|
|
||||||
|
-age = age
|
||||||
|
-yubikey = YubiKey
|
||||||
|
-yubikeys = YubiKeys
|
||||||
|
-age-plugin-yubikey = age-plugin-yubikey
|
||||||
|
-pcscd = pcscd
|
||||||
|
|
||||||
|
## CLI commands and flags
|
||||||
|
|
||||||
|
-cmd-generate = --generate
|
||||||
|
-cmd-identity = --identity
|
||||||
|
-cmd-list = --list
|
||||||
|
-cmd-list-all = --list-all
|
||||||
|
|
||||||
|
-flag-force = --force
|
||||||
|
-flag-serial = --serial
|
||||||
|
-flag-slot = --slot
|
||||||
|
|
||||||
|
## YubiKey metadata
|
||||||
|
|
||||||
|
pin-policy-always = Always (A PIN is required for every decryption, if set)
|
||||||
|
pin-policy-once = Once (A PIN is required once per session, if set)
|
||||||
|
pin-policy-never = Never (A PIN is NOT required to decrypt)
|
||||||
|
|
||||||
|
touch-policy-always = Always (A physical touch is required for every decryption)
|
||||||
|
touch-policy-cached = Cached (A physical touch is required for decryption, and is cached for 15 seconds)
|
||||||
|
touch-policy-never = Never (A physical touch is NOT required to decrypt)
|
||||||
|
|
||||||
|
unknown-policy = Unknown
|
||||||
|
|
||||||
|
yubikey-metadata =
|
||||||
|
# Serial: {$serial}, Slot: {$slot}
|
||||||
|
# Name: {$name}
|
||||||
|
# Created: {$created}
|
||||||
|
# PIN policy: {$pin_policy}
|
||||||
|
# Touch policy: {$touch_policy}
|
||||||
|
yubikey-identity =
|
||||||
|
{$yubikey_metadata}
|
||||||
|
# Recipient: {$recipient}
|
||||||
|
{$identity}
|
||||||
|
|
||||||
|
## CLI setup via text interface
|
||||||
|
|
||||||
|
cli-setup-intro =
|
||||||
|
✨ Let's get your {-yubikey} set up for {-age}! ✨
|
||||||
|
|
||||||
|
This tool can create a new {-age} identity in a free slot of your {-yubikey}.
|
||||||
|
It will generate an identity file that you can use with an {-age} client,
|
||||||
|
along with the corresponding recipient. You can also do this directly
|
||||||
|
with:
|
||||||
|
{" "}{$generate_usage}
|
||||||
|
|
||||||
|
If you are already using a {-yubikey} with {-age}, you can select an existing
|
||||||
|
slot to recreate its corresponding identity file and recipient.
|
||||||
|
|
||||||
|
When asked below to select an option, use the up/down arrow keys to
|
||||||
|
make your choice, or press [Esc] or [q] to quit.
|
||||||
|
|
||||||
|
cli-setup-insert-yk = ⏳ Please insert the {-yubikey} you want to set up.
|
||||||
|
cli-setup-yk-name = {$yubikey_name} (Serial: {$yubikey_serial})
|
||||||
|
cli-setup-select-yk = 🔑 Select a {-yubikey}
|
||||||
|
cli-setup-slot-usable = Slot {$slot_index} ({$slot_name})
|
||||||
|
cli-setup-slot-unusable = Slot {$slot_index} (Unusable)
|
||||||
|
cli-setup-slot-empty = Slot {$slot_index} (Empty)
|
||||||
|
cli-setup-select-slot = 🕳️ Select a slot for your {-age} identity
|
||||||
|
cli-setup-name-identity = 📛 Name this identity
|
||||||
|
cli-setup-select-pin-policy = 🔤 Select a PIN policy
|
||||||
|
cli-setup-select-touch-policy = 👆 Select a touch policy
|
||||||
|
|
||||||
|
cli-setup-yk4-pin-policy =
|
||||||
|
⚠️ Your {-yubikey} is a {-yubikey} 4 series. With ephemeral applications like
|
||||||
|
{-age-plugin-yubikey}, a PIN policy of "Once" behaves like a PIN policy of
|
||||||
|
"Always", and your PIN will be requested for every decryption. However, you
|
||||||
|
might still benefit from a PIN policy of "Once" in long-running applications
|
||||||
|
like agents.
|
||||||
|
cli-setup-yk4-pin-policy-confirm = Use PIN policy of "Once" with {-yubikey} 4?
|
||||||
|
|
||||||
|
cli-setup-generate-new = Generate new identity in slot {$slot_index}?
|
||||||
|
cli-setup-use-existing = Use existing identity in slot {$slot_index}?
|
||||||
|
|
||||||
|
cli-setup-identity-file-name = 📝 File name to write this identity to
|
||||||
|
cli-setup-identity-file-exists = File exists. Overwrite it?
|
||||||
|
|
||||||
|
cli-setup-finished =
|
||||||
|
✅ Done! This {-yubikey} identity is ready to go.
|
||||||
|
|
||||||
|
🔑 { $is_new ->
|
||||||
|
[true] Here's your shiny new {-yubikey} recipient:
|
||||||
|
*[false] Here's the corresponding {-yubikey} recipient:
|
||||||
|
}
|
||||||
|
{" "}{$recipient}
|
||||||
|
|
||||||
|
Here are some example things you can do with it:
|
||||||
|
|
||||||
|
- Encrypt a file to this identity:
|
||||||
|
{" "}{$encrypt_usage}
|
||||||
|
|
||||||
|
- Decrypt a file with this identity:
|
||||||
|
{" "}{$decrypt_usage}
|
||||||
|
|
||||||
|
- Recreate the identity file:
|
||||||
|
{" "}{$identity_usage}
|
||||||
|
|
||||||
|
- Recreate the recipient:
|
||||||
|
{" "}{$recipient_usage}
|
||||||
|
|
||||||
|
💭 Remember: everything breaks, have a backup plan for when this {-yubikey} does.
|
||||||
|
|
||||||
|
## Programmatic usage
|
||||||
|
|
||||||
|
open-yk-with-serial = ⏳ Please insert the {-yubikey} with serial {$yubikey_serial}.
|
||||||
|
open-yk-without-serial = ⏳ Please insert the {-yubikey}.
|
||||||
|
warn-yk-not-connected = Ignoring {$yubikey_name}: not connected
|
||||||
|
warn-yk-missing-applet = Ignoring {$yubikey_name}: Missing {$applet_name} applet
|
||||||
|
|
||||||
|
print-recipient = Recipient: {$recipient}
|
||||||
|
|
||||||
|
printed-kind-identities = identities
|
||||||
|
printed-kind-recipients = recipients
|
||||||
|
printed-multiple = Generated {$kind} for {$count} slots. If you intended to select a slot, use {-flag-slot}.
|
||||||
|
|
||||||
|
## YubiKey management
|
||||||
|
|
||||||
|
mgr-enter-pin = Enter PIN for {-yubikey} with serial {$yubikey_serial} (default is {$default_pin})
|
||||||
|
|
||||||
|
mgr-change-default-pin =
|
||||||
|
✨ Your {-yubikey} is using the default PIN. Let's change it!
|
||||||
|
✨ We'll also set the PUK equal to the PIN.
|
||||||
|
|
||||||
|
🔐 The PIN can be numbers, letters, or symbols. Not just numbers!
|
||||||
|
📏 The PIN must be at least 6 and at most 8 characters in length.
|
||||||
|
❌ Your keys will be lost if the PIN and PUK are locked after 3 incorrect tries.
|
||||||
|
|
||||||
|
mgr-enter-current-puk = Enter current PUK (default is {$default_puk})
|
||||||
|
mgr-choose-new-pin = Choose a new PIN/PUK
|
||||||
|
mgr-repeat-new-pin = Repeat the PIN/PUK
|
||||||
|
mgr-pin-mismatch = PINs don't match
|
||||||
|
mgr-nope-default-pin = You entered the default PIN again. You need to change it.
|
||||||
|
|
||||||
|
mgr-changing-mgmt-key =
|
||||||
|
✨ Your {-yubikey} is using the default management key.
|
||||||
|
✨ We'll migrate it to a PIN-protected management key.
|
||||||
|
mgr-changing-mgmt-key-error =
|
||||||
|
An error occurred while setting the new management key.
|
||||||
|
⚠️ SAVE THIS MANAGEMENT KEY - YOU MAY NEED IT TO MANAGE YOUR {-yubikey}! ⚠️
|
||||||
|
{" "}{$management_key}
|
||||||
|
mgr-changing-mgmt-key-success = Success!
|
||||||
|
|
||||||
|
## YubiKey keygen
|
||||||
|
|
||||||
|
builder-gen-key = 🎲 Generating key...
|
||||||
|
builder-gen-cert = 🔏 Generating certificate...
|
||||||
|
builder-touch-yk = 👆 Please touch the {-yubikey}
|
||||||
|
|
||||||
|
## Plugin usage
|
||||||
|
|
||||||
|
plugin-err-invalid-recipient = Invalid recipient
|
||||||
|
plugin-err-invalid-identity = Invalid {-yubikey} stub
|
||||||
|
plugin-err-invalid-stanza = Invalid {-yubikey} stanza
|
||||||
|
plugin-err-decryption-failed = Failed to decrypt {-yubikey} stanza
|
||||||
|
|
||||||
|
plugin-insert-yk = Please insert {-yubikey} with serial {$yubikey_serial}
|
||||||
|
plugin-yk-is-plugged-in = {-yubikey} is plugged in
|
||||||
|
plugin-skip-this-yk = Skip this {-yubikey}
|
||||||
|
plugin-insert-yk-retry = Could not open {-yubikey}. Please insert {-yubikey} with serial {$yubikey_serial}
|
||||||
|
plugin-err-yk-not-found = Could not find {-yubikey} with serial {$yubikey_serial}
|
||||||
|
plugin-err-yk-opening = Could not open {-yubikey} with serial {$yubikey_serial}
|
||||||
|
plugin-err-yk-timed-out = Timed out while waiting for {-yubikey} with serial {$yubikey_serial} to be inserted
|
||||||
|
plugin-err-yk-stub-mismatch = A {-yubikey} stub did not match the {-yubikey}
|
||||||
|
|
||||||
|
plugin-err-yk-invalid-pin-policy = Certificate for {-yubikey} identity contains an invalid PIN policy
|
||||||
|
|
||||||
|
plugin-enter-pin = Enter PIN for {-yubikey} with serial {$yubikey_serial}
|
||||||
|
plugin-err-accidental-touch = Did you touch the {-yubikey} by accident?
|
||||||
|
plugin-err-pin-too-short = PIN was too short.
|
||||||
|
plugin-err-pin-too-long = PIN was too long.
|
||||||
|
plugin-err-pin-required = A PIN is required for {-yubikey} with serial {$yubikey_serial}
|
||||||
|
|
||||||
|
## Errors
|
||||||
|
|
||||||
|
err-mgmt-key-auth = Failed to authenticate with the PIN-protected management key.
|
||||||
|
rec-mgmt-key-auth =
|
||||||
|
Check whether your management key is using the TDES algorithm.
|
||||||
|
AES is not supported yet: {$aes_url}
|
||||||
|
err-custom-mgmt-key = Custom unprotected non-TDES management keys are not supported.
|
||||||
|
rec-change-mgmt-key =
|
||||||
|
You can use the {-yubikey} Manager CLI to change to a protected management key:
|
||||||
|
{" "}{$cmd}
|
||||||
|
|
||||||
|
See here for more information about {-yubikey} Manager:
|
||||||
|
{" "}{$url}
|
||||||
|
|
||||||
|
err-invalid-flag-command = Flag '{$flag}' cannot be used with '{$command}'.
|
||||||
|
err-invalid-flag-tui = Flag '{$flag}' cannot be used with the interactive interface.
|
||||||
|
err-invalid-pin-policy = Invalid PIN policy '{$policy}' (expected [{$expected}]).
|
||||||
|
err-invalid-slot = Invalid slot '{$slot}' (expected number between 1 and 20).
|
||||||
|
err-invalid-touch-policy = Invalid touch policy '{$policy}' (expected [{$expected}]).
|
||||||
|
err-io = Failed to set up {-yubikey}: {$err}
|
||||||
|
err-multiple-commands = Only one of {-cmd-generate}, {-cmd-identity}, {-cmd-list}, {-cmd-list-all} can be specified.
|
||||||
|
err-multiple-yubikeys = Multiple {-yubikeys} are plugged in. Use {-flag-serial} to select a single {-yubikey}.
|
||||||
|
err-no-empty-slots = {-yubikey} with serial {$serial} has no empty slots.
|
||||||
|
err-no-matching-serial = Could not find {-yubikey} with serial {$serial}.
|
||||||
|
err-slot-has-no-identity = Slot {$slot} does not contain an {-age} identity or compatible key.
|
||||||
|
err-slot-is-not-empty = Slot {$slot} is not empty. Use {-flag-force} to overwrite the slot.
|
||||||
|
err-timed-out = Timed out while waiting for a {-yubikey} to be inserted.
|
||||||
|
err-use-list-for-single = Use {-cmd-list} to print the recipient for a single slot.
|
||||||
|
|
||||||
|
err-yk-no-service-macos = The Crypto Token Kit service is not running.
|
||||||
|
rec-yk-no-service-macos =
|
||||||
|
You may need to restart it. See this Stack Exchange answer for more help:
|
||||||
|
{" "}{$url}
|
||||||
|
|
||||||
|
err-yk-no-service-pcscd = {-pcscd} is not running.
|
||||||
|
rec-yk-no-service-pcscd =
|
||||||
|
If you are on Debian or Ubuntu, you can install it with:
|
||||||
|
{" "}{$apt}
|
||||||
|
|
||||||
|
rec-yk-no-service-pcscd-bsd =
|
||||||
|
You can install and run it as root with:
|
||||||
|
{" "}{$pkg}
|
||||||
|
{" "}{$service_enable}
|
||||||
|
{" "}{$service_start}
|
||||||
|
|
||||||
|
err-yk-no-service-win = The Smart Cards for Windows service is not running.
|
||||||
|
rec-yk-no-service-win =
|
||||||
|
See this troubleshooting guide for more help:
|
||||||
|
{" "}{$url}
|
||||||
|
|
||||||
|
err-yk-not-found = Please insert the {-yubikey} you want to set up
|
||||||
|
err-yk-general = Error while communicating with {-yubikey}: {$err}
|
||||||
|
err-yk-general-cause = Cause: {$inner_err}
|
||||||
|
|
||||||
|
err-yk-wrong-pin = Invalid {$pin_kind} ({$tries ->
|
||||||
|
[one] {$tries} try remaining
|
||||||
|
*[other] {$tries} tries remaining
|
||||||
|
} before it is blocked)
|
||||||
|
err-yk-pin-locked = {$pin_kind} locked
|
||||||
|
|
||||||
|
err-ux-A = Did this not do what you expected? Could an error be more useful?
|
||||||
|
err-ux-B = Tell us
|
||||||
|
# Put (len(A) - len(B) - 46) spaces here.
|
||||||
|
err-ux-C = {" "}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[toolchain]
|
||||||
|
channel = "1.65.0"
|
||||||
|
components = ["clippy", "rustfmt"]
|
||||||
+31
-20
@@ -1,17 +1,18 @@
|
|||||||
|
use dialoguer::Password;
|
||||||
use rand::{rngs::OsRng, RngCore};
|
use rand::{rngs::OsRng, RngCore};
|
||||||
use x509::RelativeDistinguishedName;
|
use x509::RelativeDistinguishedName;
|
||||||
use yubikey_piv::{
|
use yubikey::{
|
||||||
certificate::{Certificate, PublicKeyInfo},
|
certificate::Certificate,
|
||||||
key::{generate as yubikey_generate, AlgorithmId, RetiredSlotId, SlotId},
|
piv::{generate as yubikey_generate, AlgorithmId, RetiredSlotId, SlotId},
|
||||||
policy::{PinPolicy, TouchPolicy},
|
Key, PinPolicy, TouchPolicy, YubiKey,
|
||||||
Key, YubiKey,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
error::Error,
|
error::Error,
|
||||||
|
fl,
|
||||||
|
key::{self, Stub},
|
||||||
p256::Recipient,
|
p256::Recipient,
|
||||||
util::{Metadata, POLICY_EXTENSION_OID},
|
util::{Metadata, POLICY_EXTENSION_OID},
|
||||||
yubikey::{self, Stub},
|
|
||||||
BINARY_NAME, USABLE_SLOTS,
|
BINARY_NAME, USABLE_SLOTS,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -87,16 +88,12 @@ impl IdentityBuilder {
|
|||||||
let pin_policy = self.pin_policy.unwrap_or(DEFAULT_PIN_POLICY);
|
let pin_policy = self.pin_policy.unwrap_or(DEFAULT_PIN_POLICY);
|
||||||
let touch_policy = self.touch_policy.unwrap_or(DEFAULT_TOUCH_POLICY);
|
let touch_policy = self.touch_policy.unwrap_or(DEFAULT_TOUCH_POLICY);
|
||||||
|
|
||||||
|
eprintln!("{}", fl!("builder-gen-key"));
|
||||||
|
|
||||||
// No need to ask for users to enter their PIN if the PIN policy requires it,
|
// No need to ask for users to enter their PIN if the PIN policy requires it,
|
||||||
// because here we _always_ require them to enter their PIN in order to access the
|
// because here we _always_ require them to enter their PIN in order to access the
|
||||||
// protected management key (which is necessary in order to generate identities).
|
// protected management key (which is necessary in order to generate identities).
|
||||||
yubikey::manage(yubikey)?;
|
key::manage(yubikey)?;
|
||||||
|
|
||||||
if let TouchPolicy::Never = touch_policy {
|
|
||||||
// No need to touch YubiKey
|
|
||||||
} else {
|
|
||||||
eprintln!("👆 Please touch the YubiKey");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate a new key in the selected slot.
|
// Generate a new key in the selected slot.
|
||||||
let generated = yubikey_generate(
|
let generated = yubikey_generate(
|
||||||
@@ -107,14 +104,12 @@ impl IdentityBuilder {
|
|||||||
touch_policy,
|
touch_policy,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let recipient = match &generated {
|
let recipient = Recipient::from_spki(&generated).expect("YubiKey generates a valid pubkey");
|
||||||
PublicKeyInfo::EcP256(pubkey) => {
|
|
||||||
Recipient::from_encoded(pubkey).expect("YubiKey generates a valid pubkey")
|
|
||||||
}
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
let stub = Stub::new(yubikey.serial(), slot, &recipient);
|
let stub = Stub::new(yubikey.serial(), slot, &recipient);
|
||||||
|
|
||||||
|
eprintln!();
|
||||||
|
eprintln!("{}", fl!("builder-gen-cert"));
|
||||||
|
|
||||||
// Pick a random serial for the new self-signed certificate.
|
// Pick a random serial for the new self-signed certificate.
|
||||||
let mut serial = [0; 20];
|
let mut serial = [0; 20];
|
||||||
OsRng.fill_bytes(&mut serial);
|
OsRng.fill_bytes(&mut serial);
|
||||||
@@ -123,6 +118,23 @@ impl IdentityBuilder {
|
|||||||
.name
|
.name
|
||||||
.unwrap_or(format!("age identity {}", hex::encode(stub.tag)));
|
.unwrap_or(format!("age identity {}", hex::encode(stub.tag)));
|
||||||
|
|
||||||
|
if let PinPolicy::Always = pin_policy {
|
||||||
|
// We need to enter the PIN again.
|
||||||
|
let pin = Password::new()
|
||||||
|
.with_prompt(fl!(
|
||||||
|
"plugin-enter-pin",
|
||||||
|
yubikey_serial = yubikey.serial().to_string(),
|
||||||
|
))
|
||||||
|
.report(true)
|
||||||
|
.interact()?;
|
||||||
|
yubikey.verify_pin(pin.as_bytes())?;
|
||||||
|
}
|
||||||
|
if let TouchPolicy::Never = touch_policy {
|
||||||
|
// No need to touch YubiKey
|
||||||
|
} else {
|
||||||
|
eprintln!("{}", fl!("builder-touch-yk"));
|
||||||
|
}
|
||||||
|
|
||||||
let cert = Certificate::generate_self_signed(
|
let cert = Certificate::generate_self_signed(
|
||||||
yubikey,
|
yubikey,
|
||||||
SlotId::Retired(slot),
|
SlotId::Retired(slot),
|
||||||
@@ -140,7 +152,6 @@ impl IdentityBuilder {
|
|||||||
)],
|
)],
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let (_, cert) = x509_parser::parse_x509_certificate(cert.as_ref()).unwrap();
|
|
||||||
let metadata = Metadata::extract(yubikey, slot, &cert, false).unwrap();
|
let metadata = Metadata::extract(yubikey, slot, &cert, false).unwrap();
|
||||||
|
|
||||||
Ok((
|
Ok((
|
||||||
|
|||||||
+123
-68
@@ -1,27 +1,38 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::io;
|
use std::io;
|
||||||
use yubikey_piv::{key::RetiredSlotId, Serial};
|
use yubikey::{piv::RetiredSlotId, Serial};
|
||||||
|
|
||||||
use crate::util::slot_to_ui;
|
use crate::util::slot_to_ui;
|
||||||
|
|
||||||
|
macro_rules! wlnfl {
|
||||||
|
($f:ident, $message_id:literal) => {
|
||||||
|
writeln!($f, "{}", $crate::fl!($message_id))
|
||||||
|
};
|
||||||
|
($f:ident, $message_id:literal, $($kwarg:expr),* $(,)*) => {{
|
||||||
|
writeln!($f, "{}", $crate::fl!($message_id, $($kwarg,)*))
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
CustomManagementKey,
|
CustomManagementKey,
|
||||||
InvalidFlagCommand(String, String),
|
InvalidFlagCommand(String, String),
|
||||||
InvalidFlagTui(String),
|
InvalidFlagTui(String),
|
||||||
InvalidPinLength,
|
|
||||||
InvalidPinPolicy(String),
|
InvalidPinPolicy(String),
|
||||||
InvalidSlot(u8),
|
InvalidSlot(u8),
|
||||||
InvalidTouchPolicy(String),
|
InvalidTouchPolicy(String),
|
||||||
Io(io::Error),
|
Io(io::Error),
|
||||||
|
ManagementKeyAuth,
|
||||||
MultipleCommands,
|
MultipleCommands,
|
||||||
MultipleYubiKeys,
|
MultipleYubiKeys,
|
||||||
NoEmptySlots(Serial),
|
NoEmptySlots(Serial),
|
||||||
NoMatchingSerial(Serial),
|
NoMatchingSerial(Serial),
|
||||||
|
PukLocked,
|
||||||
SlotHasNoIdentity(RetiredSlotId),
|
SlotHasNoIdentity(RetiredSlotId),
|
||||||
SlotIsNotEmpty(RetiredSlotId),
|
SlotIsNotEmpty(RetiredSlotId),
|
||||||
TimedOut,
|
TimedOut,
|
||||||
UseListForSingleSlot,
|
UseListForSingleSlot,
|
||||||
YubiKey(yubikey_piv::Error),
|
WrongPuk(u8),
|
||||||
|
YubiKey(yubikey::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<io::Error> for Error {
|
impl From<io::Error> for Error {
|
||||||
@@ -30,8 +41,8 @@ impl From<io::Error> for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<yubikey_piv::error::Error> for Error {
|
impl From<yubikey::Error> for Error {
|
||||||
fn from(e: yubikey_piv::error::Error) -> Self {
|
fn from(e: yubikey::Error) -> Self {
|
||||||
Error::YubiKey(e)
|
Error::YubiKey(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,91 +51,135 @@ impl From<yubikey_piv::error::Error> for Error {
|
|||||||
// manually to provide the error output we want.
|
// manually to provide the error output we want.
|
||||||
impl fmt::Debug for Error {
|
impl fmt::Debug for Error {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
const CHANGE_MGMT_KEY_CMD: &str =
|
||||||
|
"ykman piv access change-management-key -a TDES --protect";
|
||||||
|
const CHANGE_MGMT_KEY_URL: &str = "https://developers.yubico.com/yubikey-manager/";
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
Error::CustomManagementKey => {
|
Error::CustomManagementKey => {
|
||||||
writeln!(f, "Custom unprotected management keys are not supported.")?
|
wlnfl!(f, "err-custom-mgmt-key")?;
|
||||||
|
wlnfl!(
|
||||||
|
f,
|
||||||
|
"rec-change-mgmt-key",
|
||||||
|
cmd = CHANGE_MGMT_KEY_CMD,
|
||||||
|
url = CHANGE_MGMT_KEY_URL
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
Error::InvalidFlagCommand(flag, command) => {
|
Error::InvalidFlagCommand(flag, command) => wlnfl!(
|
||||||
writeln!(f, "Flag '{}' cannot be used with '{}'.", flag, command)?
|
f,
|
||||||
|
"err-invalid-flag-command",
|
||||||
|
flag = flag.as_str(),
|
||||||
|
command = command.as_str(),
|
||||||
|
)?,
|
||||||
|
Error::InvalidFlagTui(flag) => wlnfl!(f, "err-invalid-flag-tui", flag = flag.as_str())?,
|
||||||
|
Error::InvalidPinPolicy(s) => wlnfl!(
|
||||||
|
f,
|
||||||
|
"err-invalid-pin-policy",
|
||||||
|
policy = s.as_str(),
|
||||||
|
expected = "always, once, never",
|
||||||
|
)?,
|
||||||
|
Error::InvalidSlot(slot) => wlnfl!(f, "err-invalid-slot", slot = slot)?,
|
||||||
|
Error::InvalidTouchPolicy(s) => wlnfl!(
|
||||||
|
f,
|
||||||
|
"err-invalid-touch-policy",
|
||||||
|
policy = s.as_str(),
|
||||||
|
expected = "always, cached, never",
|
||||||
|
)?,
|
||||||
|
Error::Io(e) => wlnfl!(f, "err-io", err = e.to_string())?,
|
||||||
|
Error::ManagementKeyAuth => {
|
||||||
|
let aes_url = "https://github.com/str4d/age-plugin-yubikey/issues/92";
|
||||||
|
wlnfl!(f, "err-mgmt-key-auth")?;
|
||||||
|
wlnfl!(f, "rec-mgmt-key-auth", aes_url = aes_url)?;
|
||||||
|
wlnfl!(
|
||||||
|
f,
|
||||||
|
"rec-change-mgmt-key",
|
||||||
|
cmd = CHANGE_MGMT_KEY_CMD,
|
||||||
|
url = CHANGE_MGMT_KEY_URL
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
Error::InvalidFlagTui(flag) => writeln!(
|
Error::MultipleCommands => wlnfl!(f, "err-multiple-commands")?,
|
||||||
f,
|
Error::MultipleYubiKeys => wlnfl!(f, "err-multiple-yubikeys")?,
|
||||||
"Flag '{}' cannot be used with the interactive interface.",
|
|
||||||
flag
|
|
||||||
)?,
|
|
||||||
Error::InvalidPinLength => writeln!(f, "The PIN needs to be 1-8 characters.")?,
|
|
||||||
Error::InvalidPinPolicy(s) => writeln!(
|
|
||||||
f,
|
|
||||||
"Invalid PIN policy '{}' (expected [always, once, never]).",
|
|
||||||
s
|
|
||||||
)?,
|
|
||||||
Error::InvalidSlot(slot) => writeln!(
|
|
||||||
f,
|
|
||||||
"Invalid slot '{}' (expected number between 1 and 20).",
|
|
||||||
slot
|
|
||||||
)?,
|
|
||||||
Error::InvalidTouchPolicy(s) => writeln!(
|
|
||||||
f,
|
|
||||||
"Invalid touch policy '{}' (expected [always, cached, never]).",
|
|
||||||
s
|
|
||||||
)?,
|
|
||||||
Error::Io(e) => writeln!(f, "Failed to set up YubiKey: {}", e)?,
|
|
||||||
Error::MultipleCommands => writeln!(
|
|
||||||
f,
|
|
||||||
"Only one of --generate, --identity, --list, --list-all can be specified."
|
|
||||||
)?,
|
|
||||||
Error::MultipleYubiKeys => writeln!(
|
|
||||||
f,
|
|
||||||
"Multiple YubiKeys are plugged in. Use --serial to select a single YubiKey."
|
|
||||||
)?,
|
|
||||||
Error::NoEmptySlots(serial) => {
|
Error::NoEmptySlots(serial) => {
|
||||||
writeln!(f, "YubiKey with serial {} has no empty slots.", serial)?
|
wlnfl!(f, "err-no-empty-slots", serial = serial.to_string())?
|
||||||
}
|
}
|
||||||
Error::NoMatchingSerial(serial) => {
|
Error::NoMatchingSerial(serial) => {
|
||||||
writeln!(f, "Could not find YubiKey with serial {}.", serial)?
|
wlnfl!(f, "err-no-matching-serial", serial = serial.to_string())?
|
||||||
}
|
}
|
||||||
Error::SlotHasNoIdentity(slot) => writeln!(
|
Error::PukLocked => wlnfl!(f, "err-yk-pin-locked", pin_kind = "PUK")?,
|
||||||
f,
|
Error::SlotHasNoIdentity(slot) => {
|
||||||
"Slot {} does not contain an age identity or compatible key.",
|
wlnfl!(f, "err-slot-has-no-identity", slot = slot_to_ui(slot))?
|
||||||
slot_to_ui(slot)
|
|
||||||
)?,
|
|
||||||
Error::SlotIsNotEmpty(slot) => writeln!(
|
|
||||||
f,
|
|
||||||
"Slot {} is not empty. Use --force to overwrite the slot.",
|
|
||||||
slot_to_ui(slot)
|
|
||||||
)?,
|
|
||||||
Error::TimedOut => {
|
|
||||||
writeln!(f, "Timed out while waiting for a YubiKey to be inserted.")?
|
|
||||||
}
|
}
|
||||||
Error::UseListForSingleSlot => {
|
Error::SlotIsNotEmpty(slot) => {
|
||||||
writeln!(f, "Use --list to print the recipient for a single slot.")?
|
wlnfl!(f, "err-slot-is-not-empty", slot = slot_to_ui(slot))?
|
||||||
|
}
|
||||||
|
Error::TimedOut => wlnfl!(f, "err-timed-out")?,
|
||||||
|
Error::UseListForSingleSlot => wlnfl!(f, "err-use-list-for-single")?,
|
||||||
|
Error::WrongPuk(tries) => {
|
||||||
|
wlnfl!(f, "err-yk-wrong-pin", pin_kind = "PUK", tries = tries)?
|
||||||
}
|
}
|
||||||
Error::YubiKey(e) => match e {
|
Error::YubiKey(e) => match e {
|
||||||
yubikey_piv::error::Error::NotFound => {
|
yubikey::Error::NotFound => wlnfl!(f, "err-yk-not-found")?,
|
||||||
writeln!(f, "Please insert the YubiKey you want to set up")?
|
yubikey::Error::PcscError {
|
||||||
}
|
inner: Some(pcsc::Error::NoService),
|
||||||
yubikey_piv::error::Error::WrongPin { tries } => writeln!(
|
} => {
|
||||||
|
if cfg!(windows) {
|
||||||
|
wlnfl!(f, "err-yk-no-service-win")?;
|
||||||
|
let url = "https://learn.microsoft.com/en-us/windows/security/identity-protection/smart-cards/smart-card-debugging-information#smart-card-service";
|
||||||
|
wlnfl!(f, "rec-yk-no-service-win", url = url)?;
|
||||||
|
} else if cfg!(target_os = "macos") {
|
||||||
|
wlnfl!(f, "err-yk-no-service-macos")?;
|
||||||
|
let url = "https://apple.stackexchange.com/a/438198";
|
||||||
|
wlnfl!(f, "rec-yk-no-service-macos", url = url)?;
|
||||||
|
} else if cfg!(target_os = "openbsd") {
|
||||||
|
wlnfl!(f, "err-yk-no-service-pcscd")?;
|
||||||
|
let pkg = "pkg_add pcsc-lite ccid";
|
||||||
|
let service_enable = "rcctl enable pcscd";
|
||||||
|
let service_start = "rcctl start pcscd";
|
||||||
|
wlnfl!(
|
||||||
f,
|
f,
|
||||||
"Invalid PIN ({} tries remaining before it is blocked)",
|
"rec-yk-no-service-pcscd-bsd",
|
||||||
tries
|
pkg = pkg,
|
||||||
)?,
|
service_enable = service_enable,
|
||||||
|
service_start = service_start
|
||||||
|
)?;
|
||||||
|
} else if cfg!(target_os = "freebsd") {
|
||||||
|
wlnfl!(f, "err-yk-no-service-pcscd")?;
|
||||||
|
let pkg = "pkg install pcsc-lite libccid";
|
||||||
|
let service_enable = "service pcscd enable";
|
||||||
|
let service_start = "service pcscd start";
|
||||||
|
wlnfl!(
|
||||||
|
f,
|
||||||
|
"rec-yk-no-service-pcscd-bsd",
|
||||||
|
pkg = pkg,
|
||||||
|
service_enable = service_enable,
|
||||||
|
service_start = service_start
|
||||||
|
)?;
|
||||||
|
} else {
|
||||||
|
wlnfl!(f, "err-yk-no-service-pcscd")?;
|
||||||
|
let apt = "sudo apt-get install pcscd";
|
||||||
|
wlnfl!(f, "rec-yk-no-service-pcscd", apt = apt)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yubikey::Error::PinLocked => wlnfl!(f, "err-yk-pin-locked", pin_kind = "PIN")?,
|
||||||
|
yubikey::Error::WrongPin { tries } => {
|
||||||
|
wlnfl!(f, "err-yk-wrong-pin", pin_kind = "PIN", tries = tries)?
|
||||||
|
}
|
||||||
e => {
|
e => {
|
||||||
writeln!(f, "Error while communicating with YubiKey: {}", e)?;
|
wlnfl!(f, "err-yk-general", err = e.to_string())?;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
if let Some(inner) = e.source() {
|
if let Some(inner) = e.source() {
|
||||||
writeln!(f, "Cause: {}", inner)?;
|
wlnfl!(f, "err-yk-general-cause", inner_err = inner.to_string())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
writeln!(f)?;
|
writeln!(f)?;
|
||||||
writeln!(
|
writeln!(f, "[ {} ]", crate::fl!("err-ux-A"))?;
|
||||||
f,
|
|
||||||
"[ Did this not do what you expected? Could an error be more useful? ]"
|
|
||||||
)?;
|
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
"[ Tell us: https://str4d.xyz/age-plugin-yubikey/report ]"
|
"[ {}: https://str4d.xyz/age-plugin-yubikey/report {} ]",
|
||||||
|
crate::fl!("err-ux-B"),
|
||||||
|
crate::fl!("err-ux-C")
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+32
-16
@@ -1,11 +1,15 @@
|
|||||||
use age_core::{
|
use age_core::{
|
||||||
format::{FileKey, Stanza},
|
format::{FileKey, Stanza},
|
||||||
primitives::{aead_encrypt, hkdf},
|
primitives::aead_encrypt,
|
||||||
|
secrecy::ExposeSecret,
|
||||||
|
};
|
||||||
|
use base64::{prelude::BASE64_STANDARD_NO_PAD, Engine};
|
||||||
|
use p256::{
|
||||||
|
ecdh::EphemeralSecret,
|
||||||
|
elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint},
|
||||||
};
|
};
|
||||||
use p256::{ecdh::EphemeralSecret, elliptic_curve::sec1::ToEncodedPoint};
|
|
||||||
use rand::rngs::OsRng;
|
use rand::rngs::OsRng;
|
||||||
use secrecy::ExposeSecret;
|
use sha2::Sha256;
|
||||||
use std::convert::TryInto;
|
|
||||||
|
|
||||||
use crate::{p256::Recipient, STANZA_TAG};
|
use crate::{p256::Recipient, STANZA_TAG};
|
||||||
|
|
||||||
@@ -23,8 +27,12 @@ pub(crate) struct EphemeralKeyBytes(p256::EncodedPoint);
|
|||||||
|
|
||||||
impl EphemeralKeyBytes {
|
impl EphemeralKeyBytes {
|
||||||
fn from_bytes(bytes: [u8; EPK_BYTES]) -> Option<Self> {
|
fn from_bytes(bytes: [u8; EPK_BYTES]) -> Option<Self> {
|
||||||
let encoded = p256::EncodedPoint::from_bytes(&bytes).ok()?;
|
let encoded = p256::EncodedPoint::from_bytes(bytes).ok()?;
|
||||||
if encoded.is_compressed() && encoded.decompress().is_some() {
|
if encoded.is_compressed()
|
||||||
|
&& p256::PublicKey::from_encoded_point(&encoded)
|
||||||
|
.is_some()
|
||||||
|
.into()
|
||||||
|
{
|
||||||
Some(EphemeralKeyBytes(encoded))
|
Some(EphemeralKeyBytes(encoded))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -40,9 +48,9 @@ impl EphemeralKeyBytes {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn decompress(&self) -> p256::EncodedPoint {
|
pub(crate) fn decompress(&self) -> p256::EncodedPoint {
|
||||||
self.0
|
// EphemeralKeyBytes is a valid compressed encoding by construction.
|
||||||
.decompress()
|
let p = p256::PublicKey::from_encoded_point(&self.0).unwrap();
|
||||||
.expect("EphemeralKeyBytes is a valid compressed encoding by construction")
|
p.to_encoded_point(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,8 +66,8 @@ impl From<RecipientLine> for Stanza {
|
|||||||
Stanza {
|
Stanza {
|
||||||
tag: STANZA_TAG.to_owned(),
|
tag: STANZA_TAG.to_owned(),
|
||||||
args: vec![
|
args: vec![
|
||||||
base64::encode_config(&r.tag, base64::STANDARD_NO_PAD),
|
BASE64_STANDARD_NO_PAD.encode(r.tag),
|
||||||
base64::encode_config(r.epk_bytes.as_bytes(), base64::STANDARD_NO_PAD),
|
BASE64_STANDARD_NO_PAD.encode(r.epk_bytes.as_bytes()),
|
||||||
],
|
],
|
||||||
body: r.encrypted_file_key.to_vec(),
|
body: r.encrypted_file_key.to_vec(),
|
||||||
}
|
}
|
||||||
@@ -77,9 +85,10 @@ impl RecipientLine {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
base64::decode_config_slice(arg, base64::STANDARD_NO_PAD, buf.as_mut())
|
BASE64_STANDARD_NO_PAD
|
||||||
|
.decode_slice_unchecked(arg, buf.as_mut())
|
||||||
.ok()
|
.ok()
|
||||||
.map(|_| buf)
|
.and_then(|len| (len == buf.as_mut().len()).then_some(buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
let (tag, epk_bytes) = match &s.args[..] {
|
let (tag, epk_bytes) = match &s.args[..] {
|
||||||
@@ -102,17 +111,24 @@ impl RecipientLine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn wrap_file_key(file_key: &FileKey, pk: &Recipient) -> Self {
|
pub(crate) fn wrap_file_key(file_key: &FileKey, pk: &Recipient) -> Self {
|
||||||
let esk = EphemeralSecret::random(OsRng);
|
let esk = EphemeralSecret::random(&mut OsRng);
|
||||||
let epk = esk.public_key();
|
let epk = esk.public_key();
|
||||||
let epk_bytes = EphemeralKeyBytes::from_public_key(&epk);
|
let epk_bytes = EphemeralKeyBytes::from_public_key(&epk);
|
||||||
|
|
||||||
let shared_secret = esk.diffie_hellman(&pk.public_key());
|
let shared_secret = esk.diffie_hellman(pk.public_key());
|
||||||
|
|
||||||
let mut salt = vec![];
|
let mut salt = vec![];
|
||||||
salt.extend_from_slice(epk_bytes.as_bytes());
|
salt.extend_from_slice(epk_bytes.as_bytes());
|
||||||
salt.extend_from_slice(pk.to_encoded().as_bytes());
|
salt.extend_from_slice(pk.to_encoded().as_bytes());
|
||||||
|
|
||||||
let enc_key = hkdf(&salt, STANZA_KEY_LABEL, shared_secret.as_bytes());
|
let enc_key = {
|
||||||
|
let mut okm = [0; 32];
|
||||||
|
shared_secret
|
||||||
|
.extract::<Sha256>(Some(&salt))
|
||||||
|
.expand(STANZA_KEY_LABEL, &mut okm)
|
||||||
|
.expect("okm is the correct length");
|
||||||
|
okm
|
||||||
|
};
|
||||||
|
|
||||||
let encrypted_file_key = {
|
let encrypted_file_key = {
|
||||||
let mut key = [0; ENCRYPTED_FILE_KEY_BYTES];
|
let mut key = [0; ENCRYPTED_FILE_KEY_BYTES];
|
||||||
|
|||||||
+813
@@ -0,0 +1,813 @@
|
|||||||
|
//! Structs for handling YubiKeys.
|
||||||
|
|
||||||
|
use age_core::{
|
||||||
|
format::{FileKey, FILE_KEY_BYTES},
|
||||||
|
primitives::{aead_decrypt, hkdf},
|
||||||
|
secrecy::{ExposeSecret, SecretString},
|
||||||
|
};
|
||||||
|
use age_plugin::{identity, Callbacks};
|
||||||
|
use bech32::{ToBase32, Variant};
|
||||||
|
use dialoguer::Password;
|
||||||
|
use log::{debug, error, warn};
|
||||||
|
use std::convert::Infallible;
|
||||||
|
use std::fmt;
|
||||||
|
use std::io;
|
||||||
|
use std::iter;
|
||||||
|
use std::thread::sleep;
|
||||||
|
use std::time::{Duration, Instant, SystemTime};
|
||||||
|
use x509_parser::der_parser::oid::Oid;
|
||||||
|
use yubikey::{
|
||||||
|
certificate::Certificate,
|
||||||
|
piv::{decrypt_data, AlgorithmId, RetiredSlotId, SlotId},
|
||||||
|
reader::{Context, Reader},
|
||||||
|
Key, MgmKey, PinPolicy, Serial, TouchPolicy, YubiKey,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
error::Error,
|
||||||
|
fl,
|
||||||
|
format::{RecipientLine, STANZA_KEY_LABEL},
|
||||||
|
p256::{Recipient, TAG_BYTES},
|
||||||
|
util::{otp_serial_prefix, Metadata, POLICY_EXTENSION_OID},
|
||||||
|
IDENTITY_PREFIX,
|
||||||
|
};
|
||||||
|
|
||||||
|
const ONE_SECOND: Duration = Duration::from_secs(1);
|
||||||
|
const FIFTEEN_SECONDS: Duration = Duration::from_secs(15);
|
||||||
|
|
||||||
|
/// The set of OIDs that we understand and use when parsing YubiKey slot certificates.
|
||||||
|
const KNOWN_OIDS: &[&[u64]] = &[POLICY_EXTENSION_OID];
|
||||||
|
|
||||||
|
pub(crate) fn is_connected(reader: Reader) -> bool {
|
||||||
|
filter_connected(&reader)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn filter_connected(reader: &Reader) -> bool {
|
||||||
|
match reader.open() {
|
||||||
|
Err(yubikey::Error::PcscError {
|
||||||
|
inner: Some(pcsc::Error::NoSmartcard | pcsc::Error::RemovedCard),
|
||||||
|
}) => {
|
||||||
|
warn!(
|
||||||
|
"{}",
|
||||||
|
fl!("warn-yk-not-connected", yubikey_name = reader.name())
|
||||||
|
);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Err(yubikey::Error::AppletNotFound { applet_name }) => {
|
||||||
|
warn!(
|
||||||
|
"{}",
|
||||||
|
fl!(
|
||||||
|
"warn-yk-missing-applet",
|
||||||
|
yubikey_name = reader.name(),
|
||||||
|
applet_name = applet_name,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Err(_) => true,
|
||||||
|
Ok(yubikey) => {
|
||||||
|
// We only connected as a side-effect of confirming that we can connect, so
|
||||||
|
// avoid resetting the YubiKey.
|
||||||
|
disconnect_without_reset(yubikey);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn wait_for_readers() -> Result<Context, Error> {
|
||||||
|
// Start a 15-second timer waiting for a YubiKey to be inserted (if necessary).
|
||||||
|
let start = SystemTime::now();
|
||||||
|
loop {
|
||||||
|
let mut readers = Context::open()?;
|
||||||
|
if readers.iter()?.any(is_connected) {
|
||||||
|
break Ok(readers);
|
||||||
|
}
|
||||||
|
|
||||||
|
match SystemTime::now().duration_since(start) {
|
||||||
|
Ok(end) if end >= FIFTEEN_SECONDS => return Err(Error::TimedOut),
|
||||||
|
_ => sleep(ONE_SECOND),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks for agent processes that might be holding exclusive access to a YubiKey, and
|
||||||
|
/// asks them as nicely as possible to release it.
|
||||||
|
///
|
||||||
|
/// Returns `true` if any known agent was running and was successfully interrupted (or
|
||||||
|
/// killed if the platform doesn't support interrupts).
|
||||||
|
fn hunt_agents() -> bool {
|
||||||
|
debug!("Sharing violation encountered, looking for agent processes");
|
||||||
|
|
||||||
|
use sysinfo::{ProcessExt, ProcessRefreshKind, RefreshKind, Signal, System, SystemExt};
|
||||||
|
|
||||||
|
let mut interrupted = false;
|
||||||
|
|
||||||
|
let sys =
|
||||||
|
System::new_with_specifics(RefreshKind::new().with_processes(ProcessRefreshKind::new()));
|
||||||
|
|
||||||
|
for process in sys.processes().values() {
|
||||||
|
match process.name() {
|
||||||
|
"scdaemon" | "scdaemon.exe" => {
|
||||||
|
// gpg-agent runs scdaemon to interact with smart cards. The canonical way
|
||||||
|
// to reload it is `gpgconf --reload scdaemon`, which kills and restarts
|
||||||
|
// the process. We emulate that here with SIGINT (which it listens to).
|
||||||
|
if process
|
||||||
|
.kill_with(Signal::Interrupt)
|
||||||
|
.unwrap_or_else(|| process.kill())
|
||||||
|
{
|
||||||
|
debug!("Stopped scdaemon (PID {})", process.pid());
|
||||||
|
interrupted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"yubikey-agent" | "yubikey-agent.exe" => {
|
||||||
|
// yubikey-agent releases all YubiKey locks when it receives a SIGHUP.
|
||||||
|
match process.kill_with(Signal::Hangup) {
|
||||||
|
Some(true) => {
|
||||||
|
debug!("Sent SIGHUP to yubikey-agent (PID {})", process.pid());
|
||||||
|
interrupted = true;
|
||||||
|
}
|
||||||
|
Some(false) => (),
|
||||||
|
None => debug!(
|
||||||
|
"Found yubikey-agent (PID {}) but platform doesn't support SIGHUP",
|
||||||
|
process.pid(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we did interrupt an agent, pause briefly to allow it to finish up.
|
||||||
|
if interrupted {
|
||||||
|
sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
|
||||||
|
interrupted
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_sesame(
|
||||||
|
op: impl Fn() -> Result<YubiKey, yubikey::Error>,
|
||||||
|
) -> Result<YubiKey, yubikey::Error> {
|
||||||
|
op().or_else(|e| match e {
|
||||||
|
yubikey::Error::PcscError {
|
||||||
|
inner: Some(pcsc::Error::SharingViolation),
|
||||||
|
} if hunt_agents() => op(),
|
||||||
|
_ => Err(e),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens a connection to this reader, returning a `YubiKey` if successful.
|
||||||
|
///
|
||||||
|
/// This is equivalent to [`Reader::open`], but additionally handles the presence of
|
||||||
|
/// agents (which can indefinitely hold exclusive access to a YubiKey).
|
||||||
|
pub(crate) fn open_connection(reader: &Reader) -> Result<YubiKey, yubikey::Error> {
|
||||||
|
open_sesame(|| reader.open())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens a YubiKey with a specific serial number.
|
||||||
|
///
|
||||||
|
/// This is equivalent to [`YubiKey::open_by_serial`], but additionally handles the
|
||||||
|
/// presence of agents (which can indefinitely hold exclusive access to a YubiKey).
|
||||||
|
fn open_by_serial(serial: Serial) -> Result<YubiKey, yubikey::Error> {
|
||||||
|
// `YubiKey::open_by_serial` has a bug where it ignores all opening errors, even if
|
||||||
|
// it potentially could have found a matching YubiKey if not for an error, and thus
|
||||||
|
// returns `Error::NotFound` if another agent is holding exclusive access to the
|
||||||
|
// required YubiKey. This gives misleading UX behaviour where age-plugin-yubikey asks
|
||||||
|
// the user to insert a YubiKey they have already inserted.
|
||||||
|
//
|
||||||
|
// For now, we instead implement the correct behaviour manually. Once MSRV has been
|
||||||
|
// raised to 1.60, we can upstream this into the `yubikey` crate.
|
||||||
|
open_sesame(|| {
|
||||||
|
let mut readers = Context::open()?;
|
||||||
|
|
||||||
|
let mut open_error = None;
|
||||||
|
|
||||||
|
for reader in readers.iter()? {
|
||||||
|
let yubikey = match reader.open() {
|
||||||
|
Ok(yk) => yk,
|
||||||
|
Err(e) => {
|
||||||
|
// Save the first error we see that indicates we might have been able
|
||||||
|
// to find a matching YubiKey.
|
||||||
|
if open_error.is_none() {
|
||||||
|
if let yubikey::Error::PcscError {
|
||||||
|
inner: Some(pcsc::Error::SharingViolation),
|
||||||
|
} = e
|
||||||
|
{
|
||||||
|
open_error = Some(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if serial == yubikey.serial() {
|
||||||
|
return Ok(yubikey);
|
||||||
|
} else {
|
||||||
|
// We didn't want this YubiKey; don't reset it.
|
||||||
|
disconnect_without_reset(yubikey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(if let Some(e) = open_error {
|
||||||
|
e
|
||||||
|
} else {
|
||||||
|
error!("no YubiKey detected with serial: {}", serial);
|
||||||
|
yubikey::Error::NotFound
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn open(serial: Option<Serial>) -> Result<YubiKey, Error> {
|
||||||
|
if !Context::open()?.iter()?.any(is_connected) {
|
||||||
|
if let Some(serial) = serial {
|
||||||
|
eprintln!(
|
||||||
|
"{}",
|
||||||
|
fl!("open-yk-with-serial", yubikey_serial = serial.to_string())
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
eprintln!("{}", fl!("open-yk-without-serial"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut readers = wait_for_readers()?;
|
||||||
|
let mut readers_iter = readers.iter()?.filter(filter_connected);
|
||||||
|
|
||||||
|
// --serial selects the YubiKey to use. If not provided, and more than one YubiKey is
|
||||||
|
// connected, an error is returned.
|
||||||
|
let yubikey = match (readers_iter.next(), readers_iter.next(), serial) {
|
||||||
|
(None, _, _) => unreachable!(),
|
||||||
|
(Some(reader), None, None) => open_connection(&reader)?,
|
||||||
|
(Some(reader), None, Some(serial)) => {
|
||||||
|
let yubikey = open_connection(&reader)?;
|
||||||
|
if yubikey.serial() != serial {
|
||||||
|
return Err(Error::NoMatchingSerial(serial));
|
||||||
|
}
|
||||||
|
yubikey
|
||||||
|
}
|
||||||
|
(Some(a), Some(b), Some(serial)) => {
|
||||||
|
let reader = iter::empty()
|
||||||
|
.chain(Some(a))
|
||||||
|
.chain(Some(b))
|
||||||
|
.chain(readers_iter)
|
||||||
|
.find(|reader| match open_connection(reader) {
|
||||||
|
Ok(yk) => yk.serial() == serial,
|
||||||
|
_ => false,
|
||||||
|
})
|
||||||
|
.ok_or(Error::NoMatchingSerial(serial))?;
|
||||||
|
open_connection(&reader)?
|
||||||
|
}
|
||||||
|
(Some(_), Some(_), None) => return Err(Error::MultipleYubiKeys),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(yubikey)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disconnect from the YubiKey without resetting it.
|
||||||
|
///
|
||||||
|
/// This can be used to preserve the YubiKey's PIN and touch caches. There are two cases
|
||||||
|
/// where we want to do this:
|
||||||
|
///
|
||||||
|
/// - We connected to this YubiKey in a read-only context, so we have not made any changes
|
||||||
|
/// to the YubiKey's state. However, we might have asked an agent to release the YubiKey
|
||||||
|
/// in `key::open_connection`, and we want to allow any state it may have left behind
|
||||||
|
/// (such as cached PINs or touches) to persist beyond our execution, for usability.
|
||||||
|
/// - We opened this connection in a decryption context, so the only changes to the
|
||||||
|
/// YubiKey's state were to potentially cache the PIN and/or touch (depending on the
|
||||||
|
/// policies of the slot). We want to allow these to persist beyond our execution, for
|
||||||
|
/// usability.
|
||||||
|
pub(crate) fn disconnect_without_reset(yubikey: YubiKey) {
|
||||||
|
let _ = yubikey.disconnect(pcsc::Disposition::LeaveCard);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_pin<E>(
|
||||||
|
mut prompt: impl FnMut(Option<String>) -> io::Result<Result<SecretString, E>>,
|
||||||
|
serial: Serial,
|
||||||
|
) -> io::Result<Result<SecretString, E>> {
|
||||||
|
let mut prev_error = None;
|
||||||
|
loop {
|
||||||
|
prev_error = Some(match prompt(prev_error)? {
|
||||||
|
Ok(pin) => match pin.expose_secret().len() {
|
||||||
|
// A PIN must be between 6 and 8 characters.
|
||||||
|
6..=8 => break Ok(Ok(pin)),
|
||||||
|
// If the string is 44 bytes and starts with the YubiKey's serial
|
||||||
|
// encoded as 12-byte modhex, the user probably touched the YubiKey
|
||||||
|
// early and "typed" an OTP.
|
||||||
|
44 if pin.expose_secret().starts_with(&otp_serial_prefix(serial)) => {
|
||||||
|
fl!("plugin-err-accidental-touch")
|
||||||
|
}
|
||||||
|
// Otherwise, the PIN is either too short or too long.
|
||||||
|
0..=5 => fl!("plugin-err-pin-too-short"),
|
||||||
|
_ => fl!("plugin-err-pin-too-long"),
|
||||||
|
},
|
||||||
|
Err(e) => break Ok(Err(e)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn manage(yubikey: &mut YubiKey) -> Result<(), Error> {
|
||||||
|
const DEFAULT_PIN: &str = "123456";
|
||||||
|
const DEFAULT_PUK: &str = "12345678";
|
||||||
|
|
||||||
|
eprintln!();
|
||||||
|
let pin = Password::new()
|
||||||
|
.with_prompt(fl!(
|
||||||
|
"mgr-enter-pin",
|
||||||
|
yubikey_serial = yubikey.serial().to_string(),
|
||||||
|
default_pin = DEFAULT_PIN,
|
||||||
|
))
|
||||||
|
.report(true)
|
||||||
|
.interact()?;
|
||||||
|
yubikey.verify_pin(pin.as_bytes())?;
|
||||||
|
|
||||||
|
// If the user is using the default PIN, help them to change it.
|
||||||
|
if pin == DEFAULT_PIN {
|
||||||
|
eprintln!();
|
||||||
|
eprintln!("{}", fl!("mgr-change-default-pin"));
|
||||||
|
eprintln!();
|
||||||
|
let current_puk = Password::new()
|
||||||
|
.with_prompt(fl!("mgr-enter-current-puk", default_puk = DEFAULT_PUK))
|
||||||
|
.interact()?;
|
||||||
|
let new_pin = loop {
|
||||||
|
let pin = request_pin(
|
||||||
|
|prev_error| {
|
||||||
|
if let Some(err) = prev_error {
|
||||||
|
eprintln!("{}", err);
|
||||||
|
}
|
||||||
|
Password::new()
|
||||||
|
.with_prompt(fl!("mgr-choose-new-pin"))
|
||||||
|
.with_confirmation(fl!("mgr-repeat-new-pin"), fl!("mgr-pin-mismatch"))
|
||||||
|
.interact()
|
||||||
|
.map(|pin| Result::<_, Infallible>::Ok(SecretString::new(pin)))
|
||||||
|
},
|
||||||
|
yubikey.serial(),
|
||||||
|
)?
|
||||||
|
.unwrap();
|
||||||
|
if pin.expose_secret() == DEFAULT_PIN {
|
||||||
|
eprintln!("{}", fl!("mgr-nope-default-pin"));
|
||||||
|
} else {
|
||||||
|
break pin;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let new_pin = new_pin.expose_secret();
|
||||||
|
yubikey
|
||||||
|
.change_puk(current_puk.as_bytes(), new_pin.as_bytes())
|
||||||
|
.map_err(|e| match e {
|
||||||
|
yubikey::Error::PinLocked => Error::PukLocked,
|
||||||
|
yubikey::Error::WrongPin { tries } => Error::WrongPuk(tries),
|
||||||
|
_ => Error::YubiKey(e),
|
||||||
|
})?;
|
||||||
|
yubikey.change_pin(pin.as_bytes(), new_pin.as_bytes())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
match MgmKey::get_protected(yubikey) {
|
||||||
|
Ok(mgm_key) => yubikey.authenticate(mgm_key).map_err(|e| match e {
|
||||||
|
yubikey::Error::AuthenticationError => Error::ManagementKeyAuth,
|
||||||
|
_ => e.into(),
|
||||||
|
})?,
|
||||||
|
Err(yubikey::Error::AuthenticationError) => Err(Error::ManagementKeyAuth)?,
|
||||||
|
_ => {
|
||||||
|
// Try to authenticate with the default management key.
|
||||||
|
yubikey
|
||||||
|
.authenticate(MgmKey::default())
|
||||||
|
.map_err(|_| Error::CustomManagementKey)?;
|
||||||
|
|
||||||
|
// Migrate to a PIN-protected management key.
|
||||||
|
let mgm_key = MgmKey::generate();
|
||||||
|
eprintln!();
|
||||||
|
eprintln!("{}", fl!("mgr-changing-mgmt-key"));
|
||||||
|
eprint!("... ");
|
||||||
|
mgm_key.set_protected(yubikey).map_err(|e| {
|
||||||
|
eprintln!(
|
||||||
|
"{}",
|
||||||
|
fl!(
|
||||||
|
"mgr-changing-mgmt-key-error",
|
||||||
|
management_key = hex::encode(mgm_key.as_ref()),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
e
|
||||||
|
})?;
|
||||||
|
eprintln!("{}", fl!("mgr-changing-mgmt-key-success"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses the certificate to identify the preferred recipient type it corresponds to.
|
||||||
|
pub(crate) fn identify_recipient(cert: &Certificate) -> Option<Recipient> {
|
||||||
|
let known_oids = KNOWN_OIDS
|
||||||
|
.iter()
|
||||||
|
.map(|oid| Oid::from(oid).unwrap())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
// If the certificate contains any unrecognised critical extensions, reject it: we
|
||||||
|
// don't know how to correctly use the identity. In particular, some identities store
|
||||||
|
// parts of their private key material in certificate extensions to work around
|
||||||
|
// hardware limitations. Not understanding these extensions could lead to encrypting
|
||||||
|
// with the wrong protocol and violating security assumptions.
|
||||||
|
let (_, c) = x509_parser::parse_x509_certificate(cert.as_ref()).ok()?;
|
||||||
|
if c.tbs_certificate
|
||||||
|
.extensions()
|
||||||
|
.iter()
|
||||||
|
.any(|ext| ext.critical && !known_oids.contains(&ext.oid))
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Recipient::from_certificate(cert)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns an iterator of keys that are occupying plugin-compatible slots, along with the
|
||||||
|
/// corresponding recipient if the key is compatible with this plugin.
|
||||||
|
pub(crate) fn list_slots(
|
||||||
|
yubikey: &mut YubiKey,
|
||||||
|
) -> Result<impl Iterator<Item = (Key, RetiredSlotId, Option<Recipient>)>, Error> {
|
||||||
|
Ok(Key::list(yubikey)?.into_iter().filter_map(|key| {
|
||||||
|
// We only use the retired slots.
|
||||||
|
match key.slot() {
|
||||||
|
SlotId::Retired(slot) => {
|
||||||
|
let recipient = identify_recipient(key.certificate());
|
||||||
|
Some((key, slot, recipient))
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns an iterator of keys that are compatible with this plugin.
|
||||||
|
pub(crate) fn list_compatible(
|
||||||
|
yubikey: &mut YubiKey,
|
||||||
|
) -> Result<impl Iterator<Item = (Key, RetiredSlotId, Recipient)>, Error> {
|
||||||
|
list_slots(yubikey)
|
||||||
|
.map(|iter| iter.filter_map(|(key, slot, res)| res.map(|recipient| (key, slot, recipient))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reference to an age key stored in a YubiKey.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Stub {
|
||||||
|
pub(crate) serial: Serial,
|
||||||
|
pub(crate) slot: RetiredSlotId,
|
||||||
|
pub(crate) tag: [u8; TAG_BYTES],
|
||||||
|
pub(crate) identity_index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Stub {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(
|
||||||
|
bech32::encode(
|
||||||
|
IDENTITY_PREFIX,
|
||||||
|
self.to_bytes().to_base32(),
|
||||||
|
Variant::Bech32,
|
||||||
|
)
|
||||||
|
.expect("HRP is valid")
|
||||||
|
.to_uppercase()
|
||||||
|
.as_str(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Stub {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.to_bytes().eq(&other.to_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stub {
|
||||||
|
/// Returns a key stub and recipient for this `(Serial, SlotId, PublicKey)` tuple.
|
||||||
|
///
|
||||||
|
/// Does not check that the `PublicKey` matches the given `(Serial, SlotId)` tuple;
|
||||||
|
/// this is checked at decryption time.
|
||||||
|
pub(crate) fn new(serial: Serial, slot: RetiredSlotId, recipient: &Recipient) -> Self {
|
||||||
|
Stub {
|
||||||
|
serial,
|
||||||
|
slot,
|
||||||
|
tag: recipient.tag(),
|
||||||
|
identity_index: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn from_bytes(bytes: &[u8], identity_index: usize) -> Option<Self> {
|
||||||
|
if bytes.len() < 9 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let serial = Serial::from(u32::from_le_bytes(bytes[0..4].try_into().unwrap()));
|
||||||
|
let slot: RetiredSlotId = bytes[4].try_into().ok()?;
|
||||||
|
Some(Stub {
|
||||||
|
serial,
|
||||||
|
slot,
|
||||||
|
tag: bytes[5..9].try_into().unwrap(),
|
||||||
|
identity_index,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_bytes(&self) -> Vec<u8> {
|
||||||
|
let mut bytes = Vec::with_capacity(9);
|
||||||
|
bytes.extend_from_slice(&self.serial.0.to_le_bytes());
|
||||||
|
bytes.push(self.slot.into());
|
||||||
|
bytes.extend_from_slice(&self.tag);
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn matches(&self, line: &RecipientLine) -> bool {
|
||||||
|
self.tag == line.tag
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns:
|
||||||
|
/// - `Ok(Ok(Some(connection)))` if we successfully connected to this YubiKey.
|
||||||
|
/// - `Ok(Ok(None))` if the user told us to skip this YubiKey.
|
||||||
|
/// - `Ok(Err(_))` if we encountered an error while trying to connect to the YubiKey.
|
||||||
|
/// - `Err(_)` on communication errors with the age client.
|
||||||
|
pub(crate) fn connect<E>(
|
||||||
|
&self,
|
||||||
|
callbacks: &mut dyn Callbacks<E>,
|
||||||
|
) -> io::Result<Result<Option<Connection>, identity::Error>> {
|
||||||
|
let mut yubikey = match open_by_serial(self.serial) {
|
||||||
|
Ok(yk) => yk,
|
||||||
|
Err(yubikey::Error::NotFound) => {
|
||||||
|
let mut message = fl!("plugin-insert-yk", yubikey_serial = self.serial.to_string());
|
||||||
|
|
||||||
|
// If the `confirm` command is available, we loop until either the YubiKey
|
||||||
|
// we want is inserted, or the used explicitly skips.
|
||||||
|
let yubikey = loop {
|
||||||
|
match callbacks.confirm(
|
||||||
|
&message,
|
||||||
|
&fl!("plugin-yk-is-plugged-in"),
|
||||||
|
Some(&fl!("plugin-skip-this-yk")),
|
||||||
|
)? {
|
||||||
|
// `confirm` command is not available.
|
||||||
|
Err(age_core::plugin::Error::Unsupported) => break None,
|
||||||
|
// User told us to skip this key.
|
||||||
|
Ok(false) => return Ok(Ok(None)),
|
||||||
|
// User said they plugged it in; try it.
|
||||||
|
Ok(true) => match open_by_serial(self.serial) {
|
||||||
|
Ok(yubikey) => break Some(yubikey),
|
||||||
|
Err(yubikey::Error::NotFound) => (),
|
||||||
|
Err(_) => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-yk-opening",
|
||||||
|
yubikey_serial = self.serial.to_string(),
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// We can't communicate with the user.
|
||||||
|
Err(age_core::plugin::Error::Fail) => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-yk-opening",
|
||||||
|
yubikey_serial = self.serial.to_string(),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// We're going to loop around, meaning that the first attempt failed.
|
||||||
|
// Change the message to indicate this to the user.
|
||||||
|
message = fl!(
|
||||||
|
"plugin-insert-yk-retry",
|
||||||
|
yubikey_serial = self.serial.to_string(),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(yk) = yubikey {
|
||||||
|
yk
|
||||||
|
} else {
|
||||||
|
// `confirm` is not available; fall back to `message` with a timeout.
|
||||||
|
if callbacks.message(&message)?.is_err() {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-yk-not-found",
|
||||||
|
yubikey_serial = self.serial.to_string(),
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start a 15-second timer waiting for the YubiKey to be inserted
|
||||||
|
let start = SystemTime::now();
|
||||||
|
loop {
|
||||||
|
match open_by_serial(self.serial) {
|
||||||
|
Ok(yubikey) => break yubikey,
|
||||||
|
Err(yubikey::Error::NotFound) => (),
|
||||||
|
Err(_) => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-yk-opening",
|
||||||
|
yubikey_serial = self.serial.to_string(),
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match SystemTime::now().duration_since(start) {
|
||||||
|
Ok(end) if end >= FIFTEEN_SECONDS => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-yk-timed-out",
|
||||||
|
yubikey_serial = self.serial.to_string(),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
_ => sleep(ONE_SECOND),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-yk-opening",
|
||||||
|
yubikey_serial = self.serial.to_string(),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Read the pubkey from the YubiKey slot and check it still matches.
|
||||||
|
let (cert, pk) = match Certificate::read(&mut yubikey, SlotId::Retired(self.slot))
|
||||||
|
.ok()
|
||||||
|
.and_then(|cert| {
|
||||||
|
identify_recipient(&cert)
|
||||||
|
.filter(|recipient| recipient.tag() == self.tag)
|
||||||
|
.map(|r| (cert, r))
|
||||||
|
}) {
|
||||||
|
Some(pk) => pk,
|
||||||
|
None => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!("plugin-err-yk-stub-mismatch"),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Ok(Some(Connection {
|
||||||
|
yubikey,
|
||||||
|
cert,
|
||||||
|
pk,
|
||||||
|
slot: self.slot,
|
||||||
|
tag: self.tag,
|
||||||
|
identity_index: self.identity_index,
|
||||||
|
cached_metadata: None,
|
||||||
|
last_touch: None,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Connection {
|
||||||
|
yubikey: YubiKey,
|
||||||
|
cert: Certificate,
|
||||||
|
pk: Recipient,
|
||||||
|
slot: RetiredSlotId,
|
||||||
|
tag: [u8; 4],
|
||||||
|
identity_index: usize,
|
||||||
|
cached_metadata: Option<Metadata>,
|
||||||
|
last_touch: Option<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Connection {
|
||||||
|
pub(crate) fn recipient(&self) -> &Recipient {
|
||||||
|
&self.pk
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn request_pin_if_necessary<E>(
|
||||||
|
&mut self,
|
||||||
|
callbacks: &mut dyn Callbacks<E>,
|
||||||
|
) -> io::Result<Result<(), identity::Error>> {
|
||||||
|
// Check if we can skip requesting a PIN.
|
||||||
|
if self.cached_metadata.is_none() {
|
||||||
|
self.cached_metadata =
|
||||||
|
match Metadata::extract(&mut self.yubikey, self.slot, &self.cert, true) {
|
||||||
|
None => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!("plugin-err-yk-invalid-pin-policy"),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
metadata => metadata,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
match self.cached_metadata.as_ref().and_then(|m| m.pin_policy) {
|
||||||
|
Some(PinPolicy::Never) => return Ok(Ok(())),
|
||||||
|
Some(PinPolicy::Once) if self.yubikey.verify_pin(&[]).is_ok() => return Ok(Ok(())),
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
// The policy requires a PIN, so request it.
|
||||||
|
let pin = match request_pin(
|
||||||
|
|prev_error| {
|
||||||
|
callbacks.request_secret(&format!(
|
||||||
|
"{}{}{}",
|
||||||
|
prev_error.as_deref().unwrap_or(""),
|
||||||
|
prev_error.as_deref().map(|_| " ").unwrap_or(""),
|
||||||
|
fl!(
|
||||||
|
"plugin-enter-pin",
|
||||||
|
yubikey_serial = self.yubikey.serial().to_string(),
|
||||||
|
)
|
||||||
|
))
|
||||||
|
},
|
||||||
|
self.yubikey.serial(),
|
||||||
|
)? {
|
||||||
|
Ok(pin) => pin,
|
||||||
|
Err(_) => {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-pin-required",
|
||||||
|
yubikey_serial = self.yubikey.serial().to_string(),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err(e) = self.yubikey.verify_pin(pin.expose_secret().as_bytes()) {
|
||||||
|
return Ok(Err(identity::Error::Identity {
|
||||||
|
index: self.identity_index,
|
||||||
|
message: format!("{:?}", Error::YubiKey(e)),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
Ok(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn unwrap_file_key(&mut self, line: &RecipientLine) -> Result<FileKey, ()> {
|
||||||
|
assert_eq!(self.tag, line.tag);
|
||||||
|
|
||||||
|
// Check if the touch policy requires a touch.
|
||||||
|
let needs_touch = match (
|
||||||
|
self.cached_metadata.as_ref().and_then(|m| m.touch_policy),
|
||||||
|
self.last_touch,
|
||||||
|
) {
|
||||||
|
(Some(TouchPolicy::Always), _) | (Some(TouchPolicy::Cached), None) => true,
|
||||||
|
(Some(TouchPolicy::Cached), Some(last)) if last.elapsed() >= FIFTEEN_SECONDS => true,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// The YubiKey API for performing scalar multiplication takes the point in its
|
||||||
|
// uncompressed SEC-1 encoding.
|
||||||
|
let shared_secret = match decrypt_data(
|
||||||
|
&mut self.yubikey,
|
||||||
|
line.epk_bytes.decompress().as_bytes(),
|
||||||
|
AlgorithmId::EccP256,
|
||||||
|
SlotId::Retired(self.slot),
|
||||||
|
) {
|
||||||
|
Ok(res) => res,
|
||||||
|
Err(_) => return Err(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// If we requested a touch and reached here, the user touched the YubiKey.
|
||||||
|
if needs_touch {
|
||||||
|
if let Some(TouchPolicy::Cached) =
|
||||||
|
self.cached_metadata.as_ref().and_then(|m| m.touch_policy)
|
||||||
|
{
|
||||||
|
self.last_touch = Some(Instant::now());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut salt = vec![];
|
||||||
|
salt.extend_from_slice(line.epk_bytes.as_bytes());
|
||||||
|
salt.extend_from_slice(self.pk.to_encoded().as_bytes());
|
||||||
|
|
||||||
|
let enc_key = hkdf(&salt, STANZA_KEY_LABEL, shared_secret.as_ref());
|
||||||
|
|
||||||
|
// A failure to decrypt is fatal, because we assume that we won't
|
||||||
|
// encounter 32-bit collisions on the key tag embedded in the header.
|
||||||
|
match aead_decrypt(&enc_key, FILE_KEY_BYTES, &line.encrypted_file_key) {
|
||||||
|
Ok(pt) => Ok(TryInto::<[u8; FILE_KEY_BYTES]>::try_into(&pt[..])
|
||||||
|
.unwrap()
|
||||||
|
.into()),
|
||||||
|
Err(_) => Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close this connection without resetting the YubiKey.
|
||||||
|
///
|
||||||
|
/// This can be used to preserve the YubiKey's PIN and touch caches.
|
||||||
|
pub(crate) fn disconnect_without_reset(self) {
|
||||||
|
disconnect_without_reset(self.yubikey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use yubikey::{piv::RetiredSlotId, Serial};
|
||||||
|
|
||||||
|
use super::Stub;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stub_round_trip() {
|
||||||
|
let stub = Stub {
|
||||||
|
serial: Serial::from(42),
|
||||||
|
slot: RetiredSlotId::R1,
|
||||||
|
tag: [7; 4],
|
||||||
|
identity_index: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
let encoded = stub.to_bytes();
|
||||||
|
assert_eq!(Stub::from_bytes(&[], 0), None);
|
||||||
|
assert_eq!(Stub::from_bytes(&encoded, 0), Some(stub));
|
||||||
|
assert_eq!(Stub::from_bytes(&encoded[..encoded.len() - 1], 0), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
+199
-146
@@ -1,24 +1,26 @@
|
|||||||
use std::convert::{TryFrom, TryInto};
|
#![forbid(unsafe_code)]
|
||||||
|
|
||||||
use std::fs::{File, OpenOptions};
|
use std::fs::{File, OpenOptions};
|
||||||
use std::io::{self, Write};
|
use std::io::{self, Write};
|
||||||
|
|
||||||
use age_plugin::run_state_machine;
|
use age_plugin::run_state_machine;
|
||||||
use dialoguer::{Confirm, Input, Select};
|
use dialoguer::{Confirm, Input, Select};
|
||||||
use gumdrop::Options;
|
use gumdrop::Options;
|
||||||
use yubikey_piv::{
|
use i18n_embed::{
|
||||||
certificate::PublicKeyInfo,
|
fluent::{fluent_language_loader, FluentLanguageLoader},
|
||||||
key::{RetiredSlotId, SlotId},
|
DesktopLanguageRequester,
|
||||||
policy::{PinPolicy, TouchPolicy},
|
|
||||||
Key, Readers, Serial,
|
|
||||||
};
|
};
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use rust_embed::RustEmbed;
|
||||||
|
use yubikey::{piv::RetiredSlotId, reader::Context, PinPolicy, Serial, TouchPolicy};
|
||||||
|
|
||||||
mod builder;
|
mod builder;
|
||||||
mod error;
|
mod error;
|
||||||
mod format;
|
mod format;
|
||||||
|
mod key;
|
||||||
mod p256;
|
mod p256;
|
||||||
mod plugin;
|
mod plugin;
|
||||||
mod util;
|
mod util;
|
||||||
mod yubikey;
|
|
||||||
|
|
||||||
use error::Error;
|
use error::Error;
|
||||||
|
|
||||||
@@ -51,6 +53,26 @@ const USABLE_SLOTS: [RetiredSlotId; 20] = [
|
|||||||
RetiredSlotId::R20,
|
RetiredSlotId::R20,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
#[derive(RustEmbed)]
|
||||||
|
#[folder = "i18n"]
|
||||||
|
struct Translations;
|
||||||
|
|
||||||
|
const TRANSLATIONS: Translations = Translations {};
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref LANGUAGE_LOADER: FluentLanguageLoader = fluent_language_loader!();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! fl {
|
||||||
|
($message_id:literal) => {{
|
||||||
|
i18n_embed_fl::fl!($crate::LANGUAGE_LOADER, $message_id)
|
||||||
|
}};
|
||||||
|
($message_id:literal, $($kwarg:expr),* $(,)*) => {{
|
||||||
|
i18n_embed_fl::fl!($crate::LANGUAGE_LOADER, $message_id, $($kwarg,)*)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Options)]
|
#[derive(Debug, Options)]
|
||||||
struct PluginOptions {
|
struct PluginOptions {
|
||||||
#[options(help = "Print this help message and exit.")]
|
#[options(help = "Print this help message and exit.")]
|
||||||
@@ -148,7 +170,7 @@ impl TryFrom<PluginOptions> for PluginFlags {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn generate(flags: PluginFlags) -> Result<(), Error> {
|
fn generate(flags: PluginFlags) -> Result<(), Error> {
|
||||||
let mut yubikey = yubikey::open(flags.serial)?;
|
let mut yubikey = key::open(flags.serial)?;
|
||||||
|
|
||||||
let (stub, recipient, metadata) = builder::IdentityBuilder::new(flags.slot)
|
let (stub, recipient, metadata) = builder::IdentityBuilder::new(flags.slot)
|
||||||
.with_name(flags.name)
|
.with_name(flags.name)
|
||||||
@@ -159,39 +181,34 @@ fn generate(flags: PluginFlags) -> Result<(), Error> {
|
|||||||
|
|
||||||
util::print_identity(stub, recipient, metadata);
|
util::print_identity(stub, recipient, metadata);
|
||||||
|
|
||||||
|
// We have written to the YubiKey, which means we've authenticated with the management
|
||||||
|
// key. Out of an abundance of caution, we let the YubiKey be reset on disconnect,
|
||||||
|
// which will clear its PIN and touch caches. This has as small negative UX effect,
|
||||||
|
// but identity generation is a relatively infrequent occurrence, and users are more
|
||||||
|
// likely to see their cached PINs reset due to switching applets (e.g. from PIV to
|
||||||
|
// FIDO2).
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_single(
|
fn print_single(
|
||||||
serial: Option<Serial>,
|
serial: Option<Serial>,
|
||||||
slot: RetiredSlotId,
|
slot: RetiredSlotId,
|
||||||
printer: impl Fn(yubikey::Stub, p256::Recipient, util::Metadata),
|
printer: impl Fn(key::Stub, p256::Recipient, util::Metadata),
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let mut yubikey = yubikey::open(serial)?;
|
let mut yubikey = key::open(serial)?;
|
||||||
|
|
||||||
let mut keys = Key::list(&mut yubikey)?.into_iter().filter_map(|key| {
|
let (key, slot, recipient) = key::list_compatible(&mut yubikey)?
|
||||||
// - We only use the retired slots.
|
|
||||||
// - Only P-256 keys are compatible with us.
|
|
||||||
match (key.slot(), key.certificate().subject_pki()) {
|
|
||||||
(SlotId::Retired(slot), PublicKeyInfo::EcP256(pubkey)) => {
|
|
||||||
p256::Recipient::from_encoded(pubkey).map(|r| (key, slot, r))
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let (key, slot, recipient) = keys
|
|
||||||
.find(|(_, s, _)| s == &slot)
|
.find(|(_, s, _)| s == &slot)
|
||||||
.ok_or(Error::SlotHasNoIdentity(slot))?;
|
.ok_or(Error::SlotHasNoIdentity(slot))?;
|
||||||
|
|
||||||
let stub = yubikey::Stub::new(yubikey.serial(), slot, &recipient);
|
let stub = key::Stub::new(yubikey.serial(), slot, &recipient);
|
||||||
let metadata = x509_parser::parse_x509_certificate(key.certificate().as_ref())
|
let metadata = util::Metadata::extract(&mut yubikey, slot, key.certificate(), true).unwrap();
|
||||||
.ok()
|
|
||||||
.and_then(|(_, cert)| util::Metadata::extract(&mut yubikey, slot, &cert, true))
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
printer(stub, recipient, metadata);
|
printer(stub, recipient, metadata);
|
||||||
|
|
||||||
|
key::disconnect_without_reset(yubikey);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,39 +216,22 @@ fn print_multiple(
|
|||||||
kind: &str,
|
kind: &str,
|
||||||
serial: Option<Serial>,
|
serial: Option<Serial>,
|
||||||
all: bool,
|
all: bool,
|
||||||
printer: impl Fn(yubikey::Stub, p256::Recipient, util::Metadata),
|
printer: impl Fn(key::Stub, p256::Recipient, util::Metadata),
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let mut readers = Readers::open()?;
|
let mut readers = Context::open()?;
|
||||||
|
|
||||||
let mut printed = 0;
|
let mut printed = 0;
|
||||||
for reader in readers.iter()?.filter(yubikey::filter_connected) {
|
for reader in readers.iter()?.filter(key::filter_connected) {
|
||||||
let mut yubikey = reader.open()?;
|
let mut yubikey = key::open_connection(&reader)?;
|
||||||
if let Some(serial) = serial {
|
if let Some(serial) = serial {
|
||||||
if yubikey.serial() != serial {
|
if yubikey.serial() != serial {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for key in Key::list(&mut yubikey)? {
|
for (key, slot, recipient) in key::list_compatible(&mut yubikey)? {
|
||||||
// We only use the retired slots.
|
let stub = key::Stub::new(yubikey.serial(), slot, &recipient);
|
||||||
let slot = match key.slot() {
|
let metadata = match util::Metadata::extract(&mut yubikey, slot, key.certificate(), all)
|
||||||
SlotId::Retired(slot) => slot,
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Only P-256 keys are compatible with us.
|
|
||||||
let recipient = match key.certificate().subject_pki() {
|
|
||||||
PublicKeyInfo::EcP256(pubkey) => match p256::Recipient::from_encoded(pubkey) {
|
|
||||||
Some(recipient) => recipient,
|
|
||||||
None => continue,
|
|
||||||
},
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
let stub = yubikey::Stub::new(yubikey.serial(), slot, &recipient);
|
|
||||||
let metadata = match x509_parser::parse_x509_certificate(key.certificate().as_ref())
|
|
||||||
.ok()
|
|
||||||
.and_then(|(_, cert)| util::Metadata::extract(&mut yubikey, slot, &cert, all))
|
|
||||||
{
|
{
|
||||||
Some(res) => res,
|
Some(res) => res,
|
||||||
None => continue,
|
None => continue,
|
||||||
@@ -242,12 +242,11 @@ fn print_multiple(
|
|||||||
println!();
|
println!();
|
||||||
}
|
}
|
||||||
println!();
|
println!();
|
||||||
|
|
||||||
|
key::disconnect_without_reset(yubikey);
|
||||||
}
|
}
|
||||||
if printed > 1 {
|
if printed > 1 {
|
||||||
eprintln!(
|
eprintln!("{}", fl!("printed-multiple", kind = kind, count = printed));
|
||||||
"Generated {} for {} slots. If you intended to select a slot, use --slot.",
|
|
||||||
kind, printed,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -257,7 +256,7 @@ fn print_details(
|
|||||||
kind: &str,
|
kind: &str,
|
||||||
flags: PluginFlags,
|
flags: PluginFlags,
|
||||||
all: bool,
|
all: bool,
|
||||||
printer: impl Fn(yubikey::Stub, p256::Recipient, util::Metadata),
|
printer: impl Fn(key::Stub, p256::Recipient, util::Metadata),
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
if let Some(slot) = flags.slot {
|
if let Some(slot) = flags.slot {
|
||||||
print_single(flags.serial, slot, printer)
|
print_single(flags.serial, slot, printer)
|
||||||
@@ -273,7 +272,12 @@ fn identity(flags: PluginFlags) -> Result<(), Error> {
|
|||||||
"--identity".into(),
|
"--identity".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
print_details("identities", flags, false, util::print_identity)
|
print_details(
|
||||||
|
&fl!("printed-kind-identities"),
|
||||||
|
flags,
|
||||||
|
false,
|
||||||
|
util::print_identity,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list(flags: PluginFlags, all: bool) -> Result<(), Error> {
|
fn list(flags: PluginFlags, all: bool) -> Result<(), Error> {
|
||||||
@@ -287,10 +291,15 @@ fn list(flags: PluginFlags, all: bool) -> Result<(), Error> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
print_details("recipients", flags, all, |_, recipient, metadata| {
|
print_details(
|
||||||
|
&fl!("printed-kind-recipients"),
|
||||||
|
flags,
|
||||||
|
all,
|
||||||
|
|_, recipient, metadata| {
|
||||||
println!("{}", metadata);
|
println!("{}", metadata);
|
||||||
println!("{}", recipient.to_string());
|
println!("{}", recipient);
|
||||||
})
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<(), Error> {
|
fn main() -> Result<(), Error> {
|
||||||
@@ -300,6 +309,12 @@ fn main() -> Result<(), Error> {
|
|||||||
.parse_default_env()
|
.parse_default_env()
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
|
let requested_languages = DesktopLanguageRequester::requested_languages();
|
||||||
|
i18n_embed::select(&*LANGUAGE_LOADER, &TRANSLATIONS, &requested_languages).unwrap();
|
||||||
|
// Unfortunately the common Windows terminals don't support Unicode Directionality
|
||||||
|
// Isolation Marks, so we disable them for now.
|
||||||
|
LANGUAGE_LOADER.set_use_isolating(false);
|
||||||
|
|
||||||
let opts = PluginOptions::parse_args_default_or_exit();
|
let opts = PluginOptions::parse_args_default_or_exit();
|
||||||
|
|
||||||
if [opts.generate, opts.identity, opts.list, opts.list_all]
|
if [opts.generate, opts.identity, opts.list, opts.list_all]
|
||||||
@@ -335,69 +350,71 @@ fn main() -> Result<(), Error> {
|
|||||||
}
|
}
|
||||||
let flags: PluginFlags = opts.try_into()?;
|
let flags: PluginFlags = opts.try_into()?;
|
||||||
|
|
||||||
eprintln!("✨ Let's get your YubiKey set up for age! ✨");
|
eprintln!(
|
||||||
eprintln!();
|
"{}",
|
||||||
eprintln!("This tool can create a new age identity in a free slot of your YubiKey.");
|
fl!(
|
||||||
eprintln!("It will generate an identity file that you can use with an age client,");
|
"cli-setup-intro",
|
||||||
eprintln!("along with the corresponding recipient. You can also do this directly");
|
generate_usage = "age-plugin-yubikey --generate",
|
||||||
eprintln!("with:");
|
)
|
||||||
eprintln!(" age-plugin-yubikey --generate");
|
);
|
||||||
eprintln!();
|
|
||||||
eprintln!("If you are already using a YubiKey with age, you can select an existing");
|
|
||||||
eprintln!("slot to recreate its corresponding identity file and recipient.");
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("When asked below to select an option, use the up/down arrow keys to");
|
|
||||||
eprintln!("make your choice, or press [Esc] or [q] to quit.");
|
|
||||||
eprintln!();
|
eprintln!();
|
||||||
|
|
||||||
if !Readers::open()?.iter()?.any(yubikey::is_connected) {
|
if !Context::open()?.iter()?.any(key::is_connected) {
|
||||||
eprintln!("⏳ Please insert the YubiKey you want to set up.");
|
eprintln!("{}", fl!("cli-setup-insert-yk"));
|
||||||
};
|
};
|
||||||
let mut readers = yubikey::wait_for_readers()?;
|
let mut readers = key::wait_for_readers()?;
|
||||||
|
|
||||||
// Filter out readers we can't connect to.
|
// Filter out readers we can't connect to.
|
||||||
let readers_list: Vec<_> = readers.iter()?.filter(yubikey::filter_connected).collect();
|
let readers_list: Vec<_> = readers.iter()?.filter(key::filter_connected).collect();
|
||||||
|
|
||||||
let reader_names = readers_list
|
let reader_names = readers_list
|
||||||
.iter()
|
.iter()
|
||||||
.map(|reader| {
|
.map(|reader| {
|
||||||
reader
|
key::open_connection(reader).map(|yk| {
|
||||||
.open()
|
let name = fl!(
|
||||||
.map(|yk| format!("{} (Serial: {})", reader.name(), yk.serial()))
|
"cli-setup-yk-name",
|
||||||
|
yubikey_name = reader.name(),
|
||||||
|
yubikey_serial = yk.serial().to_string(),
|
||||||
|
);
|
||||||
|
key::disconnect_without_reset(yk);
|
||||||
|
name
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
let mut yubikey = match Select::new()
|
let mut yubikey = match Select::new()
|
||||||
.with_prompt("🔑 Select a YubiKey")
|
.with_prompt(fl!("cli-setup-select-yk"))
|
||||||
.items(&reader_names)
|
.items(&reader_names)
|
||||||
.default(0)
|
.default(0)
|
||||||
|
.report(true)
|
||||||
.interact_opt()?
|
.interact_opt()?
|
||||||
{
|
{
|
||||||
Some(yk) => readers_list[yk].open()?,
|
Some(yk) => readers_list[yk].open()?,
|
||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
};
|
};
|
||||||
|
|
||||||
let keys = Key::list(&mut yubikey)?;
|
let keys = key::list_slots(&mut yubikey)?.collect::<Vec<_>>();
|
||||||
|
|
||||||
// Identify slots that we can't allow the user to select.
|
// Identify slots that we can't allow the user to select.
|
||||||
let slot_details: Vec<_> = USABLE_SLOTS
|
let slot_details: Vec<_> = USABLE_SLOTS
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&slot| {
|
.map(|&slot| {
|
||||||
keys.iter()
|
keys.iter()
|
||||||
.find(|key| key.slot() == SlotId::Retired(slot))
|
.find(|(_, s, _)| s == &slot)
|
||||||
.map(|key| match key.certificate().subject_pki() {
|
.map(|(key, _, recipient)| {
|
||||||
PublicKeyInfo::EcP256(pubkey) => {
|
recipient.as_ref().map(|_| {
|
||||||
p256::Recipient::from_encoded(pubkey).map(|_| {
|
|
||||||
// Cache the details we need to display to the user.
|
// Cache the details we need to display to the user.
|
||||||
let (_, cert) =
|
let (_, cert) =
|
||||||
x509_parser::parse_x509_certificate(key.certificate().as_ref())
|
x509_parser::parse_x509_certificate(key.certificate().as_ref())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let (name, _) = util::extract_name(&cert, true).unwrap();
|
let (name, _) = util::extract_name(&cert, true).unwrap();
|
||||||
let created = cert.validity().not_before.to_rfc2822();
|
let created = cert
|
||||||
|
.validity()
|
||||||
|
.not_before
|
||||||
|
.to_rfc2822()
|
||||||
|
.unwrap_or_else(|e| format!("Invalid date: {}", e));
|
||||||
|
|
||||||
format!("{}, created: {}", name, created)
|
format!("{}, created: {}", name, created)
|
||||||
})
|
})
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -410,9 +427,13 @@ fn main() -> Result<(), Error> {
|
|||||||
let i = i + 1;
|
let i = i + 1;
|
||||||
|
|
||||||
match occupied {
|
match occupied {
|
||||||
Some(Some(name)) => format!("Slot {} ({})", i, name),
|
Some(Some(name)) => fl!(
|
||||||
Some(None) => format!("Slot {} (Unusable)", i),
|
"cli-setup-slot-usable",
|
||||||
None => format!("Slot {} (Empty)", i),
|
slot_index = i,
|
||||||
|
slot_name = name.as_str(),
|
||||||
|
),
|
||||||
|
Some(None) => fl!("cli-setup-slot-unusable", slot_index = i),
|
||||||
|
None => fl!("cli-setup-slot-empty", slot_index = i),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -420,9 +441,10 @@ fn main() -> Result<(), Error> {
|
|||||||
let ((stub, recipient, metadata), is_new) = {
|
let ((stub, recipient, metadata), is_new) = {
|
||||||
let (slot_index, slot) = loop {
|
let (slot_index, slot) = loop {
|
||||||
match Select::new()
|
match Select::new()
|
||||||
.with_prompt("🕳️ Select a slot for your age identity")
|
.with_prompt(fl!("cli-setup-select-slot"))
|
||||||
.items(&slots)
|
.items(&slots)
|
||||||
.default(0)
|
.default(0)
|
||||||
|
.report(true)
|
||||||
.interact_opt()?
|
.interact_opt()?
|
||||||
{
|
{
|
||||||
Some(slot) => {
|
Some(slot) => {
|
||||||
@@ -435,43 +457,44 @@ fn main() -> Result<(), Error> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(key) = keys.iter().find(|key| key.slot() == SlotId::Retired(slot)) {
|
if let Some((key, _, recipient)) = keys.into_iter().find(|(_, s, _)| s == &slot) {
|
||||||
let recipient = match key.certificate().subject_pki() {
|
let recipient = recipient.expect("We checked this above");
|
||||||
PublicKeyInfo::EcP256(pubkey) => {
|
|
||||||
p256::Recipient::from_encoded(pubkey).expect("We checked this above")
|
|
||||||
}
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
if Confirm::new()
|
if Confirm::new()
|
||||||
.with_prompt(&format!("Use existing identity in slot {}?", slot_index))
|
.with_prompt(fl!("cli-setup-use-existing", slot_index = slot_index))
|
||||||
|
.report(true)
|
||||||
.interact()?
|
.interact()?
|
||||||
{
|
{
|
||||||
let stub = yubikey::Stub::new(yubikey.serial(), slot, &recipient);
|
let stub = key::Stub::new(yubikey.serial(), slot, &recipient);
|
||||||
let (_, cert) =
|
|
||||||
x509_parser::parse_x509_certificate(key.certificate().as_ref()).unwrap();
|
|
||||||
let metadata =
|
let metadata =
|
||||||
util::Metadata::extract(&mut yubikey, slot, &cert, true).unwrap();
|
util::Metadata::extract(&mut yubikey, slot, key.certificate(), true)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
key::disconnect_without_reset(yubikey);
|
||||||
((stub, recipient, metadata), false)
|
((stub, recipient, metadata), false)
|
||||||
} else {
|
} else {
|
||||||
|
key::disconnect_without_reset(yubikey);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let name = Input::<String>::new()
|
let name = Input::<String>::new()
|
||||||
.with_prompt(format!(
|
.with_prompt(format!(
|
||||||
"📛 Name this identity [{}]",
|
"{} [{}]",
|
||||||
|
fl!("cli-setup-name-identity"),
|
||||||
flags.name.as_deref().unwrap_or("age identity TAG_HEX")
|
flags.name.as_deref().unwrap_or("age identity TAG_HEX")
|
||||||
))
|
))
|
||||||
.allow_empty(true)
|
.allow_empty(true)
|
||||||
|
.report(true)
|
||||||
.interact_text()?;
|
.interact_text()?;
|
||||||
|
|
||||||
|
let mut displayed_yk4_warning = false;
|
||||||
|
let pin_policy = loop {
|
||||||
let pin_policy = match Select::new()
|
let pin_policy = match Select::new()
|
||||||
.with_prompt("🔤 Select a PIN policy")
|
.with_prompt(fl!("cli-setup-select-pin-policy"))
|
||||||
.items(&[
|
.items(&[
|
||||||
"Always (A PIN is required for every decryption, if set)",
|
fl!("pin-policy-always"),
|
||||||
"Once (A PIN is required once per session, if set)",
|
fl!("pin-policy-once"),
|
||||||
"Never (A PIN is NOT required to decrypt)",
|
fl!("pin-policy-never"),
|
||||||
])
|
])
|
||||||
.default(
|
.default(
|
||||||
[PinPolicy::Always, PinPolicy::Once, PinPolicy::Never]
|
[PinPolicy::Always, PinPolicy::Once, PinPolicy::Never]
|
||||||
@@ -481,6 +504,7 @@ fn main() -> Result<(), Error> {
|
|||||||
})
|
})
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
|
.report(true)
|
||||||
.interact_opt()?
|
.interact_opt()?
|
||||||
{
|
{
|
||||||
Some(0) => PinPolicy::Always,
|
Some(0) => PinPolicy::Always,
|
||||||
@@ -490,20 +514,45 @@ fn main() -> Result<(), Error> {
|
|||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// We can't preserve the PIN cache for YubiKey 4 series, because to
|
||||||
|
// retrieve the serial we switch to the OTP applet.
|
||||||
|
match (pin_policy, yubikey.version().major) {
|
||||||
|
(PinPolicy::Once, 4) => {
|
||||||
|
if !displayed_yk4_warning {
|
||||||
|
eprintln!();
|
||||||
|
eprintln!("{}", fl!("cli-setup-yk4-pin-policy"));
|
||||||
|
eprintln!();
|
||||||
|
displayed_yk4_warning = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if Confirm::new()
|
||||||
|
.with_prompt(fl!("cli-setup-yk4-pin-policy-confirm"))
|
||||||
|
.report(true)
|
||||||
|
.interact()?
|
||||||
|
{
|
||||||
|
break pin_policy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => break pin_policy,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let touch_policy = match Select::new()
|
let touch_policy = match Select::new()
|
||||||
.with_prompt("👆 Select a touch policy")
|
.with_prompt(fl!("cli-setup-select-touch-policy"))
|
||||||
.items(&[
|
.items(&[
|
||||||
"Always (A physical touch is required for every decryption)",
|
fl!("touch-policy-always"),
|
||||||
"Cached (A physical touch is required for decryption, and is cached for 15 seconds)",
|
fl!("touch-policy-cached"),
|
||||||
"Never (A physical touch is NOT required to decrypt)",
|
fl!("touch-policy-never"),
|
||||||
])
|
])
|
||||||
.default(
|
.default(
|
||||||
[TouchPolicy::Always, TouchPolicy::Cached, TouchPolicy::Never]
|
[TouchPolicy::Always, TouchPolicy::Cached, TouchPolicy::Never]
|
||||||
.iter()
|
.iter()
|
||||||
.position(|p| p == &flags
|
.position(|p| {
|
||||||
.touch_policy.unwrap_or(builder::DEFAULT_TOUCH_POLICY))
|
p == &flags.touch_policy.unwrap_or(builder::DEFAULT_TOUCH_POLICY)
|
||||||
|
})
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
|
.report(true)
|
||||||
.interact_opt()?
|
.interact_opt()?
|
||||||
{
|
{
|
||||||
Some(0) => TouchPolicy::Always,
|
Some(0) => TouchPolicy::Always,
|
||||||
@@ -514,7 +563,8 @@ fn main() -> Result<(), Error> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if Confirm::new()
|
if Confirm::new()
|
||||||
.with_prompt(&format!("Generate new identity in slot {}?", slot_index))
|
.with_prompt(fl!("cli-setup-generate-new", slot_index = slot_index))
|
||||||
|
.report(true)
|
||||||
.interact()?
|
.interact()?
|
||||||
{
|
{
|
||||||
eprintln!();
|
eprintln!();
|
||||||
@@ -530,6 +580,7 @@ fn main() -> Result<(), Error> {
|
|||||||
true,
|
true,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
|
key::disconnect_without_reset(yubikey);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -537,11 +588,12 @@ fn main() -> Result<(), Error> {
|
|||||||
|
|
||||||
eprintln!();
|
eprintln!();
|
||||||
let file_name = Input::<String>::new()
|
let file_name = Input::<String>::new()
|
||||||
.with_prompt("📝 File name to write this identity to")
|
.with_prompt(fl!("cli-setup-identity-file-name"))
|
||||||
.default(format!(
|
.default(format!(
|
||||||
"age-yubikey-identity-{}.txt",
|
"age-yubikey-identity-{}.txt",
|
||||||
hex::encode(stub.tag)
|
hex::encode(stub.tag)
|
||||||
))
|
))
|
||||||
|
.report(true)
|
||||||
.interact_text()?;
|
.interact_text()?;
|
||||||
|
|
||||||
let mut file = match OpenOptions::new()
|
let mut file = match OpenOptions::new()
|
||||||
@@ -552,7 +604,8 @@ fn main() -> Result<(), Error> {
|
|||||||
Ok(file) => file,
|
Ok(file) => file,
|
||||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
|
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
|
||||||
if Confirm::new()
|
if Confirm::new()
|
||||||
.with_prompt("File exists. Overwrite it?")
|
.with_prompt(fl!("cli-setup-identity-file-exists"))
|
||||||
|
.report(true)
|
||||||
.interact()?
|
.interact()?
|
||||||
{
|
{
|
||||||
File::create(&file_name)?
|
File::create(&file_name)?
|
||||||
@@ -563,54 +616,54 @@ fn main() -> Result<(), Error> {
|
|||||||
Err(e) => return Err(e.into()),
|
Err(e) => return Err(e.into()),
|
||||||
};
|
};
|
||||||
|
|
||||||
writeln!(file, "{}", metadata)?;
|
writeln!(
|
||||||
writeln!(file, "# Recipient: {}", recipient)?;
|
file,
|
||||||
writeln!(file, "{}", stub.to_string())?;
|
"{}",
|
||||||
|
fl!(
|
||||||
|
"yubikey-identity",
|
||||||
|
yubikey_metadata = metadata.to_string(),
|
||||||
|
recipient = recipient.to_string(),
|
||||||
|
identity = stub.to_string(),
|
||||||
|
)
|
||||||
|
)?;
|
||||||
file.sync_data()?;
|
file.sync_data()?;
|
||||||
|
|
||||||
// If `rage` binary is installed, use it in examples. Otherwise default to `age`.
|
// If `rage` binary is installed, use it in examples. Otherwise default to `age`.
|
||||||
let age_binary = which::which("rage").map(|_| "rage").unwrap_or("age");
|
let age_binary = which::which("rage").map(|_| "rage").unwrap_or("age");
|
||||||
|
|
||||||
eprintln!();
|
let encrypt_usage = format!(
|
||||||
eprintln!("✅ Done! This YubiKey identity is ready to go.");
|
|
||||||
eprintln!();
|
|
||||||
if is_new {
|
|
||||||
eprintln!("🔑 Here's your shiny new YubiKey recipient:");
|
|
||||||
} else {
|
|
||||||
eprintln!("🔑 Here's the corresponding YubiKey recipient:");
|
|
||||||
}
|
|
||||||
eprintln!(" {}", recipient);
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("Here are some example things you can do with it:");
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("- Encrypt a file to this identity:");
|
|
||||||
eprintln!(
|
|
||||||
"$ cat foo.txt | {} -r {} -o foo.txt.age",
|
"$ cat foo.txt | {} -r {} -o foo.txt.age",
|
||||||
age_binary, recipient
|
age_binary, recipient
|
||||||
);
|
);
|
||||||
eprintln!();
|
let decrypt_usage = format!(
|
||||||
eprintln!("- Decrypt a file with this identity:");
|
|
||||||
eprintln!(
|
|
||||||
"$ cat foo.txt.age | {} -d -i {} > foo.txt",
|
"$ cat foo.txt.age | {} -d -i {} > foo.txt",
|
||||||
age_binary, file_name
|
age_binary, file_name
|
||||||
);
|
);
|
||||||
eprintln!();
|
let identity_usage = format!(
|
||||||
eprintln!("- Recreate the identity file:");
|
|
||||||
eprintln!(
|
|
||||||
"$ age-plugin-yubikey -i --serial {} --slot {} > {}",
|
"$ age-plugin-yubikey -i --serial {} --slot {} > {}",
|
||||||
stub.serial,
|
stub.serial,
|
||||||
util::slot_to_ui(&stub.slot),
|
util::slot_to_ui(&stub.slot),
|
||||||
file_name,
|
file_name,
|
||||||
);
|
);
|
||||||
eprintln!();
|
let recipient_usage = format!(
|
||||||
eprintln!("- Recreate the recipient:");
|
|
||||||
eprintln!(
|
|
||||||
"$ age-plugin-yubikey -l --serial {} --slot {}",
|
"$ age-plugin-yubikey -l --serial {} --slot {}",
|
||||||
stub.serial,
|
stub.serial,
|
||||||
util::slot_to_ui(&stub.slot),
|
util::slot_to_ui(&stub.slot),
|
||||||
);
|
);
|
||||||
|
|
||||||
eprintln!();
|
eprintln!();
|
||||||
eprintln!("💭 Remember: everything breaks, have a backup plan for when this YubiKey does.");
|
eprintln!(
|
||||||
|
"{}",
|
||||||
|
fl!(
|
||||||
|
"cli-setup-finished",
|
||||||
|
is_new = if is_new { "true" } else { "false" },
|
||||||
|
recipient = recipient.to_string(),
|
||||||
|
encrypt_usage = encrypt_usage,
|
||||||
|
decrypt_usage = decrypt_usage,
|
||||||
|
identity_usage = identity_usage,
|
||||||
|
recipient_usage = recipient_usage,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-3
@@ -1,7 +1,8 @@
|
|||||||
use bech32::{ToBase32, Variant};
|
use bech32::{ToBase32, Variant};
|
||||||
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
|
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::convert::TryInto;
|
use yubikey::{certificate::PublicKeyInfo, Certificate};
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use crate::RECIPIENT_PREFIX;
|
use crate::RECIPIENT_PREFIX;
|
||||||
@@ -43,12 +44,23 @@ impl Recipient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn from_certificate(cert: &Certificate) -> Option<Self> {
|
||||||
|
Self::from_spki(cert.subject_pki())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn from_spki(spki: &PublicKeyInfo) -> Option<Self> {
|
||||||
|
match spki {
|
||||||
|
PublicKeyInfo::EcP256(pubkey) => Self::from_encoded(pubkey),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Attempts to parse a valid YubiKey recipient from its SEC-1 encoding.
|
/// Attempts to parse a valid YubiKey recipient from its SEC-1 encoding.
|
||||||
///
|
///
|
||||||
/// This accepts both compressed (as used by the plugin) and uncompressed (as used in
|
/// This accepts both compressed (as used by the plugin) and uncompressed (as used in
|
||||||
/// the YubiKey certificate) encodings.
|
/// the YubiKey certificate) encodings.
|
||||||
pub(crate) fn from_encoded(encoded: &p256::EncodedPoint) -> Option<Self> {
|
fn from_encoded(encoded: &p256::EncodedPoint) -> Option<Self> {
|
||||||
p256::PublicKey::from_encoded_point(&encoded).map(Recipient)
|
Option::from(p256::PublicKey::from_encoded_point(encoded)).map(Recipient)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the compressed SEC-1 encoding of this recipient.
|
/// Returns the compressed SEC-1 encoding of this recipient.
|
||||||
|
|||||||
+36
-21
@@ -7,12 +7,12 @@ use age_plugin::{
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
use crate::{format, p256::Recipient, yubikey, PLUGIN_NAME};
|
use crate::{fl, format, key, p256::Recipient, PLUGIN_NAME};
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub(crate) struct RecipientPlugin {
|
pub(crate) struct RecipientPlugin {
|
||||||
recipients: Vec<Recipient>,
|
recipients: Vec<Recipient>,
|
||||||
yubikeys: Vec<yubikey::Stub>,
|
yubikeys: Vec<key::Stub>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RecipientPluginV1 for RecipientPlugin {
|
impl RecipientPluginV1 for RecipientPlugin {
|
||||||
@@ -23,7 +23,7 @@ impl RecipientPluginV1 for RecipientPlugin {
|
|||||||
bytes: &[u8],
|
bytes: &[u8],
|
||||||
) -> Result<(), recipient::Error> {
|
) -> Result<(), recipient::Error> {
|
||||||
if let Some(pk) = if plugin_name == PLUGIN_NAME {
|
if let Some(pk) = if plugin_name == PLUGIN_NAME {
|
||||||
Recipient::from_bytes(&bytes)
|
Recipient::from_bytes(bytes)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
} {
|
} {
|
||||||
@@ -32,7 +32,7 @@ impl RecipientPluginV1 for RecipientPlugin {
|
|||||||
} else {
|
} else {
|
||||||
Err(recipient::Error::Recipient {
|
Err(recipient::Error::Recipient {
|
||||||
index,
|
index,
|
||||||
message: "Invalid recipient".to_owned(),
|
message: fl!("plugin-err-invalid-recipient"),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,7 @@ impl RecipientPluginV1 for RecipientPlugin {
|
|||||||
bytes: &[u8],
|
bytes: &[u8],
|
||||||
) -> Result<(), recipient::Error> {
|
) -> Result<(), recipient::Error> {
|
||||||
if let Some(stub) = if plugin_name == PLUGIN_NAME {
|
if let Some(stub) = if plugin_name == PLUGIN_NAME {
|
||||||
yubikey::Stub::from_bytes(&bytes, index)
|
key::Stub::from_bytes(bytes, index)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
} {
|
} {
|
||||||
@@ -53,7 +53,7 @@ impl RecipientPluginV1 for RecipientPlugin {
|
|||||||
} else {
|
} else {
|
||||||
Err(recipient::Error::Identity {
|
Err(recipient::Error::Identity {
|
||||||
index,
|
index,
|
||||||
message: "Invalid Yubikey stub".to_owned(),
|
message: fl!("plugin-err-invalid-identity"),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,7 +68,14 @@ impl RecipientPluginV1 for RecipientPlugin {
|
|||||||
let mut yk_errors = vec![];
|
let mut yk_errors = vec![];
|
||||||
for stub in &self.yubikeys {
|
for stub in &self.yubikeys {
|
||||||
match stub.connect(&mut callbacks)? {
|
match stub.connect(&mut callbacks)? {
|
||||||
Ok(conn) => yk_recipients.push(conn.recipient().clone()),
|
Ok(Some(conn)) => yk_recipients.push(conn.recipient().clone()),
|
||||||
|
Ok(None) => yk_errors.push(recipient::Error::Identity {
|
||||||
|
index: stub.identity_index,
|
||||||
|
message: fl!(
|
||||||
|
"plugin-err-yk-opening",
|
||||||
|
yubikey_serial = stub.serial.to_string(),
|
||||||
|
),
|
||||||
|
}),
|
||||||
Err(e) => yk_errors.push(match e {
|
Err(e) => yk_errors.push(match e {
|
||||||
identity::Error::Identity { index, message } => {
|
identity::Error::Identity { index, message } => {
|
||||||
recipient::Error::Identity { index, message }
|
recipient::Error::Identity { index, message }
|
||||||
@@ -88,7 +95,7 @@ impl RecipientPluginV1 for RecipientPlugin {
|
|||||||
self.recipients
|
self.recipients
|
||||||
.iter()
|
.iter()
|
||||||
.chain(yk_recipients.iter())
|
.chain(yk_recipients.iter())
|
||||||
.map(|pk| format::RecipientLine::wrap_file_key(&file_key, &pk).into())
|
.map(|pk| format::RecipientLine::wrap_file_key(&file_key, pk).into())
|
||||||
.collect()
|
.collect()
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
@@ -100,7 +107,7 @@ impl RecipientPluginV1 for RecipientPlugin {
|
|||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub(crate) struct IdentityPlugin {
|
pub(crate) struct IdentityPlugin {
|
||||||
yubikeys: Vec<yubikey::Stub>,
|
yubikeys: Vec<key::Stub>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IdentityPluginV1 for IdentityPlugin {
|
impl IdentityPluginV1 for IdentityPlugin {
|
||||||
@@ -111,7 +118,7 @@ impl IdentityPluginV1 for IdentityPlugin {
|
|||||||
bytes: &[u8],
|
bytes: &[u8],
|
||||||
) -> Result<(), identity::Error> {
|
) -> Result<(), identity::Error> {
|
||||||
if let Some(stub) = if plugin_name == PLUGIN_NAME {
|
if let Some(stub) = if plugin_name == PLUGIN_NAME {
|
||||||
yubikey::Stub::from_bytes(&bytes, index)
|
key::Stub::from_bytes(bytes, index)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
} {
|
} {
|
||||||
@@ -120,7 +127,7 @@ impl IdentityPluginV1 for IdentityPlugin {
|
|||||||
} else {
|
} else {
|
||||||
Err(identity::Error::Identity {
|
Err(identity::Error::Identity {
|
||||||
index,
|
index,
|
||||||
message: "Invalid Yubikey stub".to_owned(),
|
message: fl!("plugin-err-invalid-identity"),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,11 +140,8 @@ impl IdentityPluginV1 for IdentityPlugin {
|
|||||||
let mut file_keys = HashMap::with_capacity(files.len());
|
let mut file_keys = HashMap::with_capacity(files.len());
|
||||||
|
|
||||||
// Filter to files / stanzas for which we have matching YubiKeys
|
// Filter to files / stanzas for which we have matching YubiKeys
|
||||||
let mut candidate_stanzas: Vec<(
|
let mut candidate_stanzas: Vec<(&key::Stub, HashMap<usize, Vec<format::RecipientLine>>)> =
|
||||||
&yubikey::Stub,
|
self.yubikeys
|
||||||
HashMap<usize, Vec<format::RecipientLine>>,
|
|
||||||
)> = self
|
|
||||||
.yubikeys
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|stub| (stub, HashMap::new()))
|
.map(|stub| (stub, HashMap::new()))
|
||||||
.collect();
|
.collect();
|
||||||
@@ -145,11 +149,11 @@ impl IdentityPluginV1 for IdentityPlugin {
|
|||||||
for (file, stanzas) in files.iter().enumerate() {
|
for (file, stanzas) in files.iter().enumerate() {
|
||||||
for (stanza_index, stanza) in stanzas.iter().enumerate() {
|
for (stanza_index, stanza) in stanzas.iter().enumerate() {
|
||||||
match (
|
match (
|
||||||
format::RecipientLine::from_stanza(&stanza).map(|res| {
|
format::RecipientLine::from_stanza(stanza).map(|res| {
|
||||||
res.map_err(|_| identity::Error::Stanza {
|
res.map_err(|_| identity::Error::Stanza {
|
||||||
file_index: file,
|
file_index: file,
|
||||||
stanza_index,
|
stanza_index,
|
||||||
message: "Invalid yubikey stanza".to_owned(),
|
message: fl!("plugin-err-invalid-stanza"),
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
file_keys.contains_key(&file),
|
file_keys.contains_key(&file),
|
||||||
@@ -206,13 +210,22 @@ impl IdentityPluginV1 for IdentityPlugin {
|
|||||||
|
|
||||||
for (stub, files) in candidate_stanzas.iter() {
|
for (stub, files) in candidate_stanzas.iter() {
|
||||||
let mut conn = match stub.connect(&mut callbacks)? {
|
let mut conn = match stub.connect(&mut callbacks)? {
|
||||||
Ok(conn) => conn,
|
// The user skipped this YubiKey.
|
||||||
|
Ok(None) => continue,
|
||||||
|
// We connected to this YubiKey.
|
||||||
|
Ok(Some(conn)) => conn,
|
||||||
|
// We failed to connect to this YubiKey.
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
callbacks.error(e)?.unwrap();
|
callbacks.error(e)?.unwrap();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Err(e) = conn.request_pin_if_necessary(&mut callbacks)? {
|
||||||
|
callbacks.error(e)?.unwrap();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
for (&file_index, stanzas) in files {
|
for (&file_index, stanzas) in files {
|
||||||
if file_keys.contains_key(&file_index) {
|
if file_keys.contains_key(&file_index) {
|
||||||
// We decrypted this file with an earlier YubiKey.
|
// We decrypted this file with an earlier YubiKey.
|
||||||
@@ -220,7 +233,7 @@ impl IdentityPluginV1 for IdentityPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (stanza_index, line) in stanzas.iter().enumerate() {
|
for (stanza_index, line) in stanzas.iter().enumerate() {
|
||||||
match conn.unwrap_file_key(&line) {
|
match conn.unwrap_file_key(line) {
|
||||||
Ok(file_key) => {
|
Ok(file_key) => {
|
||||||
// We've managed to decrypt this file!
|
// We've managed to decrypt this file!
|
||||||
file_keys.entry(file_index).or_insert(Ok(file_key));
|
file_keys.entry(file_index).or_insert(Ok(file_key));
|
||||||
@@ -230,12 +243,14 @@ impl IdentityPluginV1 for IdentityPlugin {
|
|||||||
.error(identity::Error::Stanza {
|
.error(identity::Error::Stanza {
|
||||||
file_index,
|
file_index,
|
||||||
stanza_index,
|
stanza_index,
|
||||||
message: "Failed to decrypt YubiKey stanza".to_owned(),
|
message: fl!("plugin-err-decryption-failed"),
|
||||||
})?
|
})?
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
conn.disconnect_without_reset();
|
||||||
}
|
}
|
||||||
Ok(file_keys)
|
Ok(file_keys)
|
||||||
}
|
}
|
||||||
|
|||||||
+62
-39
@@ -1,13 +1,14 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
use std::iter;
|
||||||
|
|
||||||
use x509_parser::{certificate::X509Certificate, der_parser::oid::Oid};
|
use x509_parser::{certificate::X509Certificate, der_parser::oid::Oid};
|
||||||
use yubikey_piv::{
|
use yubikey::{
|
||||||
key::{RetiredSlotId, SlotId},
|
piv::{RetiredSlotId, SlotId},
|
||||||
policy::{PinPolicy, TouchPolicy},
|
Certificate, PinPolicy, Serial, TouchPolicy, YubiKey,
|
||||||
Serial, YubiKey,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{error::Error, p256::Recipient, yubikey::Stub, BINARY_NAME, USABLE_SLOTS};
|
use crate::fl;
|
||||||
|
use crate::{error::Error, key::Stub, p256::Recipient, BINARY_NAME, USABLE_SLOTS};
|
||||||
|
|
||||||
pub(crate) const POLICY_EXTENSION_OID: &[u64] = &[1, 3, 6, 1, 4, 1, 41482, 3, 8];
|
pub(crate) const POLICY_EXTENSION_OID: &[u64] = &[1, 3, 6, 1, 4, 1, 41482, 3, 8];
|
||||||
|
|
||||||
@@ -42,24 +43,31 @@ pub(crate) fn touch_policy_from_string(s: String) -> Result<TouchPolicy, Error>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn pin_policy_to_str(policy: Option<PinPolicy>) -> &'static str {
|
pub(crate) fn pin_policy_to_str(policy: Option<PinPolicy>) -> String {
|
||||||
match policy {
|
match policy {
|
||||||
Some(PinPolicy::Always) => "Always (A PIN is required for every decryption, if set)",
|
Some(PinPolicy::Always) => fl!("pin-policy-always"),
|
||||||
Some(PinPolicy::Once) => "Once (A PIN is required once per session, if set)",
|
Some(PinPolicy::Once) => fl!("pin-policy-once"),
|
||||||
Some(PinPolicy::Never) => "Never (A PIN is NOT required to decrypt)",
|
Some(PinPolicy::Never) => fl!("pin-policy-never"),
|
||||||
_ => "Unknown",
|
_ => fl!("unknown-policy"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn touch_policy_to_str(policy: Option<TouchPolicy>) -> &'static str {
|
pub(crate) fn touch_policy_to_str(policy: Option<TouchPolicy>) -> String {
|
||||||
match policy {
|
match policy {
|
||||||
Some(TouchPolicy::Always) => "Always (A physical touch is required for every decryption)",
|
Some(TouchPolicy::Always) => fl!("touch-policy-always"),
|
||||||
Some(TouchPolicy::Cached) => {
|
Some(TouchPolicy::Cached) => fl!("touch-policy-cached"),
|
||||||
"Cached (A physical touch is required for decryption, and is cached for 15 seconds)"
|
Some(TouchPolicy::Never) => fl!("touch-policy-never"),
|
||||||
|
_ => fl!("unknown-policy"),
|
||||||
}
|
}
|
||||||
Some(TouchPolicy::Never) => "Never (A physical touch is NOT required to decrypt)",
|
|
||||||
_ => "Unknown",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MODHEX: &str = "cbdefghijklnrtuv";
|
||||||
|
pub(crate) fn otp_serial_prefix(serial: Serial) -> String {
|
||||||
|
iter::repeat(0)
|
||||||
|
.take(4)
|
||||||
|
.chain((0..8).rev().map(|i| (serial.0 >> (4 * i)) & 0x0f))
|
||||||
|
.map(|i| MODHEX.char_indices().nth(i as usize).unwrap().1)
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn extract_name(cert: &X509Certificate, all: bool) -> Option<(String, bool)> {
|
pub(crate) fn extract_name(cert: &X509Certificate, all: bool) -> Option<(String, bool)> {
|
||||||
@@ -96,23 +104,28 @@ pub(crate) struct Metadata {
|
|||||||
slot: RetiredSlotId,
|
slot: RetiredSlotId,
|
||||||
name: String,
|
name: String,
|
||||||
created: String,
|
created: String,
|
||||||
pin_policy: Option<PinPolicy>,
|
pub(crate) pin_policy: Option<PinPolicy>,
|
||||||
touch_policy: Option<TouchPolicy>,
|
pub(crate) touch_policy: Option<TouchPolicy>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Metadata {
|
impl Metadata {
|
||||||
pub(crate) fn extract(
|
pub(crate) fn extract(
|
||||||
yubikey: &mut YubiKey,
|
yubikey: &mut YubiKey,
|
||||||
slot: RetiredSlotId,
|
slot: RetiredSlotId,
|
||||||
cert: &X509Certificate,
|
cert: &Certificate,
|
||||||
all: bool,
|
all: bool,
|
||||||
) -> Option<Self> {
|
) -> Option<Self> {
|
||||||
|
let (_, cert) = x509_parser::parse_x509_certificate(cert.as_ref()).ok()?;
|
||||||
|
|
||||||
// We store the PIN and touch policies for identities in their certificates
|
// We store the PIN and touch policies for identities in their certificates
|
||||||
// using the same certificate extension as PIV attestations.
|
// using the same certificate extension as PIV attestations.
|
||||||
// https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
|
// https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
|
||||||
let policies = |c: &X509Certificate| {
|
let policies = |c: &X509Certificate| {
|
||||||
c.extensions()
|
c.tbs_certificate
|
||||||
.get(&Oid::from(POLICY_EXTENSION_OID).unwrap())
|
.get_extension_unique(&Oid::from(POLICY_EXTENSION_OID).unwrap())
|
||||||
|
// If the extension is duplicated, we assume it is invalid.
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
// If the encoded extension doesn't have 2 bytes, we assume it is invalid.
|
// If the encoded extension doesn't have 2 bytes, we assume it is invalid.
|
||||||
.filter(|policy| policy.value.len() >= 2)
|
.filter(|policy| policy.value.len() >= 2)
|
||||||
.map(|policy| {
|
.map(|policy| {
|
||||||
@@ -135,7 +148,7 @@ impl Metadata {
|
|||||||
.unwrap_or((None, None))
|
.unwrap_or((None, None))
|
||||||
};
|
};
|
||||||
|
|
||||||
extract_name(cert, all)
|
extract_name(&cert, all)
|
||||||
.map(|(name, ours)| {
|
.map(|(name, ours)| {
|
||||||
if ours {
|
if ours {
|
||||||
let (pin_policy, touch_policy) = policies(&cert);
|
let (pin_policy, touch_policy) = policies(&cert);
|
||||||
@@ -144,7 +157,7 @@ impl Metadata {
|
|||||||
// We can extract the PIN and touch policies via an attestation. This
|
// We can extract the PIN and touch policies via an attestation. This
|
||||||
// is slow, but the user has asked for all compatible keys, so...
|
// is slow, but the user has asked for all compatible keys, so...
|
||||||
let (pin_policy, touch_policy) =
|
let (pin_policy, touch_policy) =
|
||||||
yubikey_piv::key::attest(yubikey, SlotId::Retired(slot))
|
yubikey::piv::attest(yubikey, SlotId::Retired(slot))
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|buf| {
|
.and_then(|buf| {
|
||||||
x509_parser::parse_x509_certificate(&buf)
|
x509_parser::parse_x509_certificate(&buf)
|
||||||
@@ -160,7 +173,11 @@ impl Metadata {
|
|||||||
serial: yubikey.serial(),
|
serial: yubikey.serial(),
|
||||||
slot,
|
slot,
|
||||||
name,
|
name,
|
||||||
created: cert.validity().not_before.to_rfc2822(),
|
created: cert
|
||||||
|
.validity()
|
||||||
|
.not_before
|
||||||
|
.to_rfc2822()
|
||||||
|
.unwrap_or_else(|e| format!("Invalid date: {}", e)),
|
||||||
pin_policy,
|
pin_policy,
|
||||||
touch_policy,
|
touch_policy,
|
||||||
})
|
})
|
||||||
@@ -169,19 +186,18 @@ impl Metadata {
|
|||||||
|
|
||||||
impl fmt::Display for Metadata {
|
impl fmt::Display for Metadata {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
writeln!(
|
|
||||||
f,
|
|
||||||
"# Serial: {}, Slot: {}",
|
|
||||||
self.serial,
|
|
||||||
slot_to_ui(&self.slot)
|
|
||||||
)?;
|
|
||||||
writeln!(f, "# Name: {}", self.name)?;
|
|
||||||
writeln!(f, "# Created: {}", self.created)?;
|
|
||||||
writeln!(f, "# PIN policy: {}", pin_policy_to_str(self.pin_policy))?;
|
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
"# Touch policy: {}",
|
"{}",
|
||||||
touch_policy_to_str(self.touch_policy)
|
fl!(
|
||||||
|
"yubikey-metadata",
|
||||||
|
serial = self.serial.to_string(),
|
||||||
|
slot = slot_to_ui(&self.slot),
|
||||||
|
name = self.name.as_str(),
|
||||||
|
created = self.created.as_str(),
|
||||||
|
pin_policy = pin_policy_to_str(self.pin_policy),
|
||||||
|
touch_policy = touch_policy_to_str(self.touch_policy),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -189,10 +205,17 @@ impl fmt::Display for Metadata {
|
|||||||
pub(crate) fn print_identity(stub: Stub, recipient: Recipient, metadata: Metadata) {
|
pub(crate) fn print_identity(stub: Stub, recipient: Recipient, metadata: Metadata) {
|
||||||
let recipient = recipient.to_string();
|
let recipient = recipient.to_string();
|
||||||
if !console::user_attended() {
|
if !console::user_attended() {
|
||||||
eprintln!("Recipient: {}", recipient);
|
let recipient = recipient.as_str();
|
||||||
|
eprintln!("{}", fl!("print-recipient", recipient = recipient));
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("{}", metadata);
|
println!(
|
||||||
println!("# Recipient: {}", recipient);
|
"{}",
|
||||||
println!("{}", stub.to_string());
|
fl!(
|
||||||
|
"yubikey-identity",
|
||||||
|
yubikey_metadata = metadata.to_string(),
|
||||||
|
recipient = recipient,
|
||||||
|
identity = stub.to_string(),
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
-409
@@ -1,409 +0,0 @@
|
|||||||
//! Structs for handling YubiKeys.
|
|
||||||
|
|
||||||
use age_core::{
|
|
||||||
format::{FileKey, FILE_KEY_BYTES},
|
|
||||||
primitives::{aead_decrypt, hkdf},
|
|
||||||
};
|
|
||||||
use age_plugin::{identity, Callbacks};
|
|
||||||
use bech32::{ToBase32, Variant};
|
|
||||||
use dialoguer::Password;
|
|
||||||
use log::warn;
|
|
||||||
use secrecy::ExposeSecret;
|
|
||||||
use std::convert::TryInto;
|
|
||||||
use std::fmt;
|
|
||||||
use std::io;
|
|
||||||
use std::iter;
|
|
||||||
use std::thread::sleep;
|
|
||||||
use std::time::{Duration, SystemTime};
|
|
||||||
use yubikey_piv::{
|
|
||||||
certificate::{Certificate, PublicKeyInfo},
|
|
||||||
key::{decrypt_data, AlgorithmId, RetiredSlotId, SlotId},
|
|
||||||
readers::Reader,
|
|
||||||
yubikey::Serial,
|
|
||||||
MgmKey, Readers, YubiKey,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
error::Error,
|
|
||||||
format::{RecipientLine, STANZA_KEY_LABEL},
|
|
||||||
p256::{Recipient, TAG_BYTES},
|
|
||||||
IDENTITY_PREFIX,
|
|
||||||
};
|
|
||||||
|
|
||||||
const ONE_SECOND: Duration = Duration::from_secs(1);
|
|
||||||
const FIFTEEN_SECONDS: Duration = Duration::from_secs(15);
|
|
||||||
|
|
||||||
pub(crate) fn is_connected(reader: Reader) -> bool {
|
|
||||||
filter_connected(&reader)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn filter_connected(reader: &Reader) -> bool {
|
|
||||||
match reader.open() {
|
|
||||||
Ok(_) => true,
|
|
||||||
Err(e) => {
|
|
||||||
use std::error::Error;
|
|
||||||
if let Some(pcsc::Error::RemovedCard) =
|
|
||||||
e.source().and_then(|inner| inner.downcast_ref())
|
|
||||||
{
|
|
||||||
warn!("Ignoring {}: not connected", reader.name());
|
|
||||||
false
|
|
||||||
} else {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn wait_for_readers() -> Result<Readers, Error> {
|
|
||||||
// Start a 15-second timer waiting for a YubiKey to be inserted (if necessary).
|
|
||||||
let start = SystemTime::now();
|
|
||||||
loop {
|
|
||||||
let mut readers = Readers::open()?;
|
|
||||||
if readers.iter()?.any(is_connected) {
|
|
||||||
break Ok(readers);
|
|
||||||
}
|
|
||||||
|
|
||||||
match SystemTime::now().duration_since(start) {
|
|
||||||
Ok(end) if end >= FIFTEEN_SECONDS => return Err(Error::TimedOut),
|
|
||||||
_ => sleep(ONE_SECOND),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn open(serial: Option<Serial>) -> Result<YubiKey, Error> {
|
|
||||||
if !Readers::open()?.iter()?.any(is_connected) {
|
|
||||||
if let Some(serial) = serial {
|
|
||||||
eprintln!("⏳ Please insert the YubiKey with serial {}.", serial);
|
|
||||||
} else {
|
|
||||||
eprintln!("⏳ Please insert the YubiKey.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut readers = wait_for_readers()?;
|
|
||||||
let mut readers_iter = readers.iter()?.filter(filter_connected);
|
|
||||||
|
|
||||||
// --serial selects the YubiKey to use. If not provided, and more than one YubiKey is
|
|
||||||
// connected, an error is returned.
|
|
||||||
let yubikey = match (readers_iter.next(), readers_iter.next(), serial) {
|
|
||||||
(None, _, _) => unreachable!(),
|
|
||||||
(Some(reader), None, None) => reader.open()?,
|
|
||||||
(Some(reader), None, Some(serial)) => {
|
|
||||||
let yubikey = reader.open()?;
|
|
||||||
if yubikey.serial() != serial {
|
|
||||||
return Err(Error::NoMatchingSerial(serial));
|
|
||||||
}
|
|
||||||
yubikey
|
|
||||||
}
|
|
||||||
(Some(a), Some(b), Some(serial)) => {
|
|
||||||
let reader = iter::empty()
|
|
||||||
.chain(Some(a))
|
|
||||||
.chain(Some(b))
|
|
||||||
.chain(readers_iter)
|
|
||||||
.find(|reader| match reader.open() {
|
|
||||||
Ok(yk) => yk.serial() == serial,
|
|
||||||
_ => false,
|
|
||||||
})
|
|
||||||
.ok_or(Error::NoMatchingSerial(serial))?;
|
|
||||||
reader.open()?
|
|
||||||
}
|
|
||||||
(Some(_), Some(_), None) => return Err(Error::MultipleYubiKeys),
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(yubikey)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn manage(yubikey: &mut YubiKey) -> Result<(), Error> {
|
|
||||||
eprintln!();
|
|
||||||
let pin = Password::new()
|
|
||||||
.with_prompt(&format!(
|
|
||||||
"Enter PIN for YubiKey with serial {} (default is 123456)",
|
|
||||||
yubikey.serial(),
|
|
||||||
))
|
|
||||||
.interact()?;
|
|
||||||
yubikey.verify_pin(pin.as_bytes())?;
|
|
||||||
|
|
||||||
// If the user is using the default PIN, help them to change it.
|
|
||||||
if pin == "123456" {
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("✨ Your YubiKey is using the default PIN. Let's change it!");
|
|
||||||
eprintln!("✨ We'll also set the PUK equal to the PIN.");
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("🔐 The PIN is up to 8 numbers, letters, or symbols. Not just numbers!");
|
|
||||||
eprintln!(
|
|
||||||
"❌ Your keys will be lost if the PIN and PUK are locked after 3 incorrect tries."
|
|
||||||
);
|
|
||||||
eprintln!();
|
|
||||||
let current_puk = Password::new()
|
|
||||||
.with_prompt("Enter current PUK (default is 12345678)")
|
|
||||||
.interact()?;
|
|
||||||
let new_pin = Password::new()
|
|
||||||
.with_prompt("Choose a new PIN/PUK")
|
|
||||||
.with_confirmation("Repeat the PIN/PUK", "PINs don't match")
|
|
||||||
.interact()?;
|
|
||||||
if new_pin.len() > 8 {
|
|
||||||
return Err(Error::InvalidPinLength);
|
|
||||||
}
|
|
||||||
yubikey.change_puk(current_puk.as_bytes(), new_pin.as_bytes())?;
|
|
||||||
yubikey.change_pin(pin.as_bytes(), new_pin.as_bytes())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(mgm_key) = MgmKey::get_protected(yubikey) {
|
|
||||||
yubikey.authenticate(mgm_key)?;
|
|
||||||
} else {
|
|
||||||
// Try to authenticate with the default management key.
|
|
||||||
yubikey
|
|
||||||
.authenticate(MgmKey::default())
|
|
||||||
.map_err(|_| Error::CustomManagementKey)?;
|
|
||||||
|
|
||||||
// Migrate to a PIN-protected management key.
|
|
||||||
let mgm_key = MgmKey::generate()?;
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("✨ Your YubiKey is using the default management key.");
|
|
||||||
eprintln!("✨ We'll migrate it to a PIN-protected management key.");
|
|
||||||
eprint!("... ");
|
|
||||||
mgm_key.set_protected(yubikey).map_err(|e| {
|
|
||||||
eprintln!("An error occurred while setting the new management key.");
|
|
||||||
eprintln!("⚠️ SAVE THIS MANAGEMENT KEY - YOU MAY NEED IT TO MANAGE YOUR YubiKey! ⚠️");
|
|
||||||
eprintln!(" {}", hex::encode(mgm_key.as_ref()));
|
|
||||||
e
|
|
||||||
})?;
|
|
||||||
eprintln!("Success!");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A reference to an age key stored in a YubiKey.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Stub {
|
|
||||||
pub(crate) serial: Serial,
|
|
||||||
pub(crate) slot: RetiredSlotId,
|
|
||||||
pub(crate) tag: [u8; TAG_BYTES],
|
|
||||||
identity_index: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for Stub {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.write_str(
|
|
||||||
bech32::encode(
|
|
||||||
IDENTITY_PREFIX,
|
|
||||||
self.to_bytes().to_base32(),
|
|
||||||
Variant::Bech32,
|
|
||||||
)
|
|
||||||
.expect("HRP is valid")
|
|
||||||
.to_uppercase()
|
|
||||||
.as_str(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for Stub {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.to_bytes().eq(&other.to_bytes())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Stub {
|
|
||||||
/// Returns a key stub and recipient for this `(Serial, SlotId, PublicKey)` tuple.
|
|
||||||
///
|
|
||||||
/// Does not check that the `PublicKey` matches the given `(Serial, SlotId)` tuple;
|
|
||||||
/// this is checked at decryption time.
|
|
||||||
pub(crate) fn new(serial: Serial, slot: RetiredSlotId, recipient: &Recipient) -> Self {
|
|
||||||
Stub {
|
|
||||||
serial,
|
|
||||||
slot,
|
|
||||||
tag: recipient.tag(),
|
|
||||||
identity_index: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn from_bytes(bytes: &[u8], identity_index: usize) -> Option<Self> {
|
|
||||||
let serial = Serial::from(u32::from_le_bytes(bytes[0..4].try_into().unwrap()));
|
|
||||||
let slot: RetiredSlotId = bytes[4].try_into().ok()?;
|
|
||||||
Some(Stub {
|
|
||||||
serial,
|
|
||||||
slot,
|
|
||||||
tag: bytes[5..9].try_into().unwrap(),
|
|
||||||
identity_index,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_bytes(&self) -> Vec<u8> {
|
|
||||||
let mut bytes = Vec::with_capacity(9);
|
|
||||||
bytes.extend_from_slice(&self.serial.0.to_le_bytes());
|
|
||||||
bytes.push(self.slot.into());
|
|
||||||
bytes.extend_from_slice(&self.tag);
|
|
||||||
bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn matches(&self, line: &RecipientLine) -> bool {
|
|
||||||
self.tag == line.tag
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn connect<E>(
|
|
||||||
&self,
|
|
||||||
callbacks: &mut dyn Callbacks<E>,
|
|
||||||
) -> io::Result<Result<Connection, identity::Error>> {
|
|
||||||
let mut yubikey = match YubiKey::open_by_serial(self.serial) {
|
|
||||||
Ok(yk) => yk,
|
|
||||||
Err(yubikey_piv::Error::NotFound) => {
|
|
||||||
if callbacks
|
|
||||||
.message(&format!(
|
|
||||||
"Please insert YubiKey with serial {}",
|
|
||||||
self.serial
|
|
||||||
))?
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
return Ok(Err(identity::Error::Identity {
|
|
||||||
index: self.identity_index,
|
|
||||||
message: format!("Could not find YubiKey with serial {}", self.serial),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start a 15-second timer waiting for the YubiKey to be inserted
|
|
||||||
let start = SystemTime::now();
|
|
||||||
loop {
|
|
||||||
match YubiKey::open_by_serial(self.serial) {
|
|
||||||
Ok(yubikey) => break yubikey,
|
|
||||||
Err(yubikey_piv::Error::NotFound) => (),
|
|
||||||
Err(_) => {
|
|
||||||
return Ok(Err(identity::Error::Identity {
|
|
||||||
index: self.identity_index,
|
|
||||||
message: format!(
|
|
||||||
"Could not open YubiKey with serial {}",
|
|
||||||
self.serial
|
|
||||||
),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match SystemTime::now().duration_since(start) {
|
|
||||||
Ok(end) if end >= FIFTEEN_SECONDS => {
|
|
||||||
return Ok(Err(identity::Error::Identity {
|
|
||||||
index: self.identity_index,
|
|
||||||
message: format!(
|
|
||||||
"Timed out while waiting for YubiKey with serial {} to be inserted",
|
|
||||||
self.serial
|
|
||||||
),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
_ => sleep(ONE_SECOND),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
return Ok(Err(identity::Error::Identity {
|
|
||||||
index: self.identity_index,
|
|
||||||
message: format!("Could not open YubiKey with serial {}", self.serial),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Read the pubkey from the YubiKey slot and check it still matches.
|
|
||||||
let pk = match Certificate::read(&mut yubikey, SlotId::Retired(self.slot))
|
|
||||||
.ok()
|
|
||||||
.and_then(|cert| match cert.subject_pki() {
|
|
||||||
PublicKeyInfo::EcP256(pubkey) => {
|
|
||||||
Recipient::from_encoded(pubkey).filter(|pk| pk.tag() == self.tag)
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}) {
|
|
||||||
Some(pk) => pk,
|
|
||||||
None => {
|
|
||||||
return Ok(Err(identity::Error::Identity {
|
|
||||||
index: self.identity_index,
|
|
||||||
message: "A YubiKey stub did not match the YubiKey".to_owned(),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let pin = match callbacks.request_secret(&format!(
|
|
||||||
"Enter PIN for YubiKey with serial {}",
|
|
||||||
self.serial
|
|
||||||
))? {
|
|
||||||
Ok(pin) => pin,
|
|
||||||
Err(_) => {
|
|
||||||
return Ok(Err(identity::Error::Identity {
|
|
||||||
index: self.identity_index,
|
|
||||||
message: format!("A PIN is required for YubiKey with serial {}", self.serial),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if yubikey.verify_pin(pin.expose_secret().as_bytes()).is_err() {
|
|
||||||
return Ok(Err(identity::Error::Identity {
|
|
||||||
index: self.identity_index,
|
|
||||||
message: "Invalid YubiKey PIN".to_owned(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Ok(Connection {
|
|
||||||
yubikey,
|
|
||||||
pk,
|
|
||||||
slot: self.slot,
|
|
||||||
tag: self.tag,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct Connection {
|
|
||||||
yubikey: YubiKey,
|
|
||||||
pk: Recipient,
|
|
||||||
slot: RetiredSlotId,
|
|
||||||
tag: [u8; 4],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Connection {
|
|
||||||
pub(crate) fn recipient(&self) -> &Recipient {
|
|
||||||
&self.pk
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn unwrap_file_key(&mut self, line: &RecipientLine) -> Result<FileKey, ()> {
|
|
||||||
assert_eq!(self.tag, line.tag);
|
|
||||||
|
|
||||||
// The YubiKey API for performing scalar multiplication takes the point in its
|
|
||||||
// uncompressed SEC-1 encoding.
|
|
||||||
let shared_secret = match decrypt_data(
|
|
||||||
&mut self.yubikey,
|
|
||||||
line.epk_bytes.decompress().as_bytes(),
|
|
||||||
AlgorithmId::EccP256,
|
|
||||||
SlotId::Retired(self.slot),
|
|
||||||
) {
|
|
||||||
Ok(res) => res,
|
|
||||||
Err(_) => return Err(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut salt = vec![];
|
|
||||||
salt.extend_from_slice(line.epk_bytes.as_bytes());
|
|
||||||
salt.extend_from_slice(self.pk.to_encoded().as_bytes());
|
|
||||||
|
|
||||||
let enc_key = hkdf(&salt, STANZA_KEY_LABEL, shared_secret.as_ref());
|
|
||||||
|
|
||||||
// A failure to decrypt is fatal, because we assume that we won't
|
|
||||||
// encounter 32-bit collisions on the key tag embedded in the header.
|
|
||||||
match aead_decrypt(&enc_key, FILE_KEY_BYTES, &line.encrypted_file_key) {
|
|
||||||
Ok(pt) => Ok(TryInto::<[u8; FILE_KEY_BYTES]>::try_into(&pt[..])
|
|
||||||
.unwrap()
|
|
||||||
.into()),
|
|
||||||
Err(_) => Err(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use yubikey_piv::{key::RetiredSlotId, Serial};
|
|
||||||
|
|
||||||
use super::Stub;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stub_round_trip() {
|
|
||||||
let stub = Stub {
|
|
||||||
serial: Serial::from(42),
|
|
||||||
slot: RetiredSlotId::R1,
|
|
||||||
tag: [7; 4],
|
|
||||||
identity_index: 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
let encoded = stub.to_bytes();
|
|
||||||
assert_eq!(Stub::from_bytes(&encoded, 0), Some(stub));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
use std::env;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
|
||||||
|
const PLUGIN_BIN: &str = env!("CARGO_BIN_EXE_age-plugin-yubikey");
|
||||||
|
|
||||||
|
#[test_with::env(YUBIKEY_SERIAL, YUBIKEY_SLOT)]
|
||||||
|
#[cfg_attr(all(unix, not(target_os = "macos")), test_with::executable(pcscd))]
|
||||||
|
#[test]
|
||||||
|
fn recipient_and_identity_match() {
|
||||||
|
let recipient = Command::new(PLUGIN_BIN)
|
||||||
|
.arg("--list")
|
||||||
|
.arg("--serial")
|
||||||
|
.arg(env::var("YUBIKEY_SERIAL").unwrap())
|
||||||
|
.arg("--slot")
|
||||||
|
.arg(env::var("YUBIKEY_SLOT").unwrap())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(recipient.status.code(), Some(0));
|
||||||
|
|
||||||
|
let identity = Command::new(PLUGIN_BIN)
|
||||||
|
.arg("--identity")
|
||||||
|
.arg("--serial")
|
||||||
|
.arg(env::var("YUBIKEY_SERIAL").unwrap())
|
||||||
|
.arg("--slot")
|
||||||
|
.arg(env::var("YUBIKEY_SLOT").unwrap())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(identity.status.code(), Some(0));
|
||||||
|
|
||||||
|
let recipient_file = String::from_utf8_lossy(&recipient.stdout);
|
||||||
|
let recipient = recipient_file.lines().last().unwrap();
|
||||||
|
let identity = String::from_utf8_lossy(&identity.stdout);
|
||||||
|
assert!(identity.contains(recipient));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_with::executable(rage)]
|
||||||
|
#[test]
|
||||||
|
fn plugin_encrypt() {
|
||||||
|
let enc_file = tempfile::NamedTempFile::new_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||||
|
|
||||||
|
let mut process = Command::new(which::which("rage").unwrap())
|
||||||
|
.arg("-r")
|
||||||
|
.arg("age1yubikey1q2w7u3vpya839jxxuq8g0sedh3d740d4xvn639sqhr95ejj8vu3hyfumptt")
|
||||||
|
.arg("-o")
|
||||||
|
.arg(enc_file.path())
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.env("PATH", Path::new(PLUGIN_BIN).parent().unwrap())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Scope to ensure stdin is closed.
|
||||||
|
{
|
||||||
|
let mut stdin = process.stdin.take().unwrap();
|
||||||
|
stdin.write_all(b"Testing YubiKey encryption").unwrap();
|
||||||
|
stdin.flush().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let status = process.wait().unwrap();
|
||||||
|
assert_eq!(status.code(), Some(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_with::env(YUBIKEY_SERIAL, YUBIKEY_SLOT)]
|
||||||
|
#[test_with::executable(rage)]
|
||||||
|
#[cfg_attr(all(unix, not(target_os = "macos")), test_with::executable(pcscd))]
|
||||||
|
#[test]
|
||||||
|
fn plugin_decrypt() {
|
||||||
|
let mut identity_file = tempfile::NamedTempFile::new_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||||
|
let enc_file = tempfile::NamedTempFile::new_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||||
|
let plaintext = "Testing YubiKey encryption";
|
||||||
|
|
||||||
|
// Write an identity file corresponding to this YubiKey slot.
|
||||||
|
let identity = Command::new(PLUGIN_BIN)
|
||||||
|
.arg("--identity")
|
||||||
|
.arg("--serial")
|
||||||
|
.arg(env::var("YUBIKEY_SERIAL").unwrap())
|
||||||
|
.arg("--slot")
|
||||||
|
.arg(env::var("YUBIKEY_SLOT").unwrap())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(identity.status.code(), Some(0));
|
||||||
|
identity_file.write_all(&identity.stdout).unwrap();
|
||||||
|
identity_file.flush().unwrap();
|
||||||
|
|
||||||
|
// Encrypt to the YubiKey slot.
|
||||||
|
let mut enc_process = Command::new(which::which("rage").unwrap())
|
||||||
|
.arg("-e")
|
||||||
|
.arg("-i")
|
||||||
|
.arg(identity_file.path())
|
||||||
|
.arg("-o")
|
||||||
|
.arg(enc_file.path())
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.env("PATH", Path::new(PLUGIN_BIN).parent().unwrap())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Scope to ensure stdin is closed.
|
||||||
|
{
|
||||||
|
let mut stdin = enc_process.stdin.take().unwrap();
|
||||||
|
stdin.write_all(plaintext.as_bytes()).unwrap();
|
||||||
|
stdin.flush().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let enc_status = enc_process.wait().unwrap();
|
||||||
|
assert_eq!(enc_status.code(), Some(0));
|
||||||
|
|
||||||
|
// Decrypt with the YubiKey.
|
||||||
|
let dec_process = Command::new(which::which("rage").unwrap())
|
||||||
|
.arg("-d")
|
||||||
|
.arg("-i")
|
||||||
|
.arg(identity_file.path())
|
||||||
|
.arg(enc_file.path())
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.env("PATH", Path::new(PLUGIN_BIN).parent().unwrap())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let stderr = String::from_utf8_lossy(&dec_process.stderr);
|
||||||
|
if !stderr.is_empty() {
|
||||||
|
assert!(stderr.contains("age-plugin-yubikey"));
|
||||||
|
assert!(stderr.ends_with("...\n"));
|
||||||
|
}
|
||||||
|
assert_eq!(String::from_utf8_lossy(&dec_process.stdout), plaintext);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user