├── .clang-format ├── .clang-tidy ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE │ └── pull_request.md ├── actions │ └── ci │ │ ├── Dockerfile │ │ ├── action.yml │ │ └── entrypoint.sh └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTORS.md ├── INSTALL.md ├── INTERNALS.md ├── LICENSE ├── Makefile ├── README.md ├── SECURITY.md ├── include ├── authenticator.h ├── cryptography.h ├── enrol.h ├── enumerate.h ├── exit.h ├── files.h ├── generate.h ├── help.h ├── invocation.h ├── memory.h ├── serialization.h ├── serialization │ └── v1.h └── serialization_types.h ├── man ├── 1 │ ├── khefin-ssh-askpass.m4 │ └── khefin.m4 └── 8 │ ├── khefin-add-luks-key.m4 │ └── khefin-cryptsetup-keyscript.m4 ├── metadata.make ├── scripts ├── add-luks-key.m4 ├── bash-completion.m4 ├── initramfs-tools │ ├── hook.m4 │ └── keyscript.m4 ├── mkinitcpio │ ├── install.m4 │ └── run.m4 └── ssh-askpass.m4 ├── src ├── authenticator.c ├── cryptography.c ├── enrol.c ├── enumerate.c ├── files.c ├── generate.c ├── help.c ├── invocation.c ├── main.c ├── memory.c ├── serialization.c └── serialization │ └── v1.c └── variables.m4 /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: LLVM 2 | UseTab: ForIndentation 3 | IndentCaseLabels: false 4 | IndentWidth: 4 5 | TabWidth: 4 6 | BreakBeforeBraces: Attach -------------------------------------------------------------------------------- /.clang-tidy: -------------------------------------------------------------------------------- 1 | Checks: 'clang-diagnostic-*,clang-analyzer-*,readability-*,bugprone-*,misc-*,optin.portability.UnixAPI,google-runtime-int,-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,llvm-header-guard' 2 | WarningsAsErrors: '*' 3 | HeaderFilterRegex: '.*' 4 | FormatStyle: 'file' 5 | CheckOptions: 6 | - key: google-runtime-int.TypeSufix 7 | value: '_t' 8 | - key: bugprone-unused-return-value.CheckedFunctions 9 | value: 'malloc;fgets;sodium_init;crypto_pwhash;crypto_secretbox_open_easy;crypto_secretbox_easy;cbor_serialize_alloc;cbor_load;fido_assert_allow_cred;fido_assert_set_clientdata_hash;fido_assert_set_extensions;fido_assert_set_hmac_salt;fido_assert_set_rp;fido_assert_set_up;fido_cred_set_clientdata_hash;fido_cred_set_extensions;fido_cred_set_rp;fido_cred_set_type;fido_cred_set_user;fido_dev_open;fido_dev_close;fido_dev_get_assert;fido_dev_get_cbor_info;fido_dev_info_manifest;fido_dev_make_cred' 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report a bug or unexpected behavior 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | _[A clear and concise description of what the bug is.]_ 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Run `khefin ...` _[please include ALL parameters]_ 16 | 2. Type in correct passphrase 17 | 3. See error "..." 18 | 19 | **Expected behavior** 20 | _[A clear and concise description of what you expected to happen.]_ 21 | 22 | **Environment:** 23 | - Operating system: _[e.g. Arch Linux]_ 24 | - Version: _[e.g. 1.0.0-release; find it by running `khefin version`]_ 25 | - Authenticator make and model: _[e.g. blue Yubico Security Key version 2]_ 26 | 27 | **Additional context** 28 | Add any other context about the problem here. 29 | 30 | If the bug requires a particular keyfile to be reproduced, please **run enrol to generate a new keyfile** with the passphrase `hunter2` (or, if required, a different passphrase that you include in the bug report). Please **do not attach a keyfile used for anything other than this bug report**. 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | _[A clear and concise description of what the problem is. Ex. I'm always frustrated when ...]_ 12 | 13 | **Describe the solution you'd like** 14 | _[A clear and concise description of what you want to happen.]_ 15 | 16 | **Describe alternatives you've considered** 17 | _[A clear and concise description of any alternative solutions or features you've considered.]_ 18 | 19 | **Additional context** 20 | _[Add any other context about the feature request here.]_ 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/pull_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Pull request 3 | about: Propose changes to this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Use this checklist to prepare your pull request for merging. Pull requests that do not have all of these properties will need to be revised before they can be merged. 11 | 12 | - [ ] Issue number referenced in commit message(s) 13 | 14 | - [ ] Changes squashed to a single commit, unless logically distinct (use [`Co-authored-by`](https://help.github.com/en/github/committing-changes-to-your-project/creating-a-commit-with-multiple-authors) if necessary) 15 | 16 | - [ ] No merge commits 17 | 18 | - [ ] `APPVERSION` updated in `metadata.make`, in accordance with [semantic versioning](https://semver.org/) 19 | 20 | - [ ] `make format` has been run to conform to code style 21 | 22 | - [ ] `make lint` finishes with no non-suppressed warnings (please do not add new suppressions without flagging this) 23 | 24 | - [ ] `make shellcheck` finishes with no non-suppressed warnings (please do not add new suppressions without flagging this) 25 | 26 | - [ ] Checked that `make`, `make release`, `make install` and `make clean` all work as expected 27 | 28 | - [ ] Checked that `make clean; make` compiles successfully with no warnings or errors 29 | 30 | - [ ] `CONTRIBUTORS.md` and `CHANGELOG.md` are updated (if required) 31 | 32 | - [ ] `README.md` is updated (if required) 33 | 34 | - [ ] `src/help.c`, `docs/bash-completion.m4` and `docs/manpage.m4` are updated (if required) 35 | 36 | - [ ] You accept that your contributions will be _irrevocably_ released under the license specified in `LICENSE` 37 | -------------------------------------------------------------------------------- /.github/actions/ci/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM teeks99/clang-ubuntu:10 2 | 3 | RUN apt-get update && \ 4 | apt-get -y install software-properties-common 5 | RUN apt-add-repository ppa:yubico/stable 6 | RUN apt-get update && \ 7 | apt-get -y install \ 8 | pkg-config \ 9 | curl \ 10 | git \ 11 | m4 \ 12 | shellcheck \ 13 | clang-tidy-10 \ 14 | libfido2-dev \ 15 | libssl-dev \ 16 | libcbor-dev \ 17 | libsodium-dev 18 | # work around https://bugs.launchpad.net/ubuntu/+source/libcbor/+bug/1858835 19 | RUN curl -o /usr/lib/x86_64-linux-gnu/pkgconfig/libcbor.pc https://gist.githubusercontent.com/mjec/ecc2f4421a6d3f2d798bedc23c5665b7/raw/ac817fd599285e9e1a483f72b1801ebb750213a6/libcbor.pc 20 | 21 | RUN ln -s /usr/bin/clang-10 /usr/bin/clang && \ 22 | ln -s /usr/bin/clang-format-10 /usr/bin/clang-format && \ 23 | ln -s /usr/bin/clang-tidy-10 /usr/bin/clang-tidy 24 | 25 | COPY entrypoint.sh /entrypoint.sh 26 | 27 | ENTRYPOINT ["/entrypoint.sh"] 28 | -------------------------------------------------------------------------------- /.github/actions/ci/action.yml: -------------------------------------------------------------------------------- 1 | name: 'CI' 2 | description: 'CI for khefin' 3 | inputs: 4 | what: 5 | description: 'What to run (format, lint, shellcheck, clang or gcc)' 6 | required: true 7 | runs: 8 | using: 'docker' 9 | image: 'Dockerfile' 10 | args: 11 | - ${{ inputs.what }} 12 | branding: 13 | icon: 'layers' 14 | color: 'purple' -------------------------------------------------------------------------------- /.github/actions/ci/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | case "$1" in 4 | "format") 5 | make check-format 6 | ;; 7 | "lint") 8 | make check-lint 9 | ;; 10 | "shellcheck") 11 | make shellcheck 12 | ;; 13 | "clang") 14 | make all -j 15 | ;; 16 | "gcc") 17 | CC=gcc make all -j 18 | ;; 19 | *) 20 | echo "Unrecognized command" 21 | exit 1 22 | ;; 23 | esac 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Continuous integration 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | tags: 8 | - v* 9 | pull_request: 10 | branches: 11 | - main 12 | workflow_dispatch: 13 | 14 | jobs: 15 | format: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v2 20 | with: 21 | persist-credentials: false 22 | - name: Run make format 23 | uses: ./.github/actions/ci 24 | with: 25 | what: format 26 | lint: 27 | runs-on: ubuntu-latest 28 | steps: 29 | - name: Checkout code 30 | uses: actions/checkout@v2 31 | with: 32 | persist-credentials: false 33 | - name: Run make lint 34 | uses: ./.github/actions/ci 35 | with: 36 | what: lint 37 | shellcheck: 38 | runs-on: ubuntu-latest 39 | steps: 40 | - name: Checkout code 41 | uses: actions/checkout@v2 42 | with: 43 | persist-credentials: false 44 | - name: Run make shellcheck 45 | uses: ./.github/actions/ci 46 | with: 47 | what: shellcheck 48 | build-clang: 49 | runs-on: ubuntu-latest 50 | steps: 51 | - name: Checkout code 52 | uses: actions/checkout@v2 53 | with: 54 | persist-credentials: false 55 | - name: Build with clang 56 | uses: ./.github/actions/ci 57 | with: 58 | what: clang 59 | build-gcc: 60 | runs-on: ubuntu-latest 61 | steps: 62 | - name: Checkout code 63 | uses: actions/checkout@v2 64 | with: 65 | persist-credentials: false 66 | - name: Build with gcc 67 | uses: ./.github/actions/ci 68 | with: 69 | what: gcc 70 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | 54 | # Compiled assets 55 | dist/** -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## Next version (unreleased) 4 | 5 | _These changes are on the branch `main`, but not yet in a versioned release._ 6 | 7 | ## Version 0.6.1 8 | 9 | * Fix PIN support for disk encryption scripts (issue #31) 10 | * Change initcpio scripts to use ramfs instead of encrypted loopback device 11 | * Add --passphrase-file option 12 | * Stop dropping privileges when run under sudo (issue #35) 13 | * Bump warrant canary to 17 January 2021 14 | 15 | ## Version 0.6.0 16 | 17 | * Add PIN support (issue #28) 18 | * Truncate newline from the end of passphrase provided non-interactively on STDIN 19 | 20 | ## Version 0.5.1 21 | 22 | * Bumped warrant canary to 30 October 2020 23 | * Fix misleading section of the manual relating to reading passphrase on STDIN (issue #29) 24 | * Add missing arguments in bash completion script 25 | * `enumerate` prints devices even if they are not FIDO2-compatible (issue #23) 26 | 27 | ## Version 0.5.0 28 | 29 | * Add initramfs-tools scripts (issue #19) 30 | * Rename `fido2-hmac-secret` -> `khefin` 31 | * Add `help` target to Makefile and make it the default target 32 | * Prompt for authenticator during boot if not present (issue #21) 33 | * Debug builds use address sanitizer 34 | * Fix memory leak in `enrol_device` (issue #18) 35 | 36 | ## Version 0.4.3 37 | 38 | * Add ssh-askpass implementation 39 | 40 | ## Version 0.4.2 41 | 42 | * Add --mixin parameter (issue #4) 43 | 44 | ## Version 0.4.1 45 | 46 | * Refactor code to make it possible to compile with GCC without warnings 47 | * Update CI to run make against gcc as well as clang 48 | 49 | ## Version 0.4.0 50 | 51 | * Make passphrase prompt output on STDERR instead of STDOUT 52 | * Add fido2-hmac-secret-add-luks-key script (issue #1) 53 | * Add setcap cap_ipc_lock+ep in install target, SETCAP_BINARY install flag (defaults to on), and remove setuid (issue #3) 54 | * Change ALWAYS_SILENCE_MEMORY_LOCK_ERRORS to WARN_ON_MEMORY_LOCK_ERRORS and have it default to on 55 | * Remove FIDO2_HMAC_SECRET_SILENCE_MEMLOCK_ERRORS environment variable 56 | * Move bash-completion script from docs/ to scripts/ 57 | * Do not generate bash-completion script by default 58 | * Include reasons for setuid root in README, and add ALWAYS_SILENCE_MEMORY_LOCK_ERRORS compile option (issue #3) 59 | * Permit passphrase to be supplied on STDIN, if not a tty (issue #2) 60 | 61 | ## Version 0.3.0 62 | 63 | * Add mkinitcpio hooks for using this with encrypted root device on Arch Linux 64 | * Change "password" to "passphrase" everywhere 65 | * Change `get_secret_consuming_authenticator_params` to stop consuming params, thus avoiding double-free 66 | * Fix bug where providing an invalid subcommand did not print usage and exit with EXIT_BAD_INVOCATION 67 | * Improve bash completion, removing invalid options for `generate` 68 | 69 | ## Version 0.2.0 70 | 71 | * Remove use of device vendor & product ID, replace with AAGUID 72 | * Fix double free bugs when the wrong authenticator device is used 73 | * Fix reference to algorithm as uint32 in serialzie.c 74 | * Add escaping for `-` in manpage.m4 75 | * Convert spaces to tabs in bash-completion.m4 76 | 77 | ## Version 0.1.0 78 | 79 | * Initial release. 80 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | khefin@mjec.net. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | * [Michael Cordover](https://github.com/mjec) - original author 2 | * [Maryse47](https://github.com/Maryse47) - security suggestions and contributions 3 | * [Mateusz Gozdek](https://github.com/invidian) - documentation fixes 4 | * [ZenithalHourlyRate](https://github.com/ZenithalHourlyRate) - scripts with PIN support -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | ## Dependencies 4 | 5 | Before building or running this tool, you'll need the following dependencies installed: 6 | 7 | * [libfido2](https://developers.yubico.com/libfido2/) and its dependency libcrypto from OpenSSL 8 | * [libcbor](https://libcbor.readthedocs.io/en/v0.5.0/) - also a dependency of libfido2 9 | * [libsodium](https://download.libsodium.org/doc/) 10 | 11 | At the moment I believe this tool is linux-only; issue reports or pull requests to improve portability are gratefully accepted. 12 | 13 | To build this tool, you'll also need: 14 | 15 | * [clang](https://clang.llvm.org/) or [gcc](https://gcc.gnu.org/) 16 | * [m4](https://www.gnu.org/software/m4/m4.html) 17 | * [make](https://www.gnu.org/software/make/) 18 | * [pkg-config](https://www.freedesktop.org/wiki/Software/pkg-config/) 19 | 20 | ## Building 21 | 22 | `make release` is the main compile target. 23 | 24 | If you want a [bash-completion](https://github.com/scop/bash-completion) script, add the `bash-completion` target. 25 | 26 | Run `make help` for a list of other targets. 27 | 28 | ### Build flags 29 | 30 | | Flag | Type | Default | Meaning | 31 | |------|------|---------|---------| 32 | | `LONGEST_VALID_PASSPHRASE` | integer | 1024 | length after which passphrases are truncated | 33 | | `WARN_ON_MEMORY_LOCK_ERRORS` | boolean | 1 | if `0`, this will disable warnings when memory cannot be locked | 34 | | `SETCAP_BINARY` | boolean | 1 | if `0`, then `make install` will not attempt to add `CAP_IPC_LOCK` to the installed binary | 35 | | `DEBUG` | N/A | unset | if set to any value, this will enable debug mode (enabling core dumps, assertions and symbols) | 36 | 37 | Standard makefile variables (`CC`, `CFLAGS`, `LDFLAGS`, `DESTDIR`, `PREFIX`) are respected. 38 | -------------------------------------------------------------------------------- /INTERNALS.md: -------------------------------------------------------------------------------- 1 | # Internals 2 | 3 | ## How this works 4 | 5 | The authenticator has a credential-scoped secret which is used to calculate the HMAC-SHA256 over some data (the "salt"). 6 | 7 | During the `enrol` step, we create a file ("encrypted keyfile") containing a randomly-generated salt, a credential ID (specified by the authenticator), and a randomly generated relying party ID (a credential on the authenticator is scoped to a relying party ID, which is specified when creating the credential). This data is encrypted with the passphrase you specify (using libsodium), and saved to disk. 8 | 9 | The `generate` command decrypts this data, sends it to the authenticator, and prints the result. This results in the same value being returned every time; but that value cannot be obtained without both the decrypted keyfile (which requires your passphrase) and the authenticator device. 10 | 11 | ## Encrypted keyfile 12 | 13 | This is a CBOR-encoded array with the following elements: 14 | 15 | | Field | Name | Type | Notes | 16 | |:-----:|-----------------|-------------------------|-------------------------------| 17 | | 0 | version | unsigned 8 bit integer | Schama version; always `1` | 18 | | 1 | device AAGUID | definite bytestring | Device make & model, or empty | 19 | | 2 | passphrase salt | definite bytestring | See `crypto_pwhash` | 20 | | 3 | opslimit | unsigned 64 bit integer | See `crypto_pwhash` | 21 | | 4 | memlimit | unsigned 64 bit integer | See `crypto_pwhash` | 22 | | 5 | algorithm | unsigned 16 bit integer | See `crypto_pwhash` | 23 | | 6 | nonce | definite bytestring | See `crypto_secretbox_easy` | 24 | | 7 | encrypted data | definite bytestring | | 25 | 26 | Device AAGUID will be empty if and only if the `enrol` step is done with `--obfuscate-device-info`. If it's empty, every hmac-secret-supporting device will be tried during the `generate` step. If it's not empty, only devices with a matching AAGUID are returned. 27 | 28 | Any modification of any of the fields (except version, device vendor and device product) will irrecoverably render the key unusable. 29 | 30 | The user will be prompted for a passphrase, which is run through libsodium's `crypto_pwhash`, with parameters from fields 3, 4, 5 and 6 to give a key. 31 | 32 | That key, combined with the nonce in field 7, is used to decrypt the encrypted data in field 8 with libsodium's `crypto_secretbox_easy`. 33 | 34 | Once the encrypted data section is decrypted, it contains a CBOR-encoded array with the following elements: 35 | 36 | | Field | Name | Type | Notes | 37 | |:-----:|------------------|------------------------|-------------------------------------------------------| 38 | | 0 | version | unsigned 8 bit integer | Schama version; always `1` | 39 | | 1 | relying party ID | definite UTF-8 string | random subdomain of `.v1.fido2-hmac-secret.localhost` | 40 | | 2 | credential ID | definite bytestring | | 41 | | 3 | HMAC salt | definite bytestring | | 42 | 43 | These parameters (other than version) are then passed to the FIDO2 authenticator, which returns an [HMAC-SHA-256 over the salt](https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#sctn-hmac-secret-extension). The key for that HMAC is available only to the authenticator, and is associated with the credential ID and relying party ID. This means that all three fields are essential, as is they physical authenticator device. 44 | 45 | In fact it would be sufficient for cryptographic security of the key material to store hide the HMAC salt, which provides at least 32 bytes (and normally 64 bytes or 512 bits), of entropy. Hiding the relying party ID and credential ID however costs us nothing, and adds some additional protection. 46 | 47 | At the very least, the credential ID offers an additional [100 bits of entropy](https://www.w3.org/TR/webauthn/#credential-id). Although the credential ID is opaque, it may contain the key material enrypted in a manner that only the FIDO2 authenticator can decrypt. In this case, even advanced tampering with that device would not reveal enough information to even begin an offline attack, absent the cleartext credential ID. 48 | 49 | The relying party ID contained in this data is in fact only used as part of that ID, and it is always a 32 character string composed of characters in the range [a-z0-7], for a total of 160 bits of entropy. The aim here is to ensure that any protections in the authenticator against cross-origin key use detection are available. I doubt any key has such protection, but again it costs us nothing. 50 | 51 | 52 | ## Memory locking 53 | 54 | To avoid secrets accidentally being written to disk (including swap space), the binary will disable core dumps and lock all allocated memory. The success of this depends on your locally-configured limits (and in particular `RLIMIT_MEMLOCK`) and the capabilities of the binary. To ensure success, by default the binary is given the `CAP_IPC_LOCK` capability during `make install`. This bypasses `RLIMIT_MEMLOCK`. 55 | 56 | If for any reason core dumps cannot be disabled or memory cannot be locked, a warning will be generated, unless the binary was compiled with `WARN_ON_MEMORY_LOCK_ERRORS=0`. 57 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # khefin Makefile 2 | # 3 | # Comments beginning with #: and immediately preceding a target are printed by the `help` target. 4 | 5 | 6 | ################################################################################ 7 | # DEFINITIONS # 8 | ################################################################################ 9 | 10 | # Metadata 11 | METAPATH=$(abspath ./metadata.make) 12 | -include $(METAPATH) 13 | APPDATE=$(shell date -d "$$(stat --printf "%y" $(METAPATH))" "+%d %B %Y") 14 | LONGEST_VALID_PASSPHRASE=1024 15 | WARN_ON_MEMORY_LOCK_ERRORS=1 16 | SETCAP_BINARY=1 17 | 18 | # Paths 19 | ifeq ($(origin PREFIX),undefined) 20 | PREFIX=/usr/local 21 | endif 22 | SRCDIR=$(abspath ./src) 23 | INCDIR=$(abspath ./include) 24 | MANDIR=$(abspath ./man) 25 | SCRIPTDIR=$(abspath ./scripts) 26 | DISTDIR=$(abspath ./dist) 27 | BINPATH=$(DISTDIR)/bin/$(APPNAME) 28 | M4VARSPATH=$(abspath ./variables.m4) 29 | 30 | # Source files 31 | SRCS=$(shell find $(SRCDIR) -name '*.c') 32 | HEADERS=$(shell find $(INCDIR) -name '*.h') 33 | 34 | # Derived filenames 35 | OBJS=$(SRCS:.c=.o) 36 | PREREQUISITES=$(SRCS:.c=.d) 37 | 38 | # Compiler options 39 | ifeq ($(origin CC),default) 40 | CC=clang 41 | endif 42 | WARNINGFLAGS=-Wall \ 43 | -Wshadow \ 44 | -Wwrite-strings \ 45 | -Wmissing-prototypes \ 46 | -Wimplicit-fallthrough \ 47 | -pedantic \ 48 | -fstack-protector-all \ 49 | -fno-strict-aliasing 50 | DEFINEFLAGS=-DAPPNAME=\"$(APPNAME)\" \ 51 | -DAPPVERSION=\"$(APPVERSION)\" \ 52 | -DLONGEST_VALID_PASSPHRASE=$(LONGEST_VALID_PASSPHRASE) \ 53 | -DWARN_ON_MEMORY_LOCK_ERRORS=$(WARN_ON_MEMORY_LOCK_ERRORS) 54 | INCLUDEFLAGS=$(shell pkg-config --cflags libfido2 libcbor libsodium) -iquote $(INCDIR) 55 | LDLIBS=$(shell pkg-config --libs libfido2 libcbor libsodium) 56 | 57 | # Derived compiler options 58 | CFLAGS:=$(INCLUDEFLAGS) $(DEFINEFLAGS) $(WARNINGFLAGS) $(CFLAGS) 59 | LDFLAGS:=$(WARNINGFLAGS) $(DEFINEFLAGS) $(LDFLAGS) 60 | 61 | # m4 preprocessor options 62 | M4FLAGS=-Dm4_APPNAME="$(APPNAME)" \ 63 | -Dm4_APPVERSION="$(APPVERSION)" \ 64 | -Dm4_APPDATE="$(APPDATE)" \ 65 | -Dm4_LONGEST_VALID_PASSPHRASE=$(LONGEST_VALID_PASSPHRASE) \ 66 | -Dm4_WARN_ON_MEMORY_LOCK_ERRORS=$(WARN_ON_MEMORY_LOCK_ERRORS) \ 67 | -Dm4_INSTALL_PREFIX=$(PREFIX) \ 68 | --prefix-builtins \ 69 | $(M4VARSPATH) 70 | 71 | 72 | ################################################################################ 73 | # COMMON TARGETS # 74 | ################################################################################ 75 | 76 | .PHONY: help 77 | #: Print this list of targets and their descriptions 78 | help: 79 | @grep -B1 -E "^[a-zA-Z0-9_-]+\:([^\=]|$$)" Makefile \ 80 | | grep -v -- -- \ 81 | | sed 'N;s/\n/###/' \ 82 | | sed -n 's/^#: \(.*\)###\([^:]*\):.*/\2###\1/p' \ 83 | | column -t -s '###' 84 | 85 | 86 | check_dep_pkgconfig = @printf "%-20s %-10s " "$(1)" "$(2)"; if pkg-config $(1) > /dev/null 2>&1; then printf "OK\n"; else printf "not found!\n"; fi 87 | check_dep_command = @printf "%-20s %-10s " "$(1)" "$(2)"; if command -v $(3) > /dev/null; then printf "OK\n"; else printf "not found!\n"; fi 88 | 89 | .PHONY: check 90 | #: Check for the presence of dependencies 91 | check: 92 | $(call check_dep_pkgconfig,libfido2,required) 93 | $(call check_dep_pkgconfig,libcbor,required) 94 | $(call check_dep_pkgconfig,libsodium,required) 95 | $(call check_dep_command,bash,optional,bash) 96 | $(call check_dep_command,ssh-agent,optional,ssh-agent) 97 | $(call check_dep_command,mkinitcpio,optional,mkinitcpio) 98 | $(call check_dep_command,initramfs-tools,optional,mkinitramfs) 99 | 100 | # Release build targets 101 | .PHONY: all 102 | #: Alias for release manpages bash-completion ssh-askpass 103 | all: release manpages bash-completion ssh-askpass 104 | 105 | .PHONY: release 106 | #: Build an optimized and stripped binary 107 | release: CFLAGS:=-O3 $(CFLAGS) 108 | release: LDFLAGS:=-O3 -s $(LDFLAGS) 109 | release: $(BINPATH) 110 | 111 | .PHONY: install 112 | #: Install built files to $DESTDIR 113 | install: release manpages 114 | install -g 0 -o 0 -p -m 0755 -D $(DISTDIR)/bin/$(APPNAME) $(DESTDIR)$(PREFIX)/bin/$(APPNAME) 115 | if [ "$(SETCAP_BINARY)" -ne 0 ]; then setcap cap_ipc_lock+ep $(DESTDIR)$(PREFIX)/bin/$(APPNAME); fi 116 | install -g 0 -o 0 -p -m 0644 -D $(DISTDIR)/share/man/man1/$(APPNAME).1.gz $(DESTDIR)$(PREFIX)/share/man/man1/$(APPNAME).1.gz 117 | if [ -f $(DISTDIR)/share/bash-completion/completions/$(APPNAME) ]; then install -g 0 -o 0 -p -m 0644 -D $(DISTDIR)/share/bash-completion/completions/$(APPNAME) $(DESTDIR)$(PREFIX)/share/bash-completion/completions/$(APPNAME); fi 118 | if [ -f $(DISTDIR)/bin/$(APPNAME)-add-luks-key ]; then install -g 0 -o 0 -p -m 0755 -D $(DISTDIR)/bin/$(APPNAME)-add-luks-key $(DESTDIR)$(PREFIX)/bin/$(APPNAME)-add-luks-key; fi 119 | if [ -f $(DISTDIR)/bin/$(APPNAME)-add-luks-key ] && [ -f $(DISTDIR)/share/man/man8/$(APPNAME)-add-luks-key.8.gz ]; then install -g 0 -o 0 -p -m 0644 -D $(DISTDIR)/share/man/man8/$(APPNAME)-add-luks-key.8.gz $(DESTDIR)$(PREFIX)/share/man/man8/$(APPNAME)-add-luks-key.8.gz; fi 120 | if [ -f $(DISTDIR)/bin/$(APPNAME)-ssh-askpass ]; then install -g 0 -o 0 -p -m 0755 -D $(DISTDIR)/bin/$(APPNAME)-ssh-askpass $(DESTDIR)$(PREFIX)/bin/$(APPNAME)-ssh-askpass; fi 121 | if [ -f $(DISTDIR)/bin/$(APPNAME)-ssh-askpass ] && [ -f $(DISTDIR)/share/man/man1/$(APPNAME)-ssh-askpass.1.gz ]; then install -g 0 -o 0 -p -m 0644 -D $(DISTDIR)/share/man/man1/$(APPNAME)-ssh-askpass.1.gz $(DESTDIR)$(PREFIX)/share/man/man1/$(APPNAME)-ssh-askpass.1.gz; fi 122 | if [ -f $(DISTDIR)/lib/initcpio/install/$(APPNAME) ]; then install -g 0 -o 0 -p -m 0644 -D $(DISTDIR)/lib/initcpio/install/$(APPNAME) $(DESTDIR)$(PREFIX)/lib/initcpio/install/$(APPNAME); fi 123 | if [ -f $(DISTDIR)/lib/initcpio/hooks/$(APPNAME) ]; then install -g 0 -o 0 -p -m 0644 -D $(DISTDIR)/lib/initcpio/hooks/$(APPNAME) $(DESTDIR)$(PREFIX)/lib/initcpio/hooks/$(APPNAME); fi 124 | if [ -f $(DISTDIR)/etc/initramfs-tools/hooks/crypt$(APPNAME) ]; then install -g 0 -o 0 -p -m 0755 -D $(DISTDIR)/etc/initramfs-tools/hooks/crypt$(APPNAME) $(DESTDIR)/etc/initramfs-tools/hooks/crypt$(APPNAME); fi 125 | if [ -f $(DISTDIR)/lib/$(APPNAME)/cryptsetup-keyscript ]; then install -g 0 -o 0 -p -m 0755 -D $(DISTDIR)/lib/$(APPNAME)/cryptsetup-keyscript $(DESTDIR)$(PREFIX)/lib/$(APPNAME)/cryptsetup-keyscript; fi 126 | if [ -f $(DISTDIR)/lib/$(APPNAME)/cryptsetup-keyscript ] && [ -f $(DISTDIR)/share/man/man8/$(APPNAME)-cryptsetup-keyscript.8.gz ]; then install -g 0 -o 0 -p -m 0644 -D $(DISTDIR)/share/man/man8/$(APPNAME)-cryptsetup-keyscript.8.gz $(DESTDIR)$(PREFIX)/share/man/man8/$(APPNAME)-cryptsetup-keyscript.8.gz; fi 127 | 128 | .PHONY: uninstall 129 | #: Remove files from $DESTDIR 130 | uninstall: 131 | $(RM) $(DESTDIR)$(PREFIX)/share/man/man8/$(APPNAME)-cryptsetup-keyscript.8.gz 132 | $(RM) $(DESTDIR)$(PREFIX)/lib/$(APPNAME)/cryptsetup-keyscript 133 | $(RM) $(DESTDIR)/etc/initramfs-tools/hooks/crypt$(APPNAME) 134 | $(RM) $(DESTDIR)$(PREFIX)/lib/initcpio/hooks/$(APPNAME) 135 | $(RM) $(DESTDIR)$(PREFIX)/lib/initcpio/install/$(APPNAME) 136 | $(RM) $(DESTDIR)$(PREFIX)/share/man/man1/$(APPNAME)-ssh-askpass.1.gz 137 | $(RM) $(DESTDIR)$(PREFIX)/bin/$(APPNAME)-ssh-askpass 138 | $(RM) $(DESTDIR)$(PREFIX)/share/man/man8/$(APPNAME)-add-luks-key.8.gz 139 | $(RM) $(DESTDIR)$(PREFIX)/bin/$(APPNAME)-add-luks-key 140 | $(RM) $(DESTDIR)$(PREFIX)/share/bash-completion/completions/$(APPNAME) 141 | $(RM) $(DESTDIR)$(PREFIX)/share/man/man1/$(APPNAME).1.gz 142 | $(RM) $(DESTDIR)$(PREFIX)/bin/$(APPNAME) 143 | 144 | .PHONY: clean 145 | #: Delete built files 146 | clean: cleandep cleanobj cleandist 147 | 148 | .PHONY: debug 149 | #: Build an unoptimized binary with debug symbols 150 | debug: CFLAGS:=-fsanitize=address -fno-omit-frame-pointer -g -DDEBUG $(CFLAGS) 151 | debug: LDFLAGS:=-fsanitize=address -fno-omit-frame-pointer -g -DDEBUG $(LDFLAGS) 152 | debug: $(BINPATH) 153 | 154 | 155 | ################################################################################ 156 | # MAN PAGES # 157 | ################################################################################ 158 | 159 | .PHONY: manpages 160 | #: Build man pages 161 | manpages: $(DISTDIR)/share/man/man1/$(APPNAME).1.gz $(DISTDIR)/share/man/man1/$(APPNAME)-ssh-askpass.1.gz $(DISTDIR)/share/man/man8/$(APPNAME)-add-luks-key.8.gz $(DISTDIR)/share/man/man8/$(APPNAME)-cryptsetup-keyscript.8.gz 162 | 163 | $(DISTDIR)/share/man/man1/%.1.gz: $(DISTDIR)/share/man/man1/%.1 164 | gzip -f $< 165 | 166 | $(DISTDIR)/share/man/man8/%.8.gz: $(DISTDIR)/share/man/man8/%.8 167 | gzip -f $< 168 | 169 | .INTERMEDIATE: $(DISTDIR)/share/man/man1/%.1 170 | $(DISTDIR)/share/man/man1/%.1: $(MANDIR)/1/%.m4 $(METAPATH) $(M4VARSPATH) 171 | mkdir -p $(DISTDIR)/share/man/man1 172 | m4 $(M4FLAGS) $< > $@ 173 | 174 | .INTERMEDIATE: $(DISTDIR)/share/man/man8/%.8 175 | $(DISTDIR)/share/man/man8/%.8: $(MANDIR)/8/%.m4 $(METAPATH) $(M4VARSPATH) 176 | mkdir -p $(DISTDIR)/share/man/man8 177 | m4 $(M4FLAGS) $< > $@ 178 | 179 | 180 | ################################################################################ 181 | # COMPLETION SCRIPTS # 182 | ################################################################################ 183 | 184 | .PHONY: bash-completion 185 | #: Build bash completion scripts 186 | bash-completion: $(DISTDIR)/share/bash-completion/completions/$(APPNAME) 187 | 188 | shellcheck: $(DISTDIR)/share/bash-completion/completions/$(APPNAME) 189 | 190 | $(DISTDIR)/share/bash-completion/completions/$(APPNAME): $(SCRIPTDIR)/bash-completion.m4 $(METAPATH) $(M4VARSPATH) 191 | mkdir -p $(DISTDIR)/share/bash-completion/completions 192 | m4 $(M4FLAGS) $(SCRIPTDIR)/bash-completion.m4 > $@ 193 | 194 | 195 | ################################################################################ 196 | # DISK ENCRYPTION # 197 | ################################################################################ 198 | 199 | .PHONY: add-luks-key 200 | add-luks-key: $(DISTDIR)/bin/$(APPNAME)-add-luks-key 201 | 202 | shellcheck: $(DISTDIR)/bin/$(APPNAME)-add-luks-key 203 | $(DISTDIR)/bin/$(APPNAME)-add-luks-key: $(SCRIPTDIR)/add-luks-key.m4 $(M4VARSPATH) 204 | mkdir -p $(DISTDIR)/bin 205 | m4 $(M4FLAGS) $< > $@ 206 | 207 | 208 | .PHONY: mkinitcpio 209 | #: Build disk encryption scripts for use with mkinitcpio 210 | mkinitcpio: add-luks-key $(DISTDIR)/lib/initcpio/install/$(APPNAME) $(DISTDIR)/lib/initcpio/hooks/$(APPNAME) 211 | 212 | shellcheck: $(DISTDIR)/lib/initcpio/install/$(APPNAME) $(DISTDIR)/lib/initcpio/hooks/$(APPNAME) 213 | 214 | $(DISTDIR)/lib/initcpio/install/$(APPNAME): $(SCRIPTDIR)/mkinitcpio/install.m4 $(M4VARSPATH) 215 | mkdir -p $(DISTDIR)/lib/initcpio/install 216 | m4 $(M4FLAGS) $< > $@ 217 | 218 | $(DISTDIR)/lib/initcpio/hooks/$(APPNAME): $(SCRIPTDIR)/mkinitcpio/run.m4 $(M4VARSPATH) 219 | mkdir -p $(DISTDIR)/lib/initcpio/hooks 220 | m4 $(M4FLAGS) $< > $@ 221 | 222 | 223 | .PHONY: initramfs-tools 224 | #: Build disk encryption scripts for use with initramfs-tools 225 | initramfs-tools: add-luks-key $(DISTDIR)/etc/initramfs-tools/hooks/crypt$(APPNAME) $(DISTDIR)/lib/$(APPNAME)/cryptsetup-keyscript 226 | 227 | shellcheck: $(DISTDIR)/etc/initramfs-tools/hooks/crypt$(APPNAME) $(DISTDIR)/lib/$(APPNAME)/cryptsetup-keyscript 228 | 229 | $(DISTDIR)/etc/initramfs-tools/hooks/crypt$(APPNAME): $(SCRIPTDIR)/initramfs-tools/hook.m4 $(M4VARSPATH) 230 | mkdir -p $(DISTDIR)/etc/initramfs-tools/hooks/ 231 | m4 $(M4FLAGS) $< > $@ 232 | 233 | $(DISTDIR)/lib/$(APPNAME)/cryptsetup-keyscript: $(SCRIPTDIR)/initramfs-tools/keyscript.m4 $(M4VARSPATH) 234 | mkdir -p $(DISTDIR)/lib/$(APPNAME) 235 | m4 $(M4FLAGS) $< > $@ 236 | 237 | 238 | 239 | ################################################################################ 240 | # SSH-ASKPASS # 241 | ################################################################################ 242 | 243 | .PHONY: ssh-askpass 244 | #: Build SSH askpass script 245 | ssh-askpass: $(DISTDIR)/bin/$(APPNAME)-ssh-askpass 246 | 247 | shellcheck: $(DISTDIR)/bin/$(APPNAME)-ssh-askpass 248 | 249 | $(DISTDIR)/bin/$(APPNAME)-ssh-askpass: $(SCRIPTDIR)/ssh-askpass.m4 $(METAPATH) $(M4VARSPATH) 250 | mkdir -p $(DISTDIR)/bin 251 | m4 $(M4FLAGS) $(SCRIPTDIR)/ssh-askpass.m4 > $@ 252 | 253 | 254 | ################################################################################ 255 | # SOURCE CODE CHECKS # 256 | ################################################################################ 257 | 258 | .PHONY: lint 259 | #: Lint and fix source code with clang-tidy 260 | lint: 261 | clang-tidy --fix $(SRCS) -- $(INCLUDEFLAGS) $(DEFINEFLAGS) 262 | 263 | .PHONY: check-lint 264 | check-lint: 265 | clang-tidy $(SRCS) -- $(INCLUDEFLAGS) $(DEFINEFLAGS) 266 | 267 | .PHONY: shellcheck 268 | #: Check scripts with shellcheck 269 | shellcheck: 270 | shellcheck $^ 271 | 272 | .PHONY: format 273 | #: Format source code with clang-format 274 | format: 275 | clang-format -style=file -i $(SRCS) $(HEADERS) 276 | 277 | .PHONY: check-format 278 | check-format: 279 | clang-format -style=file -Werror --dry-run $(SRCS) $(HEADERS) 280 | 281 | 282 | ################################################################################ 283 | # INDIVIDUAL SOURCE FILES # 284 | ################################################################################ 285 | 286 | $(BINPATH): $(OBJS) 287 | mkdir -p $(DISTDIR)/bin 288 | $(CC) -o $(BINPATH) $(OBJS) $(LDFLAGS) $(LDLIBS) 289 | 290 | -include $(PREREQUISITES) 291 | 292 | $(INCDIR)/help.h: $(METAPATH) 293 | 294 | %.d: %.c 295 | $(CC) $(CFLAGS) $< -MM -MT $(@:.d=.o) >$@ 296 | 297 | 298 | ################################################################################ 299 | # CLEANUP # 300 | ################################################################################ 301 | 302 | .PHONY: cleandist 303 | cleandist: 304 | $(RM) -rf $(DISTDIR) 305 | 306 | .PHONY: cleandep 307 | cleandep: 308 | $(RM) $(PREREQUISITES) 309 | 310 | .PHONY: cleanobj 311 | cleanobj: 312 | $(RM) $(OBJS) 313 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # khefin 2 | 3 | **As the primary author of `khefin`, I'm announcing my intention to deprecate this tool at the end of 2022.** Please see [Issue #42](https://github.com/mjec/khefin/issues/42) for more. 4 | 5 | A system for using a FIDO2 authenticator with [hmac-secret extension](https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#sctn-hmac-secret-extension) support to generate passphrase-protected secrets. 6 | 7 | [![Continuous integration status](https://github.com/mjec/khefin/workflows/Continuous%20integration/badge.svg)](https://github.com/mjec/khefin/actions?query=workflow%3A%22Continuous+integration%22) 8 | 9 | ## Installation 10 | 11 | For Arch Linux, install the [`khefin` AUR package](https://aur.archlinux.org/packages/khefin/). 12 | 13 | Install dependencies `libfido2`, `libcbor` and `libsodium`, then `make all && sudo make install`. 14 | 15 | For more, see `INSTALL.md`. 16 | 17 | At the moment I believe this tool is linux-only; issue reports or pull requests to improve portability are gratefully accepted. 18 | 19 | ## Usage 20 | 21 | The man page contains full usage information, but briefly: 22 | 23 | `khefin enumerate` will give you a list of connected authenticator devices, with a leading `!` for any device that is not supported. 24 | 25 | `khefin enrol -d /dev/hidraw0 -f /path/to/encrypted/keyfile` will create (or overwrite!) `/path/to/encrypted/keyfile` with an encrypted keyfile, the output of which depends on the authenticator at `/dev/hidraw0`. 26 | 27 | `khefin generate -f /path/to/encrypted/keyfile` will read that encrypted keyfile and output a secret based on it; but this will fail if the originally-used authenticator device is not connected (and the button pressed, if required). This will produce a 128 character ASCII (hex digits) string on STDOUT, followed by a single newline. 28 | 29 | `khefin-add-luks-key /path/to/encrypted/keyfile /dev/disk` will add the result of your encrypted keyfile to a keyslot in the LUKS-encrypted `/dev/disk`. See the manual for this tool for more information. **[Backup your LUKS header](https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions#6-backup-and-data-recovery) and data before using this.** 30 | 31 | `khefin-ssh-askpass` is a drop-in replacement for the `ssh-askpass` binary. See the manual for this tool for more information. 32 | 33 | ## Authenticator support 34 | 35 | This application relies on an extension to the FIDO2 standard, which not all FIDO2 authenticators support. `khefin enumerate` will show a leading `!` for any connected authenticator that is not supported. 36 | 37 | For a list of authenticators known to work or not work with this software, see [the GitHub wiki page](https://github.com/mjec/khefin/wiki/Supported-authenticators). 38 | 39 | ## Risks 40 | 41 | The number one risk is that by playing around with encryption like this you will lose your data. Keep good, offline backups of your data. Test your backups regularly, to ensure files can be recovered without access to any of your usual hardware or software. 42 | 43 | Each keyfile is associated with _only one_ authenticator, and _only one_ passphrase. To be secure, you are going to need at least two authenticators, which means two keyfiles. Make sure that whatever system you're using has support for that. 44 | 45 | [Backup your LUKS header](https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions#6-backup-and-data-recovery) and data before using this for disk encryption keys. Seriously. 46 | 47 | Keep a backup of the keyfile created by this application as well. If you lose that file, it is impossible to recover the secret. 48 | 49 | The security of this system depends on the security of your authenticator device, libsodium, libfido2, and the quality of your passphrase. It's also possible -- and indeed more likely than any of the former issues -- that there's a bug in the code for this application which compromises its security somehow. Pull requests and issues are very welcome. 50 | 51 | ## Warrant canary (but not a warranty) 52 | 53 | As at 17 January 2021, I (@mjec) have not received or complied with any government or non-government requests for information or services relating to this software, nor am I aware of any such requests. 54 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Versions 0.4.0 and above of this package are currently receiving security updates. 6 | 7 | ## Reporting a Vulnerability 8 | 9 | You can report vulnerabilities by filing a Github issue. This project supports full, immediate disclosure of security issues. 10 | 11 | If for some reason you would like to chat, email khefin@mjec.net. 12 | -------------------------------------------------------------------------------- /include/authenticator.h: -------------------------------------------------------------------------------- 1 | #ifndef AUTHENTICATOR_H 2 | #define AUTHENTICATOR_H 3 | 4 | #define RELYING_PARTY_ID_SIZE 32 5 | #define RELYING_PARTY_SUFFIX ".v1.fido2-hmac-secret.localhost" 6 | #define RELYING_PARTY_SUFFIX_SIZE strlen(RELYING_PARTY_SUFFIX) 7 | 8 | #ifndef MAX_DEVICES_TO_LIST 9 | #define MAX_DEVICES_TO_LIST 64 10 | #endif 11 | 12 | #define CLIENT_DATA_HASH_SIZE_BYTES 32 13 | 14 | #include 15 | 16 | typedef struct secret_t { 17 | unsigned char *secret; 18 | size_t secret_size; 19 | } secret_t; 20 | 21 | typedef struct authenticator_parameters_t { 22 | unsigned char *user_id; 23 | size_t user_id_size; 24 | unsigned char *client_data_hash; 25 | size_t client_data_hash_size; 26 | char *user_name; 27 | char *user_display_name; 28 | char *relying_party_id; 29 | char *relying_party_name; 30 | unsigned char *credential_id; 31 | size_t credential_id_size; 32 | unsigned char *salt; 33 | size_t salt_size; 34 | char *authenticator_pin; 35 | } authenticator_parameters_t; 36 | 37 | typedef struct devices_list_t { 38 | size_t count; 39 | fido_dev_info_t *list; 40 | } devices_list_t; 41 | 42 | devices_list_t *list_devices(void); 43 | void free_devices_list(devices_list_t *devices_list); 44 | 45 | fido_dev_t *get_device_even_if_not_fido2(const char *path); 46 | fido_dev_t *get_device(const char *path); 47 | bool device_supports_hmac_secret(fido_cbor_info_t *device_info); 48 | fido_cbor_info_t *get_device_info(fido_dev_t *device); 49 | void free_device_info(fido_cbor_info_t *cbor_info); 50 | void close_and_free_device_ignoring_errors(fido_dev_t *device); 51 | void close_and_free_device(fido_dev_t *device); 52 | 53 | authenticator_parameters_t * 54 | allocate_parameters_except_rpid(size_t credential_id_size, size_t salt_size); 55 | /** 56 | * This function assumes all pointers are to malloc()'d memory 57 | * except relying_party_id, credential_id and salt, which must 58 | * be malloc()'d. 59 | */ 60 | void free_parameters(authenticator_parameters_t *params); 61 | 62 | void create_credential(fido_dev_t *device, authenticator_parameters_t *params); 63 | 64 | secret_t *allocate_secret(size_t size); 65 | int get_secret_from_authenticator_params(fido_dev_t *device, 66 | authenticator_parameters_t *params, 67 | secret_t *secret_struct); 68 | void free_secret(secret_t *secret_struct); 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /include/cryptography.h: -------------------------------------------------------------------------------- 1 | #ifndef CRYPTOGRAPHY_H 2 | #define CRYPTOGRAPHY_H 3 | 4 | #include "invocation.h" 5 | #include "serialization_types.h" 6 | #include "stdlib.h" 7 | #include 8 | 9 | #define KEY_SIZE crypto_secretbox_KEYBYTES 10 | 11 | typedef struct key_spec_t { 12 | char *passphrase; 13 | unsigned char *kdf_salt; 14 | size_t kdf_salt_size; 15 | unsigned long long opslimit; 16 | size_t memlimit; 17 | int algorithm; 18 | } key_spec_t; 19 | 20 | unsigned char *derive_key(key_spec_t *key_spec); 21 | void free_key_spec(key_spec_t *spec); 22 | void free_key(unsigned char *key); 23 | key_spec_t * 24 | make_key_spec_from_passphrase_and_cleartext(char *passphrase, 25 | deserialized_cleartext *cleartext); 26 | key_spec_t *make_new_key_spec_from_invocation(invocation_state_t *invocation); 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /include/enrol.h: -------------------------------------------------------------------------------- 1 | #ifndef ENROL_H 2 | #define ENROL_H 3 | 4 | #include "authenticator.h" 5 | #include "invocation.h" 6 | 7 | #define RPID_ENCODING_TABLE_SIZE 32 8 | static const char __attribute__((unused)) 9 | RPID_ENCODING_TABLE[RPID_ENCODING_TABLE_SIZE] = { 10 | /* clang-format off */ 11 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 12 | 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 13 | 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 14 | 'y', 'z', '2', '3', '4', '5', '6', '7', 15 | /* clang-format on */ 16 | }; 17 | 18 | #ifndef SALT_SIZE_BYTES 19 | #define SALT_SIZE_BYTES 64 20 | #endif 21 | 22 | void enrol_device(invocation_state_t *invocation); 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /include/enumerate.h: -------------------------------------------------------------------------------- 1 | #ifndef ENUMERATE_H 2 | #define ENUMERATE_H 3 | 4 | #include "authenticator.h" 5 | 6 | void print_devices_list(devices_list_t *devices_list); 7 | void print_device_aaguid(fido_cbor_info_t *ctap_info); 8 | 9 | #endif 10 | -------------------------------------------------------------------------------- /include/exit.h: -------------------------------------------------------------------------------- 1 | #ifndef EXIT_H 2 | #define EXIT_H 3 | 4 | #include 5 | 6 | // Three categories of error: 7 | // - user errors, like a bad passphrase 8 | // - runtime errors, like out of memory 9 | // - programmer errors, which are bugs 10 | // In each category, we have 5 bits (32 codes) available to be more specific. 11 | // Each category's bitmask MUST be non-zero. Conveniently this means that all 12 | // exit codes less than 0x20 (32) are not specific to this application, as are 13 | // all exit codes greater than or equal to 0x80 (128). 14 | #define EXIT_H_USER_ERROR_BITS 0x20 /* 0b001xxxxx */ 15 | #define EXIT_H_RUNTIME_ERROR_BITS 0x40 /* 0b010xxxxx */ 16 | #define EXIT_H_PROGRAMMER_ERROR_BITS 0x60 /* 0b011xxxxx */ 17 | 18 | #ifndef EXIT_SUCCESS 19 | #define EXIT_SUCCESS 0 20 | #endif 21 | 22 | #define EXIT_BAD_INVOCATION (0 | EXIT_H_USER_ERROR_BITS) 23 | #define EXIT_BAD_PASSPHRASE (1 | EXIT_H_USER_ERROR_BITS) 24 | #define EXIT_NO_DEVICES (2 | EXIT_H_USER_ERROR_BITS) 25 | #define EXIT_NO_VALID_AUTHENTICATOR (3 | EXIT_H_USER_ERROR_BITS) 26 | #define EXIT_DESERIALIZATION_ERROR (4 | EXIT_H_USER_ERROR_BITS) 27 | #define EXIT_BAD_PIN (5 | EXIT_H_USER_ERROR_BITS) 28 | 29 | #define EXIT_OUT_OF_MEMORY (0 | EXIT_H_RUNTIME_ERROR_BITS) 30 | #define EXIT_AUTHENTICATOR_ERROR (1 | EXIT_H_RUNTIME_ERROR_BITS) 31 | #define EXIT_CRYPTOGRAPHY_ERROR (2 | EXIT_H_RUNTIME_ERROR_BITS) 32 | #define EXIT_OVER_PRIVILEGED (3 | EXIT_H_RUNTIME_ERROR_BITS) 33 | #define EXIT_UNABLE_TO_GET_USER_SECRET (4 | EXIT_H_RUNTIME_ERROR_BITS) 34 | 35 | #define EXIT_PROGRAMMER_ERROR (0 | EXIT_H_PROGRAMMER_ERROR_BITS) 36 | 37 | #ifndef EXIT_FAILURE 38 | #define EXIT_FAILURE 1 39 | #endif 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /include/files.h: -------------------------------------------------------------------------------- 1 | #ifndef FILES_H 2 | #define FILES_H 3 | 4 | #include "serialization_types.h" 5 | 6 | #ifndef LARGEST_VALID_PAYLOAD_SIZE_BYTES 7 | #define LARGEST_VALID_PAYLOAD_SIZE_BYTES 10485760 8 | #endif 9 | 10 | encoded_file *read_file(const char *path); 11 | void write_file(encoded_file *file); 12 | void free_encoded_file(encoded_file *file); 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /include/generate.h: -------------------------------------------------------------------------------- 1 | #ifndef GENERATE_H 2 | #define GENERATE_H 3 | 4 | #include "authenticator.h" 5 | #include "invocation.h" 6 | #include "serialization_types.h" 7 | 8 | unsigned short int 9 | print_secret_consuming_invocation(invocation_state_t *invocation, 10 | devices_list_t *devices_list); 11 | bool device_aaguid_matches(deserialized_cleartext *cleartext, 12 | fido_cbor_info_t *device_info); 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /include/help.h: -------------------------------------------------------------------------------- 1 | #ifndef HELP_H 2 | #define HELP_H 3 | 4 | #ifndef APPNAME 5 | #pragma message("APPNAME not defined; are you using the Makefile?") 6 | #define APPNAME "khefin" 7 | #endif 8 | 9 | #ifndef APPVERSION 10 | #pragma message("APPVERSION not defined; are you using the Makefile?") 11 | #define APPVERSION "unknown (not built with APPVERSION defined)" 12 | #endif 13 | 14 | void print_version(void); 15 | void print_usage(char *program_name); 16 | void print_help(char *program_name); 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /include/invocation.h: -------------------------------------------------------------------------------- 1 | #ifndef INVOCATION_H 2 | #define INVOCATION_H 3 | 4 | #include 5 | #include 6 | 7 | #ifndef LONGEST_VALID_PASSPHRASE 8 | #define LONGEST_VALID_PASSPHRASE 1024 9 | #endif 10 | 11 | // from FIDO2 CTAP spec section 5.6.1: 12 | // https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#client-pin-support-requirements 13 | #define LONGEST_VALID_PIN 255 14 | 15 | #define NL_CHARACTER_TO_STRIP 0x0a 16 | 17 | #define LOWERCASE(x) ((x) | 0x20) 18 | #define UPPERCASE(x) ((x) & ~0x20) 19 | 20 | typedef enum subcommand_t { 21 | subcommand_unknown, 22 | subcommand_help, 23 | subcommand_version, 24 | subcommand_enrol, 25 | subcommand_generate, 26 | subcommand_enumerate, 27 | } subcommand_t; 28 | 29 | typedef enum kdf_hardness_t { 30 | kdf_hardness_invalid, 31 | kdf_hardness_unspecified, 32 | kdf_hardness_low, 33 | kdf_hardness_medium, 34 | kdf_hardness_high, 35 | } kdf_hardness_t; 36 | 37 | typedef struct invocation_state_t { 38 | subcommand_t subcommand; 39 | char *device; 40 | char *file; 41 | char *passphrase; 42 | char *authenticator_pin; 43 | bool obfuscate_device_info; 44 | kdf_hardness_t kdf_hardness; 45 | char *mixin; 46 | } invocation_state_t; 47 | 48 | invocation_state_t *parse_arguments_and_get_passphrase(int argc, char **argv); 49 | void prompt_for_secret(const char *description, size_t maximum_size, 50 | char *result); 51 | void free_invocation(invocation_state_t *invocation); 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /include/memory.h: -------------------------------------------------------------------------------- 1 | #ifndef MEMORY_H 2 | #define MEMORY_H 3 | 4 | #ifndef WARN_ON_MEMORY_LOCK_ERRORS 5 | #define WARN_ON_MEMORY_LOCK_ERRORS 1 6 | #endif 7 | 8 | #include 9 | 10 | // This is a limit, not an allocation, so it's ok for it to be too big. 11 | // Set it to twice the largest amount of memory we could use (see 12 | // cryptography.c). 13 | #define MEMLOCK_LIMIT_BYTES (crypto_pwhash_MEMLIMIT_SENSITIVE * 2) 14 | 15 | void lock_memory_and_drop_privileges(void); 16 | 17 | void *malloc_or_exit(size_t n, const char *what); 18 | char *strdup_or_exit(const char *str, const char *what); 19 | char *strndup_or_exit(const char *str, size_t n, const char *what); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /include/serialization.h: -------------------------------------------------------------------------------- 1 | #ifndef SERIALIZATION_H 2 | #define SERIALIZATION_H 3 | 4 | #include 5 | 6 | #include "authenticator.h" 7 | #include "cryptography.h" 8 | #include "serialization_types.h" 9 | 10 | #define SERIALIZATION_MAX_VERSION 1 11 | 12 | #define OBFUSCATED_DEVICE_SENTINEL 0 13 | 14 | #ifdef DEBUG 15 | #define FIELD_COUNTER_ASSERT_START unsigned short __field_counter_assert = 0; 16 | #define FIELD_COUNTER_ASSERT(function, expected, line) \ 17 | if (__field_counter_assert++ != expected) \ 18 | errx(EXIT_PROGRAMMER_ERROR, \ 19 | "BUG (%s:%d): Serializing s is messed up: field %d should be at " \ 20 | "position %d", \ 21 | function, line, __field_counter_assert, expected); 22 | #else 23 | #define FIELD_COUNTER_ASSERT_START 24 | #define FIELD_COUNTER_ASSERT(function, expected, line) 25 | #endif 26 | 27 | authenticator_parameters_t * 28 | build_authenticator_parameters_from_deserialized_cleartext_and_key_and_mixin( 29 | deserialized_cleartext *cleartext, unsigned char *key_bytes, char *mixin); 30 | deserialized_cleartext * 31 | build_deserialized_cleartext_from_authenticator_parameters_and_key_spec( 32 | authenticator_parameters_t *authenticator_params, key_spec_t *key_spec); 33 | void free_cleartext(deserialized_cleartext *clear); 34 | void free_secrets(deserialized_secrets *secret); 35 | encoded_file *write_cleartext(deserialized_cleartext *cleartext, 36 | const char *path); 37 | deserialized_cleartext *load_cleartext(encoded_file *file); 38 | deserialized_secrets *load_secrets_from_bytes(unsigned char *decrypted, 39 | size_t decrypted_size); 40 | const char *get_cbor_error_string(cbor_error_code code); 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /include/serialization/v1.h: -------------------------------------------------------------------------------- 1 | #ifndef SERIALIZATION_V1_H 2 | #define SERIALIZATION_V1_H 3 | 4 | #include 5 | 6 | #include "../serialization.h" 7 | 8 | deserialized_cleartext * 9 | deserialize_cleartext_from_cbor_v1(cbor_item_t *cbor_root); 10 | cbor_item_t *serialize_cleartext_to_cbor_v1(deserialized_cleartext *clear); 11 | 12 | deserialized_secrets *deserialize_secrets_from_cbor_v1(cbor_item_t *cbor_root); 13 | cbor_item_t *serialize_secrets_to_cbor_v1(deserialized_secrets *secrets); 14 | 15 | #define SERIALIZATION_VERSION 1 16 | 17 | #define CLEAR_FIELD_VERSION 0 18 | #define CLEAR_FIELD_DEVICE_AAGUID 1 19 | #define CLEAR_FIELD_KDF_SALT 2 20 | #define CLEAR_FIELD_OPSLIMIT 3 21 | #define CLEAR_FIELD_MEMLIMIT 4 22 | #define CLEAR_FIELD_ALGORITHM 5 23 | #define CLEAR_FIELD_NONCE 6 24 | #define CLEAR_FIELD_ENCRYPTED_DATA 7 25 | 26 | #define CLEAR_COUNT_OF_FIELDS 8 27 | 28 | #define ENCRYPTED_FIELD_VERSION 0 29 | #define ENCRYPTED_FIELD_RP_ID 1 30 | #define ENCRYPTED_FIELD_CREDENTIAL_ID 2 31 | #define ENCRYPTED_FIELD_HMAC_SALT 3 32 | 33 | #define ENCRYPTED_COUNT_OF_FIELDS 4 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /include/serialization_types.h: -------------------------------------------------------------------------------- 1 | #ifndef SERIALIZATION_TYPES_H 2 | #define SERIALIZATION_TYPES_H 3 | 4 | #include 5 | #include 6 | 7 | typedef struct encoded_file { 8 | char *path; 9 | unsigned char *data; 10 | size_t length; 11 | } encoded_file; 12 | 13 | typedef struct deserialized_cleartext { 14 | uint8_t version; 15 | unsigned char *device_aaguid; 16 | size_t device_aaguid_size; 17 | 18 | unsigned char *kdf_salt; 19 | size_t kdf_salt_size; 20 | 21 | unsigned long long opslimit; 22 | size_t memlimit; 23 | int algorithm; 24 | 25 | unsigned char *nonce; 26 | size_t nonce_size; 27 | 28 | unsigned char *encrypted_data; 29 | size_t encrypted_data_size; 30 | } deserialized_cleartext; 31 | 32 | typedef struct deserialized_secrets { 33 | uint8_t version; 34 | 35 | char *relying_party_id; 36 | 37 | unsigned char *credential_id; 38 | size_t credential_id_size; 39 | 40 | unsigned char *salt; 41 | size_t salt_size; 42 | 43 | } deserialized_secrets; 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /man/1/khefin-ssh-askpass.m4: -------------------------------------------------------------------------------- 1 | .TH "m4_APPNAME-ssh-askpass" 1 "m4_APPDATE" "m4_APPVERSION" "m4_APPNAME-ssh-askpass man page" 2 | 3 | .SH NAME 4 | m4_APPNAME-ssh-askpass an ssh-askpass implementation using m4_APPNAME to secure SSH keys 5 | 6 | .SH SYNOPSIS 7 | .B m4_APPNAME-ssh-askpass 8 | .B get-passphrase 9 | .IR ssh-keyfile 10 | 11 | .SH DESCRIPTION 12 | This is a Bash script that can be used as a drop-in replacement for \fBssh-askpass\fR. 13 | It works by having a passphrase for each SSH key derived using \fB`'m4_APPNAME generate\fR and based on the SSH key's fingerprint. 14 | 15 | For this to work, you will need to set \fIssh-keyfile\fR's password to the output of \fB`'m4_APPNAME-ssh-askpass get-passphrase\fI ssh-keyfile\fR. 16 | You may use \fBssh-keygen -p -f \fIssh-keyfile\fB -N "$(m4_APPNAME-ssh-askpass get-passphrase \fIssh-keyfile\fB)"\fR to do this, however be aware that this will make the passphrase (briefly) available to other users on the system, who can inspect the command line for \fBssh-keygen\fR. 17 | 18 | Once that is done, you will need to set the \fBSSH_ASKPASS\fR environment variable to the path to \fB`'m4_APPNAME-ssh-askpass\fR so that \fBssh-agent\fR(1) knows to call it. 19 | 20 | .SH NOTES 21 | Because of the way this script works, it is not possible to use it with an authenticator that has a PIN. 22 | 23 | You should also make a backup of your encrypted keyfile (see \fBFILES\fR below), because without this file you will be unable to decrypt your SSH keys. 24 | 25 | This script accepts parameters which are not documented here, in accordance with the way ssh-agent calls it. 26 | In particular, the following ways of calling this script are supported: 27 | 28 | .TP 29 | \(bu \fB`'m4_APPNAME-ssh-askpass\fR "Enter passphrase for $keyfile_path:" 30 | 31 | .TP 32 | \(bu \fB`'m4_APPNAME-ssh-askpass\fR "Enter passphrase for $keyfile_path (will confirm each use):" 33 | 34 | .TP 35 | \(bu \fB`'m4_APPNAME-ssh-askpass\fR "Allow use of key $key_name?\\nKey fingerprint $key_fingerprint." 36 | 37 | .SH ENVIRONMENT 38 | 39 | .TP 40 | .BR m4_SSH_ASKPASS_ENCRYPTED_KEYFILE_ENV 41 | Path to the encrypted keyfile to use to protect SSH keys. 42 | Defaults to \fB`'m4_SSH_ASKPASS_DEFAULT_ENCRYPTED_KEYFILE\fR. 43 | 44 | .TP 45 | .BR m4_SSH_ASKPASS_NOTIFY_ENV 46 | The command to use to send notifications. 47 | Defaults to \fB`'m4_SSH_ASKPASS_DEFAULT_NOTIFY_COMMAND\fR or to printing to stderr if \fBget-passphrase\fR is used. 48 | 49 | .SH FILES 50 | 51 | .TP 52 | .BR m4_SSH_ASKPASS_DEFAULT_ENCRYPTED_KEYFILE 53 | The encrypted keyfile to use to protect SSH keys. 54 | Must be created with \fB`'m4_APPNAME`' enrol -p ""\fR. 55 | Can be changed by setting the \fB`'m4_SSH_ASKPASS_NOTIFY_ENV\fR environment variable. 56 | This file should by readable only by its owner, however that is not checked by this application. 57 | 58 | .SH BUGS 59 | .UR https://github.com/mjec/khefin/issues 60 | The GitHub issues page 61 | .UE 62 | has an up\-to\-date list of known issues. Bugs can also be reported there. 63 | 64 | .SH SEE ALSO 65 | 66 | .BR ssh-agent (1) 67 | .BR ssh-keygen (1) 68 | .BR m4_APPNAME (1) 69 | -------------------------------------------------------------------------------- /man/1/khefin.m4: -------------------------------------------------------------------------------- 1 | m4_define(`m4_MEMLOCK_WARNINGS_DIVERT_DESTINATION', m4_ifelse(m4_WARN_ON_MEMORY_LOCK_ERRORS, 0, -1, 0))m4_dnl 2 | .TH "m4_APPNAME" 1 "m4_APPDATE" "m4_APPVERSION" "m4_APPNAME man page" 3 | 4 | .SH NAME 5 | m4_APPNAME generate passphrase\-protected secrets from a FIDO2 authenticator that supports the hmac\-secret extension 6 | 7 | .SH SYNOPSIS 8 | .B m4_APPNAME 9 | .IR subcommand 10 | [\fIoptions\fR] 11 | 12 | .SH SUBCOMMANDS 13 | 14 | .B help 15 | print help screen and exit. 16 | 17 | .B version 18 | print version and exit. 19 | 20 | .B enumerate 21 | show a list of authenticator devices currently connected. 22 | 23 | .B enrol 24 | create or overwrite \fIfile\fR with randomly\-generated data required to produce a secret for the given \fIpassphrase\fR, using \fIdevice\fR. 25 | 26 | .B generate 27 | generate an HMAC across the data contained in \fIfile\fR, once it has been decrypted with the given \fIpassphrase\fR. 28 | 29 | .SH OPTIONS 30 | 31 | .TP 32 | .BR \-d ", " \-\-device =\fIdevice\fR 33 | REQUIRED for the \fBenrol\fR subcommand, otherwise prohibited. 34 | The path to the authenticator to enrol, e.g. /dev/hidraw0; see \fBenumerate\fR. 35 | This device MUST support the FIDO2 hmac\-secret extension (supported by most Yubico Security Keys and YubiKeys). 36 | 37 | .TP 38 | .BR \-f ", " \-\-file =\fIfile\fR 39 | REQUIRED for the \fBenrol\fR and \fBgenerate\fR subcommands, otherwise prohibited. 40 | The path to write to (for \fBenrol\fR; this file will be overwritten) or read from (for \fBgenerate\fR). 41 | 42 | .TP 43 | .BR \-p ", " \-\-passphrase =\fIpassphrase\fR 44 | Optional for the \fBenrol\fR and \fBgenerate\fR subcommands, otherwise prohibited. 45 | The passphrase to use to encrypt (for \fBenrol\fR) or decrypt (for \fBgenerate\fR) \fIfile\fR. 46 | If neither this nor \fIpassphrase-file\fR are specified, you will be prompted to enter a passphrase. 47 | Note that either way, passphrases must \fBnot\fR contain a null (0x00) byte. 48 | 49 | .TP 50 | .BR \-r ", " \-\-passphrase\-file =\fIpassphrase-file\fR 51 | Optional for the \fBenrol\fR and \fBgenerate\fR subcommands, otherwise prohibited. 52 | A file containing the passphrase to use to encrypt (for \fBenrol\fR) or decrypt (for \fBgenerate\fR) \fIfile\fR. 53 | Note that the entire file contents will be used, including any trailing newline. 54 | If neither this nor \fIpassphrase\fR are specified, you will be prompted to enter a passphrase. 55 | Note that either way, passphrases must \fBnot\fR contain a null (0x00) byte. 56 | 57 | .TP 58 | .BR \-n ", " \-\-pin =\fIPIN\fR 59 | Optional for the \fBenrol\fR and \fBgenerate\fR subcommands, otherwise prohibited. 60 | The PIN for your authenticator \fIdevice\fR. 61 | If not specified, and required by your authenticator, you will be prompted to enter a PIN. 62 | Note that either way, PINs must \fBnot\fR contain a null (0x00) byte. 63 | 64 | .TP 65 | .BR \-o ", " \-\-obfuscate\-device\-info 66 | Optional for the \fBenrol\fR subcommand, otherwise prohibited. 67 | If specified, do not store the \fIdevice\fR AAGUID (identifier of device make and model) in \fIfile\fR. 68 | 69 | .TP 70 | .BR \-k ", " \-\-kdf\-hardness =\fIhardness\fR 71 | Optional for the \fBenrol\fR subcommand, otherwise prohibited. 72 | Specify the complexity of the key derivation function used to derive a cryptographic key from \fIpassphrase\fR. 73 | Valid values for \fIhardness\fR are \fBhigh\fR, \fBmedium\fR or \fBlow\fR. 74 | If not specified, a value will be chosen automatically based on total system RAM. 75 | While greater hardness provides better security (at the cost of CPU time and RAM), more important is that \fIpassphrase\fR is long and difficult to guess. 76 | 77 | .TP 78 | .BR \-m ", " \-\-mixin =\fIdata\fR 79 | Optional for the \fBgenerate\fR subcommand, otherwise prohibited. 80 | Combine \fIdata\fR with the encrypted salt, so that the returned value depends on it. 81 | Note that setting \fIdata\fR to an empty string behaves differently to not using this argument at all. 82 | 83 | .SH DESCRIPTION 84 | 85 | m4_APPNAME produces deterministic output which can only be reproduced without \fIfile\fR, the \fIpassphrase\fR and the same authenticator \fIdevice\fR that was used during the \fBenrol\fR step. 86 | 87 | The canonical use case for m4_APPNAME is for generating an encryption key (or key material) that depends on two factors (a passphrase you know, and a device you have). 88 | 89 | The \fBenumerate\fR subcommand produces a list of connected authenticators, one per line, with the following tab\-separated fields: 90 | 91 | .RS 92 | 1. a one\-character field, containing a \fB!\fR if the authenticator does not support the hmac\-secret extension and otherwise a blank space 93 | 94 | 2. the path to the authenticator, e.g. /dev/hidraw0 95 | 96 | 3. the authenticator name and manufacturer, e.g. Yubico Security Key by Yubico 97 | 98 | 4. the authenticator AAGUID, e.g. f8a011f3-8c0a-4d15-8006-17111f9edc7d 99 | .RE 100 | 101 | If \fIpassphrase\fR and \fIPIN\fR are not provided as command line arguments, then behavior depends on whether m4_APPNAME is running at a TTY (interactively) or not. 102 | 103 | If m4_APPNAME has a TTY, you will be prompted to enter a passphrase and, if necessary, a PIN. 104 | For the \fBgenerate\fR subcommand, you will be prompted for each connected authenticator that has a PIN. 105 | 106 | If m4_APPNAME does not have a TTY, the passphrase will be read on STDIN, without any prompt, until a newline (or EOF) is reached. 107 | Then, if necessary, the PIN will be read on STDIN, without any prompt, until a newline (or EOF) is reached. 108 | Note that in this case, the newlines will \fBnot\fR be included in the passphrase or PIN. 109 | 110 | If you have multiple authenticators connected, \fBgenerate\fR may require you to provide multiple PINs, one for each PIN-protected connected authenticator. 111 | The order in which multiple PINs are requested is not guaranteed. 112 | As such providing an authenticator PIN on non-interactive STDIN is discouraged. 113 | 114 | In every case, only the first m4_LONGEST_VALID_PASSPHRASE bytes of a passphrase will be used. 115 | 116 | .SH EXIT STATUS 117 | 118 | .TP 119 | .BR 0 120 | Success 121 | 122 | .TP 123 | .BR 32 124 | Bad invocation (invalid \fIsubcommand\fR or \fIoptions\fR) 125 | 126 | .TP 127 | .BR 33 128 | Bad passphrase 129 | 130 | .TP 131 | .BR 34 132 | No authenticator device connected 133 | 134 | .TP 135 | .BR 35 136 | Of the authenticator(s) connected, none could be used (e.g. the connected device is different from the device used for the \fBenrol\fR step) 137 | 138 | .TP 139 | .BR 36 140 | \fIfile\fR is corrupt or cannot be decoded 141 | 142 | .TP 143 | .BR 64 144 | Out of memory 145 | 146 | .TP 147 | .BR 65 148 | Authenticator error 149 | 150 | .TP 151 | .BR 66 152 | Cryptography error 153 | 154 | .TP 155 | .BR 67 156 | Unable to drop privileges 157 | 158 | .TP 159 | .BR 68 160 | Unable to get passphrase or PIN safely (no TTY or STDIN, or not enough lines on STDIN) 161 | 162 | .TP 163 | .BR 96 164 | This is evidence of a bug; please report it (see \fBBUGS\fR below) 165 | 166 | .SH FILES 167 | 168 | \fIfile\fR (or the key file) contains information essential to producing the output of m4_APPNAME. 169 | Parts of the file are unencrypted, including the authenticator \fIdevice\fR AAGUID (unless \-\-obfuscate\-device\-info is set during the \fBenrol\fR step, this identifies the make and model of device), nonces, and the parameters for the key derivation algorithm used for the encrypted part of the file. 170 | 171 | Each key file can be used to produce exactly one secret, given exactly one passphrase and exactly one device. 172 | There is no support for having a backup authenticator for a given file, for example; instead you should create two key files. 173 | 174 | If you are using the output of m4_APPNAME for anything, you should keep a backup of \fIfile\fR. 175 | The sensitive components of this file are encrypted with a key derived solely from your \fIpassphrase\fR. 176 | As such, you should \fBnever\fR store your passphrase with the key file. 177 | You can store a backup of the key file in public unencrypted storage without compromising the security of the system per se, though it is good practice to ensure there are reasonable controls preventing public access. 178 | 179 | .SH NOTES 180 | If you run m4_APPNAME under \fBsudo\fR(8), it will drop privileges to the invoking user (specified by the \fBSUDO_UID\fR environment variable) after locking memory. 181 | 182 | m4_divert(m4_MEMLOCK_WARNINGS_DIVERT_DESTINATION)m4_dnl 183 | If you are seeing errors like \fBUnable to lock memory, which means secrets may be swapped to disk\fR, this means that RLIMIT_MEMLOCK is too low for m4_APPNAME to lock all its memory. 184 | The risk from this is that memory could be swapped to disk, resulting in secrets being written to swap space. 185 | You can fix this by raising RLIMIT_MEMLOCK, running m4_APPNAME as root, or by giving the binary the CAP_IPC_LOCK capability (so it can bypass RLIMIT_MEMLOCK) by running the following command as root: 186 | 187 | .RS 188 | setcap cap_ipc_lock+ep /path/to/m4_APPNAME 189 | .RE 190 | 191 | m4_divert(0)m4_dnl 192 | The name khefin is a reference to a minor god in the Discworld series of novels by Terry Pratchett. 193 | In that series, Khefin is the two-faced god of gateways, similar to the Roman god Janus. 194 | 195 | .SH SECURITY 196 | 197 | This system depends on the security of (and thus can never be more secure than) your authenticator device, the FIDO2 standard, libsodium, HMAC\-SHA256 and your passphrase. 198 | 199 | Because the output of m4_APPNAME is the same every time, you should rotate key files regularly. 200 | 201 | This also means that m4_APPNAME is not an ideal solution for authentication. 202 | Where possible, you should use a system which relies on a challenge being signed by your authenticator device. 203 | Examples of such systems which use FIDO2 authenticators are WebAuthn and pam_u2f. 204 | In particular, for providing a second factor for sign\-in or privilege escallation using PAM, pam_u2f is a better solution. 205 | 206 | .SH BUGS 207 | .UR https://github.com/mjec/khefin/issues 208 | The GitHub issues page 209 | .UE 210 | has an up\-to\-date list of known issues. Bugs can also be reported there. 211 | 212 | .SH SEE ALSO 213 | 214 | .BR pam_u2f (8) 215 | m4_divert(m4_MEMLOCK_WARNINGS_DIVERT_DESTINATION)m4_dnl 216 | .BR setcap (8) 217 | m4_divert(0)m4_dnl 218 | .BR sudo (8) 219 | -------------------------------------------------------------------------------- /man/8/khefin-add-luks-key.m4: -------------------------------------------------------------------------------- 1 | .TH "m4_APPNAME-add-luks-key" 8 "m4_APPDATE" "m4_APPVERSION" "m4_APPNAME-add-luks-key man page" 2 | 3 | .SH NAME 4 | m4_APPNAME-add-luks-key add a LUKS key to an encrypted disk derived from a keyfile created with m4_APPNAME 5 | 6 | .SH SYNOPSIS 7 | .B m4_APPNAME-add-luks-key 8 | .IR encrypted-keyfile 9 | .IR disk 10 | [\fIcryptsetup-options\fR] 11 | 12 | .SH DESCRIPTION 13 | This is a Bash script that runs \fBcryptsetup\fR(8)'s \fIluksAddKey\fR, passing in a keyfile generated with \fB`'m4_APPNAME\fR(1). 14 | It is designed for use with the m4_APPNAME \fBmkinitcpio\fR(8) or \fBinitramfs-tools\fR(8) hooks. 15 | 16 | \fIencrypted-keyfile\fR must have been generated by \fB`'m4_APPNAME enrol\fR. 17 | 18 | This script must be run as root. 19 | 20 | .SH NOTES 21 | \fBMake an off-system backup of your LUKS header for \f(BIdisk\fB before running this command.\fR 22 | 23 | You should also make a backup of \fIencrypted-keyfile\fR, because without this file the new keyslot on \fIdisk\fR cannot be used. 24 | 25 | .SH BUGS 26 | .UR https://github.com/mjec/khefin/issues 27 | The GitHub issues page 28 | .UE 29 | has an up\-to\-date list of known issues. Bugs can also be reported there. 30 | 31 | .SH SEE ALSO 32 | 33 | .BR cryptsetup (8) 34 | .BR m4_APPNAME (1) 35 | 36 | Run \fBmkinitcpio -H m4_APPNAME\fR for help with the m4_APPNAME mkinitcpio hook (if installed). 37 | 38 | See \fB`'m4_APPNAME-cryptsetup-keyscript\fR(8) for help with the m4_APPNAME initramfs-tools hook (if installed). -------------------------------------------------------------------------------- /man/8/khefin-cryptsetup-keyscript.m4: -------------------------------------------------------------------------------- 1 | .TH "m4_APPNAME cryptsetup-keyscript" 8 "m4_APPDATE" "m4_APPVERSION" "m4_APPNAME cryptsetup-keyscript man page" 2 | 3 | .SH NAME 4 | m4_APPNAME-cryptsetup-keyscript a Debian-style keyscript for unlocking a LUKS-encrypted disk at boot time with a key derived from a keyfile created with m4_APPNAME 5 | 6 | .SH DESCRIPTION 7 | This script, installed to \fI`'m4_INSTALL_PREFIX/lib/m4_APPNAME/cryptsetup-keyscript\fR by default, is designed to be specified as a \fIkeyscript\fR in \fBcrypttab\fR(5). 8 | The \fIkey\fR field in the \fBcrypttab\fR(5) will be used as the keyfile passed to \fB`'m4_APPNAME generate\fR. 9 | 10 | In general, to set up disk encryption protected by \fB`'m4_APPNAME\fR(1) you would go through the following steps: 11 | 12 | .RS 13 | 1. Run \fB`'m4_APPNAME enrol\fR to generate a keyfile. 14 | 15 | 2. Run \fB`'m4_APPNAME`'-add-luks-key\fR(8) to add a key to your LUKS-encrypted disk. 16 | 17 | 3. Update \fI/etc/crypttab\fR to specify this keyfile. An example crypttab entry might be: 18 | .RS 19 | sda1_crypt UUID=... /path/to/keyfile luks,keyscript=m4_INSTALL_PREFIX/lib/m4_APPNAME/cryptsetup-keyscript 20 | .RE 21 | 22 | 4. Run \fBupdate-initramfs -u\fR to update your initramfs. 23 | .RE 24 | 25 | .SH NOTES 26 | 27 | .B Before using this keyscript, you should be aware of how to boot your computer in the event this does not work correctly. 28 | You should have a backup of your LUKS header, a key slot in your disk that does not rely on m4_APPNAME, and an understanding of how to recover from an unbootable system. 29 | 30 | This script requires m4_APPNAME and appropriate libraries to be copied to your initramfs, along with the relevant keyfile. 31 | This is normally handled by the m4_APPNAME initramfs hook script, which is installed to \fI/etc/initramfs-tools/hooks/crypt`'m4_APPNAME\fR by default. 32 | If you are not using \fBinitramfs-tools\fR(8), it is up to you to ensure this happens. 33 | 34 | The m4_APPNAME initramfs hook relies on m4_APPNAME being available in the \fBPATH\fR used by \fBmkinitramfs\fR(8), which may not include \fI`'m4_INSTALL_PREFIX/bin\fR. 35 | You may need to edit the hook script to specify the full path to m4_APPNAME, or ensure m4_APPNAME is installed in the appropriate path. 36 | 37 | The m4_APPNAME initramfs hook relies on the full path to the keyscript ending with \fB`'m4_APPNAME/cryptsetup-keyscript\fR, wherever it is located. 38 | 39 | .SH FILES 40 | .TP 41 | .IR m4_INSTALL_PREFIX/lib/m4_APPNAME/cryptsetup-keyscript 42 | This script. 43 | 44 | .TP 45 | .IR /etc/initramfs-tools/hooks/crypt`'m4_APPNAME 46 | The \fBinitramfs-tools\fR(8) hook that ensures this script can run correctly. 47 | 48 | .SH BUGS 49 | .UR https://github.com/mjec/khefin/issues 50 | The GitHub issues page 51 | .UE 52 | has an up\-to\-date list of known issues. Bugs can also be reported there. 53 | 54 | .SH SEE ALSO 55 | 56 | .BR cryptsetup (8) 57 | .BR crypttab (5) 58 | .BR initramfs-tools (8) 59 | .BR m4_APPNAME (1) 60 | .BR m4_APPNAME`'-add-luks-key (8) 61 | -------------------------------------------------------------------------------- /metadata.make: -------------------------------------------------------------------------------- 1 | APPNAME=khefin 2 | APPVERSION=0.6.1 -------------------------------------------------------------------------------- /scripts/add-luks-key.m4: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set +xv -euo pipefail 4 | umask 077 5 | 6 | ramfs_mount_point="$(mktemp -d)" 7 | disk_encryption_key_file="$ramfs_mount_point/keyfile" 8 | 9 | help() { 10 | printf "Usage: %s [cryptsetup-options]\n\n" "$0" 11 | fold -w 80 -s < must have been generated by m4_APPNAME enrol. 15 | 16 | This script must be run as root. 17 | 18 | !!! Make an off-system backup of your LUKS header for before running this command. !!! 19 | 20 | You should also make a backup of , because without this file the new keyslot on disk cannot be used. 21 | HELPEOF 22 | } 23 | 24 | cleanup() { 25 | # Try really hard to clean up, even if part of cleanup fails 26 | set +e 27 | rm -f "$disk_encryption_key_file" 28 | umount -f -q "$ramfs_mount_point" 29 | rm -rf "$ramfs_mount_point" 30 | } 31 | 32 | trap cleanup EXIT TERM INT 33 | 34 | if [ "$#" -lt 2 ] || [ "$(id -u)" -ne 0 ]; then 35 | help 36 | exit 1 37 | fi 38 | 39 | mount -t ramfs -o size=64k "$ramfs_mount_point" "$ramfs_mount_point" 40 | m4_APPNAME generate -f "$1" > "$disk_encryption_key_file" 41 | cryptsetup luksAddKey "$2" "${@:3}" "$disk_encryption_key_file" 42 | : < /dev/null > "$disk_encryption_key_file" 43 | -------------------------------------------------------------------------------- /scripts/bash-completion.m4: -------------------------------------------------------------------------------- 1 | m4_dnl This file defines bash completions using the https://github.com/scop/bash-completion framework. 2 | m4_define(`m4_APPNAME_US', m4_translit(m4_APPNAME, `-', `_'))m4_dnl 3 | m4_define(`m4_COMPLETION_FUNCTION_NAME', `_complete_'m4_APPNAME_US)m4_dnl 4 | m4_dnl 5 | m4_dnl 6 | #!/bin/bash 7 | 8 | m4_COMPLETION_FUNCTION_NAME`'() { 9 | local cur prev words 10 | local subcommands="help version enumerate enrol generate" 11 | local opts 12 | _init_completion -s || return 13 | 14 | case "$prev" in 15 | help|version|enumerate|--help|--passphrase|-p|--mixin|-m|--pin|-n) 16 | return 17 | ;; 18 | --file|-!(-*)f) 19 | _filedir 20 | return 21 | ;; 22 | --device|-!(-*)d) 23 | mapfile -t COMPREPLY < <("${words[0]}" enumerate | grep -v '^!' | cut -f 2) 24 | return 25 | ;; 26 | --kdf-hardness|-!(-*)k) 27 | mapfile -t COMPREPLY < <(compgen -W "low medium high" -- "$cur") 28 | return 29 | ;; 30 | esac 31 | 32 | case "${words[1]}" in 33 | generate) 34 | opts="-f -p -r -n -m --file --passphrase --passphrase-file --pin --mixin" 35 | ;; 36 | enrol) 37 | opts="-f -d -p -r -n -o -k --file --device --passphrase --passphrase-file --pin --obfuscate-device-info --kdf-hardness" 38 | ;; 39 | esac 40 | 41 | if [[ "$prev" == "m4_APPNAME" ]]; then 42 | mapfile -t COMPREPLY < <(compgen -W "$subcommands" -- "$cur") 43 | [[ ${COMPREPLY[0]} == *= ]] && compopt -o nospace 44 | else 45 | mapfile -t COMPREPLY < <(compgen -W "$opts" -- "$cur") 46 | fi 47 | } 48 | 49 | complete -F m4_COMPLETION_FUNCTION_NAME m4_APPNAME 50 | -------------------------------------------------------------------------------- /scripts/initramfs-tools/hook.m4: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | `#' Change this to a full path if m4_APPNAME is not installed on the mkinitramfs path. E.g.: 4 | `#' path_to_`'m4_APPNAME="/usr/local/bin/m4_APPNAME" 5 | path_to_`'m4_APPNAME="$(command -v m4_APPNAME)" 6 | 7 | PREREQ="cryptroot" 8 | 9 | prereqs() { 10 | echo "$PREREQ" 11 | } 12 | 13 | case $1 in 14 | prereqs) 15 | prereqs 16 | exit 0 17 | ;; 18 | esac 19 | 20 | #shellcheck disable=SC1091 21 | . /usr/share/initramfs-tools/hook-functions 22 | #shellcheck disable=SC1091 23 | . /lib/cryptsetup/functions 24 | 25 | if ! [ -f "$TABFILE" ]; then 26 | >&2 printf "Skipping hook because no crypttab file at %s\n" "$TABFILE" 27 | exit 0 28 | fi 29 | 30 | copy_app() { 31 | if ! copy_exec "$path_to_`'m4_APPNAME"; then 32 | >&2 printf "Unable to find m4_APPNAME on PATH (%s).\n" "$PATH" 33 | >&2 printf "Ensure m4_APPNAME is installed into that path, or hard-code its path at the top of %s.\n" "$0" 34 | exit 1 35 | fi 36 | } 37 | 38 | copy_key() { 39 | crypttab_parse_options 40 | 41 | # using case for wildcard matching 42 | case "${CRYPTTAB_OPTION_keyscript-}" in 43 | *m4_APPNAME/cryptsetup-keyscript) 44 | if [ "${CRYPTTAB_KEY-none}" = "none" ]; then 45 | >&2 printf "m4_APPNAME keyscript specified but no key specified!\n" 46 | exit 1 47 | fi 48 | 49 | if ! [ -f "$CRYPTTAB_KEY" ]; then 50 | >&2 printf "m4_APPNAME keyscript specified but key at %s does not exist.\n" "$CRYPTTAB_KEY" 51 | exit 1 52 | fi 53 | 54 | copy_app 55 | copy_file "key" "$CRYPTTAB_KEY" 56 | if [ $? -gt 1 ]; then 57 | exit 1 58 | fi 59 | ;; 60 | esac 61 | } 62 | 63 | crypttab_foreach_entry copy_key 64 | 65 | exit 0 66 | -------------------------------------------------------------------------------- /scripts/initramfs-tools/keyscript.m4: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | decrypt_`'m4_APPNAME () { 4 | m4_APPNAME enumerate >/dev/null 5 | if [ $? -eq 34 ]; then 6 | >&2 printf "Authenticator device not found!\n" 7 | return 1 8 | fi 9 | >&2 printf "Using key %s\n" "$1" 10 | if ! m4_APPNAME generate -f "$1"; then 11 | return 1 12 | fi 13 | return 0 14 | } 15 | 16 | if ! command -v m4_APPNAME > /dev/null; then 17 | >&2 printf "%s: m4_APPNAME is not available\n" "$0" 18 | exit 1 19 | fi 20 | 21 | if [ -z "$1" ]; then 22 | >&2 printf "%s: missing first argument (a keyfile)\n" "$0" 23 | exit 1 24 | fi 25 | 26 | decrypt_`'m4_APPNAME "$1" 27 | exit $? 28 | -------------------------------------------------------------------------------- /scripts/mkinitcpio/install.m4: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | build() { 4 | keyfiles_source_dir="${keyfiles_source_dir-m4_INITCPIO_DEFAULT_KEYFILES_SOURCE_DIR}" 5 | encrypted_keyfile_dir="${encrypted_keyfile_dir-m4_INITCPIO_DEFAULT_ENCRYPTED_KEYFILE_DIR}" 6 | 7 | # If $keyfiles_source_dir doesn't exist, we can't copy over any keyfiles, and this hook should never run 8 | if [ ! -d "$keyfiles_source_dir" ]; then 9 | return 10 | fi 11 | 12 | # If $keyfiles_source_dir is empty, we can't copy over keyfiles, and this hook should never run 13 | if [ "$(find "$keyfiles_source_dir" -maxdepth 1 -type f -print | wc -l)" -eq 0 ]; then 14 | return 15 | fi 16 | 17 | add_binary m4_APPNAME 18 | add_binary stty 19 | 20 | find "$keyfiles_source_dir" -maxdepth 1 ! -name "$(printf "*\n*")" -type f -print \ 21 | | while IFS= read -r keyfile; do 22 | add_file "$keyfile" "$encrypted_keyfile_dir"/"$(basename "$keyfile")" 400 23 | done 24 | 25 | add_runscript 26 | } 27 | 28 | help() { 29 | fold -w 80 -s < /dev/null 20 | if [ "$?" -eq 34 ]; then 21 | if [ "${do_not_prompt_for_authenticator:-$undefined}" != "$undefined" ]; then 22 | printf "No authenticator device found; skipping m4_APPNAME.\n" 23 | return 24 | else 25 | printf "Insert your authenticator device and press any key to continue.\n" 26 | printf "If you press a key without inserting your authenticator, the m4_APPNAME hook will be skipped.\n" 27 | stty -icanon -echo 28 | dd bs=1 count=1 2>/dev/null 29 | stty icanon echo 30 | m4_APPNAME enumerate > /dev/null 31 | if [ "$?" -eq 34 ]; then 32 | printf "No authenticator device found; skipping m4_APPNAME hook.\n" 33 | return 34 | fi 35 | fi 36 | fi 37 | 38 | if [ -d "$ramfs_mount_point" ] && [ -n "$(ls -A "$ramfs_mount_point")" ]; then 39 | printf "%s unexpectedly exists and is not an empty directory; skipping m4_APPNAME hook.\n" "$ramfs_mount_point" 40 | elif [ -e "$ramfs_mount_point" ]; then 41 | printf "%s unexpectedly exists and is not an empty directory; skipping m4_APPNAME hook.\n" "$ramfs_mount_point" 42 | fi 43 | 44 | mkdir -p "$ramfs_mount_point" 45 | mount -t ramfs -o size=64k "$ramfs_mount_point" "$ramfs_mount_point" 46 | 47 | if [ "${encrypted_keyfile_passphrase-$undefined}" != "$undefined" ]; then 48 | # Never prompt 49 | passphrase_prompt_option=m4_PROMPT_NEVER 50 | printf "Using hardcoded passphrase for m4_APPNAME.\n" 51 | elif [ "${same_passphrase_every_keyfile:-$undefined}" != "$undefined" ]; then 52 | # Prompt first time only 53 | passphrase_prompt_option=m4_PROMPT_ONCE 54 | else 55 | # Always prompt 56 | passphrase_prompt_option=m4_PROMPT_ALWAYS 57 | fi 58 | 59 | # This ! [ $x -gt 0 ] construction means that we do the body even if $x is not a number 60 | if ! [ "${encrypted_keyfile_passphrase_attempts-NaN}" -gt 0 ] > /dev/null 2>&1; then 61 | encrypted_keyfile_passphrase_attempts=m4_INITCPIO_DEFAULT_MAX_PASSPHRASE_ATTEMPTS 62 | fi 63 | 64 | for encrypted_keyfile in "$encrypted_keyfile_dir"/* "$encrypted_keyfile_dir"/.*; do 65 | if [ ! -f "$encrypted_keyfile" ]; then 66 | continue 67 | fi 68 | 69 | passphrase_tries=0 70 | exit_loop=0 71 | 72 | if [ "$passphrase_prompt_option" -eq m4_PROMPT_ALWAYS ]; then 73 | # Prompt for a new passphrase for this keyfile 74 | unset encrypted_keyfile_passphrase 75 | fi 76 | 77 | while 78 | passphrase_tries=$((passphrase_tries + 1)) 79 | if [ "${encrypted_keyfile_passphrase-$undefined}" = "$undefined" ]; then 80 | stty -echo 81 | case $passphrase_prompt_option in 82 | m4_PROMPT_ONCE) printf "Enter your passphrase for all keyfiles in %s: " "$encrypted_keyfile_dir" ;; 83 | m4_PROMPT_ALWAYS) printf "Enter your passphrase for %s: " "$encrypted_keyfile" ;; 84 | esac 85 | read -r encrypted_keyfile_passphrase 86 | stty echo 87 | printf "\n" 88 | fi 89 | 90 | if [ $passphrase_prompt_option -ne m4_PROMPT_ALWAYS ]; then 91 | printf "Trying to decrypt %s.\n" "$encrypted_keyfile" 92 | fi 93 | 94 | printf "%s" "$encrypted_keyfile_passphrase" > "$encrypted_keyfile_passphrase_file" 95 | m4_APPNAME generate -f "$encrypted_keyfile" -r "$encrypted_keyfile_passphrase_file" > $disk_encryption_key_file 96 | result=$? 97 | : < /dev/null > $encrypted_keyfile_passphrase_file 98 | 99 | if [ $result -eq 0 ]; then 100 | export cryptkey="rootfs:$disk_encryption_key_file" 101 | return 102 | elif [ $result -eq 33 ] && [ $passphrase_prompt_option -ne m4_PROMPT_NEVER ]; then 103 | `#' From m4_APPNAME man page, EXIT CODES section: 104 | `#' 33 Bad passphrase 105 | unset encrypted_keyfile_passphrase 106 | else 107 | # Failure but not due to a bad passphrase, so move on to the next keyfile 108 | exit_loop=1 109 | fi 110 | 111 | if [ $passphrase_tries -ge "$encrypted_keyfile_passphrase_attempts" ]; then 112 | printf "Too many failed passphrase attempts (maximum of %s).\n" $encrypted_keyfile_passphrase_attempts 113 | exit_loop=1 114 | fi 115 | 116 | [ $exit_loop -eq 0 ] 117 | do :; done 118 | done 119 | 120 | unset encrypted_keyfile_passphrase 121 | } 122 | 123 | run_cleanuphook() { 124 | : < /dev/null > $disk_encryption_key_file 125 | rm -f "$disk_encryption_key_file" 126 | rm -f "$encrypted_keyfile_passphrase_file" 127 | umount -f "$ramfs_mount_point" 128 | rm -rf "$ramfs_mount_point" 129 | } 130 | -------------------------------------------------------------------------------- /scripts/ssh-askpass.m4: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | prompt="${1-}" 6 | f2hs_keyfile="${m4_SSH_ASKPASS_ENCRYPTED_KEYFILE_ENV-m4_SSH_ASKPASS_DEFAULT_ENCRYPTED_KEYFILE}" 7 | 8 | print_usage() { 9 | progname="$(basename "$0")" 10 | printf >&2 "%s get-passphrase \"\$keyfile_path\"\n" "$progname" 11 | } 12 | 13 | notify() { 14 | ${m4_SSH_ASKPASS_NOTIFY_ENV-m4_SSH_ASKPASS_DEFAULT_NOTIFY_COMMAND} "$1" "$2" 15 | } 16 | 17 | get_fingerprint_for_keyfile() { 18 | if [ ! -f "$1" ]; then 19 | notify "m4_APPNAME ssh-askpass failure" "No such keyfile: $1" 20 | exit 1 21 | fi 22 | ssh-keygen -l -f "$1" | cut -f 2 -d ' ' 23 | } 24 | 25 | if [ -z "$prompt" ]; then 26 | print_usage 27 | exit 1 28 | fi 29 | 30 | if [ ! -r "$f2hs_keyfile" ]; then 31 | printf >&2 "m4_APPNAME encrypted keyfile does not exist at %s.\nYou can create it with m4_APPNAME enrol." "$f2hs_keyfile" 32 | exit 1 33 | fi 34 | 35 | if [ "$prompt" = "get-passphrase" ]; then 36 | if [ -z "${m4_SSH_ASKPASS_NOTIFY_ENV-}" ]; then 37 | notify() { 38 | >&2 printf "%s\n%s\n" "$1" "$2" 39 | } 40 | fi 41 | 42 | if [ -z "${2-}" ]; then 43 | print_usage 44 | exit 1 45 | fi 46 | fi 47 | 48 | set +e 49 | m4_APPNAME enumerate >/dev/null 2>&1 50 | if [ $? -eq 34 ]; then 51 | notify "m4_APPNAME ssh-askpass failure" "No compatible FIDO2 authenticator device is connected." 52 | exit 1 53 | fi 54 | set -e 55 | 56 | if [ "$prompt" = "get-passphrase" ]; then 57 | fingerprint="$(get_fingerprint_for_keyfile "$2")" 58 | notify "Trigger authenticator to get passphrase" "Keyfile $2 (fingerprint $fingerprint)." 59 | m4_APPNAME generate -f "$f2hs_keyfile" -m "$fingerprint" -p "" 60 | elif printf "%s" "$prompt" | grep '^Allow use of key' > /dev/null; then 61 | notify "Trigger authenticator to allow use of key" "$prompt" 62 | m4_APPNAME generate -f "$f2hs_keyfile" -m "" -p "" > /dev/null 2>&1 63 | else 64 | keyfile="$(printf "%s" "$prompt" | sed -E 's/ \(will confirm each use\)(:[[:space:]]*)$/\1/ ; s/Enter passphrase for (.+):.*$/\1/')" 65 | fingerprint="$(get_fingerprint_for_keyfile "$keyfile")" 66 | notify "Trigger authenticator to add key to ssh agent" "Keyfile $keyfile (fingerprint $fingerprint)." 67 | m4_APPNAME generate -f "$f2hs_keyfile" -m "$fingerprint" -p "" 68 | fi 69 | -------------------------------------------------------------------------------- /src/authenticator.c: -------------------------------------------------------------------------------- 1 | #include "authenticator.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "exit.h" 8 | #include "memory.h" 9 | #include "serialization.h" 10 | 11 | devices_list_t *list_devices(void) { 12 | fido_dev_info_t *list; 13 | size_t count; 14 | int r; 15 | devices_list_t *result = 16 | malloc_or_exit(sizeof(devices_list_t), "list of devices"); 17 | 18 | if ((list = fido_dev_info_new(MAX_DEVICES_TO_LIST)) == NULL) { 19 | errx(EXIT_OUT_OF_MEMORY, "Unable to create new list of devices"); 20 | } 21 | 22 | if ((r = fido_dev_info_manifest(list, MAX_DEVICES_TO_LIST, &count)) != 23 | FIDO_OK) { 24 | if (r != FIDO_ERR_INTERNAL) { 25 | errx(EXIT_AUTHENTICATOR_ERROR, 26 | "Unable to get devices manifest: %s (0x%x)", fido_strerr(r), 27 | r); 28 | } 29 | count = 0; 30 | list = NULL; 31 | } 32 | 33 | result->count = count; 34 | result->list = list; 35 | 36 | return result; 37 | } 38 | 39 | void free_devices_list(devices_list_t *devices_list) { 40 | if (devices_list == NULL) { 41 | return; 42 | } 43 | if (devices_list->list != NULL) { 44 | fido_dev_info_free(&devices_list->list, devices_list->count); 45 | } 46 | free(devices_list); 47 | } 48 | 49 | fido_dev_t *get_device_even_if_not_fido2(const char *path) { 50 | fido_dev_t *device; 51 | int r; 52 | 53 | if ((device = fido_dev_new()) == NULL) { 54 | errx(EXIT_OUT_OF_MEMORY, 55 | "Unable to create device structure (out of memory?)"); 56 | } 57 | 58 | if ((r = fido_dev_open(device, path)) != FIDO_OK) { 59 | errx(EXIT_AUTHENTICATOR_ERROR, 60 | "Unable to access device at %s: %s (0x%x)", path, fido_strerr(r), 61 | r); 62 | } 63 | 64 | return device; 65 | } 66 | 67 | fido_dev_t *get_device(const char *path) { 68 | fido_dev_t *device = get_device_even_if_not_fido2(path); 69 | 70 | if (fido_dev_is_fido2(device) == false) { 71 | errx(EXIT_AUTHENTICATOR_ERROR, 72 | "Device at %s is not a FIDO2 authenticator", path); 73 | } 74 | 75 | return device; 76 | } 77 | 78 | bool device_supports_hmac_secret(fido_cbor_info_t *device_info) { 79 | char *const *extensions = fido_cbor_info_extensions_ptr(device_info); 80 | size_t extensions_length = fido_cbor_info_extensions_len(device_info); 81 | 82 | for (size_t i = 0; i < extensions_length; i++) { 83 | if (strcmp("hmac-secret", extensions[i]) == 0) { 84 | return true; 85 | } 86 | } 87 | 88 | return false; 89 | } 90 | 91 | fido_cbor_info_t *get_device_info(fido_dev_t *device) { 92 | fido_cbor_info_t *device_info; 93 | int r; 94 | 95 | if ((device_info = fido_cbor_info_new()) == NULL) { 96 | errx(EXIT_OUT_OF_MEMORY, 97 | "Unable to create device info structure (out of memory?)"); 98 | } 99 | 100 | if ((r = fido_dev_get_cbor_info(device, device_info)) != FIDO_OK) { 101 | errx(EXIT_AUTHENTICATOR_ERROR, 102 | "Unable to get info from device: %s (0x%x)", fido_strerr(r), r); 103 | } 104 | 105 | return device_info; 106 | } 107 | 108 | void free_device_info(fido_cbor_info_t *cbor_info) { 109 | if (cbor_info == NULL) { 110 | return; 111 | } 112 | fido_cbor_info_free(&cbor_info); 113 | } 114 | 115 | void close_and_free_device_ignoring_errors(fido_dev_t *device) { 116 | if (device == NULL) { 117 | return; 118 | } 119 | int r; 120 | if ((r = fido_dev_close(device)) != FIDO_OK) { 121 | warnx("Unable to close device: %s (0x%x)", fido_strerr(r), r); 122 | return; 123 | }; 124 | fido_dev_free(&device); 125 | } 126 | 127 | void close_and_free_device(fido_dev_t *device) { 128 | if (device == NULL) { 129 | return; 130 | } 131 | 132 | int r; 133 | 134 | if ((r = fido_dev_close(device)) != FIDO_OK) { 135 | errx(EXIT_AUTHENTICATOR_ERROR, "Unable to close device: %s (0x%x)", 136 | fido_strerr(r), r); 137 | } 138 | 139 | fido_dev_free(&device); 140 | } 141 | 142 | authenticator_parameters_t * 143 | allocate_parameters_except_rpid(size_t credential_id_size, size_t salt_size) { 144 | authenticator_parameters_t *params = malloc_or_exit( 145 | sizeof(authenticator_parameters_t), "authenticator parameters"); 146 | 147 | if (credential_id_size) { 148 | params->credential_id = malloc_or_exit( 149 | credential_id_size, "credential id in authenticator parameters"); 150 | params->credential_id_size = credential_id_size; 151 | } else { 152 | params->credential_id = NULL; 153 | params->credential_id_size = 0; 154 | } 155 | 156 | if (salt_size) { 157 | params->salt = 158 | malloc_or_exit(salt_size, "salt in authenticator parameters"); 159 | params->salt_size = salt_size; 160 | } else { 161 | params->salt = NULL; 162 | params->salt_size = 0; 163 | } 164 | 165 | // This data is required, but isn't meaninfully used, so we zero it out 166 | params->user_id = calloc(1, 1); 167 | params->user_id_size = 1; 168 | 169 | // CDH must be 32 bytes 170 | params->client_data_hash = 171 | malloc_or_exit(CLIENT_DATA_HASH_SIZE_BYTES, 172 | "client data hash in authenticator parameters"); 173 | params->client_data_hash_size = CLIENT_DATA_HASH_SIZE_BYTES; 174 | for (int i = 0; i < params->client_data_hash_size; i++) { 175 | params->client_data_hash[i] = 'A'; 176 | } 177 | 178 | // Empty null-terminated UTF-8 strings 179 | params->user_name = calloc(2, 1); 180 | params->user_name[0] = 'A'; 181 | params->user_display_name = calloc(2, 1); 182 | params->user_display_name[0] = 'A'; 183 | params->relying_party_name = calloc(2, 1); 184 | params->relying_party_name[0] = 'A'; 185 | params->authenticator_pin = NULL; 186 | 187 | return params; 188 | } 189 | 190 | /** 191 | * This function assumes all pointers are to malloc()'d memory 192 | * except relying_party_id, credential_id and salt, which must 193 | * be malloc()'d. 194 | */ 195 | void free_parameters(authenticator_parameters_t *params) { 196 | if (params == NULL) { 197 | return; 198 | } 199 | 200 | if (params->user_id != NULL) { 201 | free(params->user_id); 202 | } 203 | 204 | if (params->client_data_hash != NULL) { 205 | free(params->client_data_hash); 206 | } 207 | 208 | if (params->user_name != NULL) { 209 | free(params->user_name); 210 | } 211 | 212 | if (params->user_display_name != NULL) { 213 | free(params->user_display_name); 214 | } 215 | 216 | if (params->relying_party_name != NULL) { 217 | free(params->relying_party_name); 218 | } 219 | 220 | // The following parameters are secret 221 | if (params->relying_party_id != NULL) { 222 | sodium_memzero(params->relying_party_id, RELYING_PARTY_ID_SIZE); 223 | free(params->relying_party_id); 224 | } 225 | if (params->credential_id != NULL) { 226 | sodium_memzero(params->credential_id, params->credential_id_size); 227 | free(params->credential_id); 228 | } 229 | if (params->salt != NULL) { 230 | sodium_memzero(params->salt, params->salt_size); 231 | free(params->salt); 232 | } 233 | if (params->authenticator_pin != NULL) { 234 | sodium_memzero(params->authenticator_pin, 235 | strlen(params->authenticator_pin)); 236 | free(params->authenticator_pin); 237 | } 238 | free(params); 239 | } 240 | 241 | void create_credential(fido_dev_t *device, authenticator_parameters_t *params) { 242 | fido_cred_t *credential; 243 | const unsigned char *cred_id; 244 | size_t cred_id_size; 245 | int r; 246 | 247 | if ((credential = fido_cred_new()) == NULL) { 248 | errx(EXIT_OUT_OF_MEMORY, 249 | "Unable to create credential structure (out of memory?)"); 250 | } 251 | 252 | if ((r = fido_cred_set_extensions(credential, FIDO_EXT_HMAC_SECRET)) != 253 | FIDO_OK) { 254 | fido_cred_free(&credential); 255 | close_and_free_device_ignoring_errors(device); 256 | errx(EXIT_AUTHENTICATOR_ERROR, 257 | "Unable to set extension to hmac-secret: %s (0x%x)", 258 | fido_strerr(r), r); 259 | } 260 | 261 | if ((r = fido_cred_set_rp(credential, params->relying_party_id, 262 | params->relying_party_name)) != FIDO_OK) { 263 | fido_cred_free(&credential); 264 | close_and_free_device_ignoring_errors(device); 265 | errx(EXIT_AUTHENTICATOR_ERROR, "Unable to set relying party: %s (0x%x)", 266 | fido_strerr(r), r); 267 | } 268 | 269 | if ((r = fido_cred_set_type(credential, COSE_ES256)) != FIDO_OK) { 270 | fido_cred_free(&credential); 271 | close_and_free_device_ignoring_errors(device); 272 | errx(EXIT_AUTHENTICATOR_ERROR, 273 | "Unable to set credential type: %s (0x%x)", fido_strerr(r), r); 274 | } 275 | 276 | if ((r = fido_cred_set_user(credential, params->user_id, 277 | params->user_id_size, params->user_name, 278 | params->user_display_name, NULL)) != FIDO_OK) { 279 | fido_cred_free(&credential); 280 | close_and_free_device_ignoring_errors(device); 281 | errx(EXIT_AUTHENTICATOR_ERROR, "Unable to set user info: %s (0x%x)", 282 | fido_strerr(r), r); 283 | } 284 | 285 | if ((r = fido_cred_set_clientdata_hash(credential, params->client_data_hash, 286 | params->client_data_hash_size)) != 287 | FIDO_OK) { 288 | fido_cred_free(&credential); 289 | close_and_free_device_ignoring_errors(device); 290 | errx(EXIT_AUTHENTICATOR_ERROR, 291 | "Unable to set client data hash: %s (0x%x)", fido_strerr(r), r); 292 | } 293 | 294 | if ((r = fido_cred_set_rk(credential, FIDO_OPT_FALSE)) != FIDO_OK) { 295 | fido_cred_free(&credential); 296 | close_and_free_device_ignoring_errors(device); 297 | errx(EXIT_AUTHENTICATOR_ERROR, 298 | "Unable to disable use of resident key: %s (0x%x)", fido_strerr(r), 299 | r); 300 | } 301 | 302 | if ((r = fido_dev_make_cred(device, credential, 303 | params->authenticator_pin)) != FIDO_OK) { 304 | fido_cred_free(&credential); 305 | close_and_free_device_ignoring_errors(device); 306 | if (r == FIDO_ERR_PIN_INVALID) { 307 | errx(EXIT_BAD_PIN, "Invalid authenticator PIN"); 308 | } 309 | errx(EXIT_AUTHENTICATOR_ERROR, 310 | "Unable to create credential on FIDO2 device: %s (0x%x)", 311 | fido_strerr(r), r); 312 | } 313 | 314 | cred_id = fido_cred_id_ptr(credential); 315 | cred_id_size = fido_cred_id_len(credential); 316 | 317 | if (cred_id == NULL || cred_id_size < 1) { 318 | fido_cred_free(&credential); 319 | close_and_free_device_ignoring_errors(device); 320 | errx(EXIT_AUTHENTICATOR_ERROR, "Unable to read credential ID"); 321 | } 322 | 323 | params->credential_id = malloc_or_exit( 324 | cred_id_size, "credential id in authenticator parameters"); 325 | params->credential_id_size = cred_id_size; 326 | memcpy(params->credential_id, cred_id, cred_id_size); 327 | 328 | fido_cred_free(&credential); 329 | } 330 | 331 | int get_secret_from_authenticator_params( 332 | fido_dev_t *device, authenticator_parameters_t *params, 333 | secret_t *secret_struct) { // cred_id_t *cred_struct, unsigned char *salt, 334 | // size_t salt_length) { 335 | int r; 336 | const unsigned char *secret_pointer; 337 | size_t secret_size; 338 | fido_assert_t *assertion; 339 | 340 | if (params->credential_id == NULL || params->credential_id_size < 1) { 341 | close_and_free_device_ignoring_errors(device); 342 | errx(EXIT_PROGRAMMER_ERROR, "BUG (%s:%d): No credential ID supplied", 343 | __func__, __LINE__); 344 | } 345 | 346 | if (params->salt == NULL || params->salt_size < 1) { 347 | close_and_free_device_ignoring_errors(device); 348 | errx(EXIT_PROGRAMMER_ERROR, "BUG (%s:%d): No salt supplied", __func__, 349 | __LINE__); 350 | } 351 | 352 | if ((assertion = fido_assert_new()) == NULL) { 353 | free_parameters(params); 354 | close_and_free_device_ignoring_errors(device); 355 | errx(EXIT_OUT_OF_MEMORY, 356 | "Unable to create assertion structure (out of memory?)"); 357 | } 358 | 359 | if ((r = fido_assert_set_hmac_salt(assertion, params->salt, 360 | params->salt_size)) != FIDO_OK) { 361 | free_parameters(params); 362 | close_and_free_device_ignoring_errors(device); 363 | fido_assert_free(&assertion); 364 | errx(EXIT_AUTHENTICATOR_ERROR, 365 | "Unable to set extension to HMAC salt: %s (0x%x)", fido_strerr(r), 366 | r); 367 | } 368 | 369 | if ((r = fido_assert_set_extensions(assertion, FIDO_EXT_HMAC_SECRET)) != 370 | FIDO_OK) { 371 | free_parameters(params); 372 | close_and_free_device_ignoring_errors(device); 373 | fido_assert_free(&assertion); 374 | errx(EXIT_AUTHENTICATOR_ERROR, 375 | "Unable to set extension to hmac-secret: %s (0x%x)", 376 | fido_strerr(r), r); 377 | } 378 | 379 | if ((r = fido_assert_set_rp(assertion, params->relying_party_id)) != 380 | FIDO_OK) { 381 | free_parameters(params); 382 | close_and_free_device_ignoring_errors(device); 383 | fido_assert_free(&assertion); 384 | errx(EXIT_AUTHENTICATOR_ERROR, "Unable to set relying party: %s (0x%x)", 385 | fido_strerr(r), r); 386 | } 387 | 388 | if ((r = fido_assert_set_clientdata_hash( 389 | assertion, params->client_data_hash, 390 | params->client_data_hash_size)) != FIDO_OK) { 391 | free_parameters(params); 392 | close_and_free_device_ignoring_errors(device); 393 | fido_assert_free(&assertion); 394 | errx(EXIT_AUTHENTICATOR_ERROR, 395 | "Unable to set client data hash: %s (0x%x)", fido_strerr(r), r); 396 | } 397 | 398 | if ((r = fido_assert_allow_cred(assertion, params->credential_id, 399 | params->credential_id_size)) != FIDO_OK) { 400 | free_parameters(params); 401 | close_and_free_device_ignoring_errors(device); 402 | fido_assert_free(&assertion); 403 | errx(EXIT_AUTHENTICATOR_ERROR, "Unable to set credential ID: %s (0x%x)", 404 | fido_strerr(r), r); 405 | } 406 | 407 | if ((r = fido_assert_set_up(assertion, FIDO_OPT_TRUE)) != FIDO_OK) { 408 | free_parameters(params); 409 | close_and_free_device_ignoring_errors(device); 410 | fido_assert_free(&assertion); 411 | errx(EXIT_AUTHENTICATOR_ERROR, 412 | "Unable to run assert_set_up(): %s (0x%x)", fido_strerr(r), r); 413 | } 414 | 415 | r = fido_dev_get_assert(device, assertion, params->authenticator_pin); 416 | if (r != FIDO_OK) { 417 | fido_assert_free(&assertion); 418 | if (r == FIDO_ERR_INVALID_CREDENTIAL || 419 | r == FIDO_ERR_USER_ACTION_PENDING || r == FIDO_ERR_NO_CREDENTIALS || 420 | r == FIDO_ERR_ACTION_TIMEOUT || r == FIDO_ERR_PIN_INVALID) { 421 | return r; 422 | } 423 | free_parameters(params); 424 | close_and_free_device_ignoring_errors(device); 425 | errx(EXIT_AUTHENTICATOR_ERROR, 426 | "Unable to get secret from device: %s (0x%x)", fido_strerr(r), r); 427 | } 428 | 429 | secret_pointer = fido_assert_hmac_secret_ptr(assertion, 0); 430 | secret_size = fido_assert_hmac_secret_len(assertion, 0); 431 | 432 | if (secret_pointer == NULL || secret_size < 1) { 433 | close_and_free_device_ignoring_errors(device); 434 | fido_assert_free(&assertion); 435 | errx(EXIT_AUTHENTICATOR_ERROR, "Unable to read credential ID"); 436 | } 437 | 438 | secret_struct->secret_size = secret_size; 439 | secret_struct->secret = 440 | malloc_or_exit(secret_struct->secret_size, "secret"); 441 | memcpy(secret_struct->secret, secret_pointer, secret_size); 442 | fido_assert_free(&assertion); 443 | 444 | return FIDO_OK; 445 | } 446 | 447 | void free_secret(secret_t *secret_struct) { 448 | if (secret_struct == NULL) { 449 | return; 450 | } 451 | if (secret_struct->secret != NULL) { 452 | free(secret_struct->secret); 453 | } 454 | free(secret_struct); 455 | } 456 | -------------------------------------------------------------------------------- /src/cryptography.c: -------------------------------------------------------------------------------- 1 | #include "cryptography.h" 2 | 3 | #include "exit.h" 4 | #include "invocation.h" 5 | #include "memory.h" 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | unsigned char *derive_key(key_spec_t *key_spec) { 12 | if (key_spec->kdf_salt_size != crypto_pwhash_SALTBYTES) { 13 | err(EXIT_PROGRAMMER_ERROR, 14 | "KDF salt is of wrong size (is %zu bytes, should be %d bytes)", 15 | key_spec->kdf_salt_size, crypto_pwhash_SALTBYTES); 16 | } 17 | 18 | unsigned char *key_bytes = 19 | malloc_or_exit(KEY_SIZE, "passphrase-derived key"); 20 | 21 | if (crypto_pwhash(key_bytes, KEY_SIZE, key_spec->passphrase, 22 | strlen(key_spec->passphrase), key_spec->kdf_salt, 23 | key_spec->opslimit, key_spec->memlimit, 24 | key_spec->algorithm) != 0) { 25 | err(EXIT_OUT_OF_MEMORY, 26 | "Unable to derive key from passphrase (out of memory?)"); 27 | } 28 | 29 | return key_bytes; 30 | } 31 | 32 | void free_key(unsigned char *key) { 33 | if (key == NULL) { 34 | return; 35 | } 36 | sodium_memzero(key, KEY_SIZE); 37 | free(key); 38 | } 39 | 40 | key_spec_t * 41 | make_key_spec_from_passphrase_and_cleartext(char *passphrase, 42 | deserialized_cleartext *cleartext) { 43 | key_spec_t *keyspec = malloc_or_exit( 44 | sizeof(key_spec_t), "password-derived key specificications"); 45 | keyspec->passphrase = strdup_or_exit( 46 | passphrase, "passphrase in password-derived key specificications"); 47 | keyspec->opslimit = cleartext->opslimit; 48 | keyspec->memlimit = cleartext->memlimit; 49 | keyspec->algorithm = cleartext->algorithm; 50 | keyspec->kdf_salt = 51 | malloc_or_exit(cleartext->kdf_salt_size, 52 | "salt in password-derived key specificications"); 53 | memcpy(keyspec->kdf_salt, cleartext->kdf_salt, cleartext->kdf_salt_size); 54 | keyspec->kdf_salt_size = cleartext->kdf_salt_size; 55 | 56 | return keyspec; 57 | } 58 | 59 | key_spec_t *make_new_key_spec_from_invocation(invocation_state_t *invocation) { 60 | key_spec_t *keyspec = malloc_or_exit( 61 | sizeof(key_spec_t), "password-derived key specificications"); 62 | keyspec->passphrase = 63 | strdup_or_exit(invocation->passphrase, 64 | "passphrase in password-derived key specificications"); 65 | 66 | switch (invocation->kdf_hardness) { 67 | case kdf_hardness_low: 68 | keyspec->opslimit = crypto_pwhash_OPSLIMIT_INTERACTIVE; 69 | keyspec->memlimit = crypto_pwhash_MEMLIMIT_INTERACTIVE; 70 | break; 71 | case kdf_hardness_medium: 72 | keyspec->opslimit = crypto_pwhash_OPSLIMIT_MODERATE; 73 | keyspec->memlimit = crypto_pwhash_MEMLIMIT_MODERATE; 74 | break; 75 | case kdf_hardness_high: 76 | keyspec->opslimit = crypto_pwhash_OPSLIMIT_SENSITIVE; 77 | keyspec->memlimit = crypto_pwhash_MEMLIMIT_SENSITIVE; 78 | break; 79 | case kdf_hardness_unspecified: 80 | case kdf_hardness_invalid: 81 | errx(EXIT_PROGRAMMER_ERROR, 82 | "BUG (%s:%d): invalid KDF hardness passed in (%d)\n", __func__, 83 | __LINE__, invocation->kdf_hardness); 84 | break; 85 | } 86 | 87 | if (keyspec->opslimit < 3) { 88 | // opslimit must be at least 3 because we're using Argon2i: 89 | // https://download.libsodium.org/doc/password_hashing/default_phf#notes 90 | keyspec->opslimit = 3; 91 | } 92 | 93 | keyspec->algorithm = crypto_pwhash_ALG_ARGON2I13; 94 | keyspec->kdf_salt = 95 | malloc_or_exit(crypto_pwhash_SALTBYTES, 96 | "salt in password-derived key specificications"); 97 | randombytes_buf(keyspec->kdf_salt, crypto_pwhash_SALTBYTES); 98 | keyspec->kdf_salt_size = crypto_pwhash_SALTBYTES; 99 | 100 | return keyspec; 101 | } 102 | 103 | void free_key_spec(key_spec_t *spec) { 104 | if (spec == NULL) { 105 | return; 106 | } 107 | if (spec->passphrase != NULL) { 108 | sodium_memzero(spec->passphrase, strlen(spec->passphrase)); 109 | free(spec->passphrase); 110 | } 111 | if (spec->kdf_salt != NULL) { 112 | free(spec->kdf_salt); 113 | } 114 | free(spec); 115 | } 116 | -------------------------------------------------------------------------------- /src/enrol.c: -------------------------------------------------------------------------------- 1 | #include "enrol.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "exit.h" 9 | #include "files.h" 10 | #include "memory.h" 11 | #include "serialization.h" 12 | 13 | void enrol_device(invocation_state_t *invocation) { 14 | fido_dev_t *authenticator; 15 | authenticator_parameters_t *authenticator_params; 16 | deserialized_cleartext *cleartext; 17 | 18 | authenticator = get_device(invocation->device); 19 | fido_cbor_info_t *device_info = get_device_info(authenticator); 20 | if (!device_supports_hmac_secret(device_info)) { 21 | free_device_info(device_info); 22 | errx(EXIT_AUTHENTICATOR_ERROR, 23 | "Device at %s does not support the required hmac-secret extension", 24 | invocation->device); 25 | } 26 | 27 | authenticator_params = allocate_parameters_except_rpid(0, SALT_SIZE_BYTES); 28 | randombytes_buf(authenticator_params->salt, SALT_SIZE_BYTES); 29 | 30 | authenticator_params->relying_party_id = 31 | malloc_or_exit(RELYING_PARTY_ID_SIZE + RELYING_PARTY_SUFFIX_SIZE + 1, 32 | "relying party id in authenticator parameters"); 33 | for (int i = 0; i < RELYING_PARTY_ID_SIZE; i++) { 34 | authenticator_params->relying_party_id[i] = 35 | RPID_ENCODING_TABLE[randombytes_uniform(RPID_ENCODING_TABLE_SIZE)]; 36 | } 37 | authenticator_params->relying_party_id[RELYING_PARTY_ID_SIZE] = (char)0; 38 | strncat(authenticator_params->relying_party_id, RELYING_PARTY_SUFFIX, 39 | RELYING_PARTY_SUFFIX_SIZE + 1); 40 | 41 | if (fido_dev_has_pin(authenticator)) { 42 | authenticator_params->authenticator_pin = malloc_or_exit( 43 | LONGEST_VALID_PIN + 1, "authenticator PIN in enrol_device"); 44 | if (invocation->authenticator_pin == NULL) { 45 | prompt_for_secret("authenticator PIN", LONGEST_VALID_PIN, 46 | authenticator_params->authenticator_pin); 47 | } else { 48 | strncpy(authenticator_params->authenticator_pin, 49 | invocation->authenticator_pin, LONGEST_VALID_PIN); 50 | } 51 | 52 | if (strlen(authenticator_params->authenticator_pin) == 0) { 53 | free_device_info(device_info); 54 | free_parameters(authenticator_params); 55 | errx(EXIT_BAD_PIN, "No PIN specified, unable to continue."); 56 | } 57 | } 58 | 59 | create_credential(authenticator, authenticator_params); 60 | close_and_free_device_ignoring_errors(authenticator); 61 | 62 | key_spec_t *key_spec = make_new_key_spec_from_invocation(invocation); 63 | cleartext = 64 | build_deserialized_cleartext_from_authenticator_parameters_and_key_spec( 65 | authenticator_params, key_spec); 66 | free_key_spec(key_spec); 67 | 68 | cleartext->device_aaguid_size = fido_cbor_info_aaguid_len(device_info); 69 | cleartext->device_aaguid = 70 | malloc_or_exit(cleartext->device_aaguid_size, "device AAGUID"); 71 | memcpy(cleartext->device_aaguid, fido_cbor_info_aaguid_ptr(device_info), 72 | cleartext->device_aaguid_size); 73 | free_device_info(device_info); 74 | free_parameters(authenticator_params); 75 | authenticator_params = NULL; 76 | // We no longer need the passphrase or PIN, so zero it out, even though 77 | // we'll need the rest of invocation later. 78 | sodium_memzero(invocation->passphrase, strlen(invocation->passphrase)); 79 | if (invocation->authenticator_pin != NULL) { 80 | sodium_memzero(invocation->authenticator_pin, 81 | strlen(invocation->authenticator_pin)); 82 | } 83 | 84 | encoded_file *f = write_cleartext(cleartext, invocation->file); 85 | write_file(f); 86 | free_encoded_file(f); 87 | 88 | free_cleartext(cleartext); 89 | } 90 | -------------------------------------------------------------------------------- /src/enumerate.c: -------------------------------------------------------------------------------- 1 | #include "enumerate.h" 2 | 3 | #include 4 | #include 5 | 6 | #include "authenticator.h" 7 | #include "exit.h" 8 | 9 | void print_devices_list(devices_list_t *devices_list) { 10 | for (size_t i = 0; i < devices_list->count; i++) { 11 | const fido_dev_info_t *device_info = 12 | fido_dev_info_ptr(devices_list->list, i); 13 | fido_dev_t *authenticator = 14 | get_device_even_if_not_fido2(fido_dev_info_path(device_info)); 15 | 16 | fido_cbor_info_t *ctap_info = get_device_info(authenticator); 17 | 18 | bool device_supported = fido_dev_is_fido2(authenticator) && 19 | device_supports_hmac_secret(ctap_info); 20 | 21 | printf("%s\t", device_supported ? " " : "!"); 22 | 23 | printf("%s\t", fido_dev_info_path(device_info)); 24 | 25 | printf("%s %s\t", fido_dev_info_manufacturer_string(device_info), 26 | fido_dev_info_product_string(device_info)); 27 | 28 | print_device_aaguid(ctap_info); 29 | printf("\n"); 30 | 31 | free_device_info(ctap_info); 32 | close_and_free_device_ignoring_errors(authenticator); 33 | } 34 | 35 | if (devices_list->count == 0) { 36 | free_devices_list(devices_list); 37 | errx(EXIT_NO_DEVICES, "No devices found"); 38 | } 39 | } 40 | 41 | void print_device_aaguid(fido_cbor_info_t *ctap_info) { 42 | const unsigned char *device_aaguid = fido_cbor_info_aaguid_ptr(ctap_info); 43 | size_t device_aaguid_size = fido_cbor_info_aaguid_len(ctap_info); 44 | 45 | for (size_t i = 0; i < device_aaguid_size; i++) { 46 | printf("%02x", device_aaguid[i]); 47 | // Add separators for GUID, two characters per byte: 48 | // 0 1 49 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 50 | // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 51 | // NOLINTNEXTLINE(readability-magic-numbers) 52 | if (i == 3 || i == 5 || i == 7 || i == 9) { 53 | printf("-"); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/files.c: -------------------------------------------------------------------------------- 1 | #include "files.h" 2 | #include "exit.h" 3 | #include "memory.h" 4 | #include 5 | #include 6 | 7 | encoded_file *read_file(const char *path) { 8 | encoded_file *result = 9 | malloc_or_exit(sizeof(encoded_file), "encoded file structure"); 10 | 11 | long int ftell_result; 12 | 13 | FILE *fp = fopen(path, "r"); 14 | if (fp == NULL) { 15 | errx(EXIT_DESERIALIZATION_ERROR, "Unable to open file at %s", path); 16 | } 17 | 18 | if (fseek(fp, 0, SEEK_END) != 0) { 19 | errx(EXIT_DESERIALIZATION_ERROR, "Unable to seek to end of file at %s", 20 | path); 21 | } 22 | 23 | if ((ftell_result = ftell(fp)) < 0) { 24 | errx(EXIT_DESERIALIZATION_ERROR, "Unable to get size of file at %s", 25 | path); 26 | } 27 | size_t length = (size_t)ftell_result; 28 | 29 | if (fseek(fp, 0, SEEK_SET) != 0) { 30 | errx(EXIT_DESERIALIZATION_ERROR, 31 | "Unable to seek to start of file at %s", path); 32 | } 33 | 34 | if (length > LARGEST_VALID_PAYLOAD_SIZE_BYTES) { 35 | errx(EXIT_DESERIALIZATION_ERROR, 36 | "File at %s is too big (more than %d bytes); refusing to load it", 37 | path, LARGEST_VALID_PAYLOAD_SIZE_BYTES); 38 | } 39 | 40 | unsigned char *buffer = 41 | malloc_or_exit(length, "buffer for reading keyfile"); 42 | 43 | if (fread(buffer, length, 1, fp) != 1) { 44 | errx(EXIT_DESERIALIZATION_ERROR, 45 | "Unable to read file at %s into buffer", path); 46 | } 47 | 48 | fclose(fp); 49 | 50 | size_t path_size_including_null = strlen(path) + 1; 51 | result->path = 52 | malloc_or_exit(path_size_including_null, "encoded file path"); 53 | strncpy(result->path, path, path_size_including_null); 54 | result->data = buffer; 55 | result->length = length; 56 | 57 | return result; 58 | } 59 | 60 | void write_file(encoded_file *file) { 61 | FILE *fp = fopen(file->path, "w"); 62 | 63 | if (fp == NULL) { 64 | errx(EXIT_DESERIALIZATION_ERROR, "Unable to open file at %s", 65 | file->path); 66 | } 67 | 68 | if (fseek(fp, 0, SEEK_SET) != 0) { 69 | errx(EXIT_DESERIALIZATION_ERROR, 70 | "Unable to seek to start of file at %s", file->path); 71 | } 72 | 73 | if (fwrite(file->data, file->length, 1, fp) != 1) { 74 | errx(EXIT_DESERIALIZATION_ERROR, "Unable to write file at %s", 75 | file->path); 76 | } 77 | 78 | fclose(fp); 79 | } 80 | 81 | void free_encoded_file(encoded_file *file) { 82 | if (file->path) { 83 | free(file->path); 84 | } 85 | if (file->data) { 86 | free(file->data); 87 | } 88 | free(file); 89 | } 90 | -------------------------------------------------------------------------------- /src/generate.c: -------------------------------------------------------------------------------- 1 | #include "generate.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "cryptography.h" 8 | #include "exit.h" 9 | #include "files.h" 10 | #include "memory.h" 11 | #include "serialization.h" 12 | 13 | unsigned short int 14 | print_secret_consuming_invocation(invocation_state_t *invocation, 15 | devices_list_t *devices_list) { 16 | encoded_file *f = read_file(invocation->file); 17 | deserialized_cleartext *cleartext = load_cleartext(f); 18 | free_encoded_file(f); 19 | 20 | key_spec_t *key_spec = make_key_spec_from_passphrase_and_cleartext( 21 | invocation->passphrase, cleartext); 22 | unsigned char *key_bytes = derive_key(key_spec); 23 | free_key_spec(key_spec); 24 | key_spec = NULL; 25 | authenticator_parameters_t *authenticator_params = 26 | build_authenticator_parameters_from_deserialized_cleartext_and_key_and_mixin( 27 | cleartext, key_bytes, invocation->mixin); 28 | 29 | // Clean up things we don't need anymore 30 | free_key(key_bytes); 31 | key_bytes = NULL; 32 | 33 | for (size_t i = 0; i < devices_list->count; i++) { 34 | const fido_dev_info_t *di = fido_dev_info_ptr(devices_list->list, i); 35 | const char *authenticator_path = fido_dev_info_path(di); 36 | const char *authenticator_product_string = 37 | fido_dev_info_product_string(di); 38 | fido_dev_t *authenticator = get_device(authenticator_path); 39 | fido_cbor_info_t *device_info = get_device_info(authenticator); 40 | if (device_aaguid_matches(cleartext, device_info)) { 41 | if (!device_supports_hmac_secret(device_info)) { 42 | close_and_free_device_ignoring_errors(authenticator); 43 | free_device_info(device_info); 44 | continue; 45 | } 46 | 47 | bool authenticator_has_pin = fido_dev_has_pin(authenticator); 48 | 49 | if (authenticator_has_pin) { 50 | authenticator_params->authenticator_pin = malloc_or_exit( 51 | LONGEST_VALID_PIN + 1, "authenticator PIN in enrol_device"); 52 | const char *prompt_format_string = 53 | "authenticator PIN for %s at %s"; 54 | char *prompt_string = 55 | malloc_or_exit(strlen(prompt_format_string) + 56 | strlen(authenticator_product_string) + 57 | strlen(authenticator_path) + 1, 58 | "PIN prompt"); 59 | sprintf(prompt_string, prompt_format_string, 60 | authenticator_product_string, authenticator_path); 61 | 62 | if (invocation->authenticator_pin == NULL) { 63 | prompt_for_secret(prompt_string, LONGEST_VALID_PIN, 64 | authenticator_params->authenticator_pin); 65 | } else { 66 | strncpy(authenticator_params->authenticator_pin, 67 | invocation->authenticator_pin, LONGEST_VALID_PIN); 68 | } 69 | free(prompt_string); 70 | prompt_string = NULL; 71 | 72 | if (strlen(authenticator_params->authenticator_pin) == 0) { 73 | fprintf(stderr, 74 | "No PIN entered; skipping this authenticator.\n"); 75 | close_and_free_device_ignoring_errors(authenticator); 76 | free_device_info(device_info); 77 | continue; 78 | } 79 | } 80 | 81 | secret_t *secret = malloc_or_exit(sizeof(secret_t), "secret"); 82 | secret->secret = NULL; 83 | secret->secret_size = 0; 84 | int result = get_secret_from_authenticator_params( 85 | authenticator, authenticator_params, secret); 86 | close_and_free_device_ignoring_errors(authenticator); 87 | free_device_info(device_info); 88 | if (result == FIDO_OK) { 89 | for (int j = 0; j < secret->secret_size; j++) { 90 | printf("%02x", secret->secret[j]); 91 | } 92 | printf("\n"); 93 | fflush(stdout); 94 | free_parameters(authenticator_params); 95 | authenticator_params = NULL; 96 | 97 | free_cleartext(cleartext); 98 | cleartext = NULL; 99 | 100 | free_secret(secret); 101 | secret = NULL; 102 | return EXIT_SUCCESS; 103 | } 104 | free_secret(secret); 105 | secret = NULL; 106 | switch (result) { 107 | case FIDO_ERR_NO_CREDENTIALS: 108 | // no warning here 109 | break; 110 | case FIDO_ERR_PIN_INVALID: 111 | warnx("Invalid PIN for %s at %s", 112 | fido_dev_info_product_string(di), authenticator_path); 113 | break; 114 | default: 115 | warnx("%s at %s did not return a valid secret: %s (0x%x)", 116 | fido_dev_info_product_string(di), authenticator_path, 117 | fido_strerr(result), result); 118 | break; 119 | } 120 | } 121 | } 122 | 123 | free_invocation(invocation); 124 | invocation = NULL; 125 | 126 | free_parameters(authenticator_params); 127 | authenticator_params = NULL; 128 | 129 | free_cleartext(cleartext); 130 | cleartext = NULL; 131 | 132 | if (devices_list->count > 0) { 133 | return EXIT_NO_VALID_AUTHENTICATOR; 134 | } 135 | 136 | return EXIT_NO_DEVICES; 137 | } 138 | 139 | bool device_aaguid_matches(deserialized_cleartext *cleartext, 140 | fido_cbor_info_t *device_info) { 141 | if (cleartext->device_aaguid_size == 0) { 142 | return true; 143 | } 144 | 145 | size_t this_device_aaguid_size = fido_cbor_info_aaguid_len(device_info); 146 | 147 | if (this_device_aaguid_size != cleartext->device_aaguid_size) { 148 | return false; 149 | } 150 | 151 | unsigned char *this_device_aaguid = 152 | malloc_or_exit(cleartext->device_aaguid_size, "device AAGUID"); 153 | memcpy(this_device_aaguid, fido_cbor_info_aaguid_ptr(device_info), 154 | this_device_aaguid_size); 155 | 156 | for (size_t i = 0; i < cleartext->device_aaguid_size; i++) { 157 | if (cleartext->device_aaguid[i] != this_device_aaguid[i]) { 158 | free(this_device_aaguid); 159 | return false; 160 | } 161 | } 162 | 163 | free(this_device_aaguid); 164 | return true; 165 | } 166 | -------------------------------------------------------------------------------- /src/help.c: -------------------------------------------------------------------------------- 1 | #include "help.h" 2 | 3 | #include 4 | #include 5 | 6 | void print_version(void) { printf("%s %s\n", APPNAME, APPVERSION); } 7 | 8 | void print_usage(char *program_name) { 9 | char *program_basename = strrchr(program_name, '/'); 10 | if (program_basename != NULL && program_basename[1] != (char)0) { 11 | program_name = program_basename + 1; 12 | } 13 | printf( // clang-format off 14 | "Usage: %s help\n" 15 | " %s version\n" 16 | " %s enumerate\n" 17 | " %s generate -f [-p | -r ]\n" 18 | " %*s [-n ] [-m ]\n" 19 | " %s enrol -d -f [-p | -r ]\n" 20 | " %*s [-n ] [-o] [-k ]\n", 21 | // clang-format on 22 | program_name, program_name, program_name, program_name, 23 | (int)strlen(program_name), " ", program_name, (int)strlen(program_name), 24 | " "); 25 | } 26 | 27 | void print_help(char *program_name) { 28 | print_usage(program_name); 29 | printf( 30 | "%s", 31 | // clang-format off 32 | // This has manually-inserted hard wraps at 80 characters, 33 | // which is inconsistent with clang-format. 34 | "\n" 35 | "help print this screen and exit.\n" 36 | "\n" 37 | "version print version and exit.\n" 38 | "\n" 39 | "enumerate show a list of authenticator devices currently connected.\n" 40 | "\n" 41 | "enrol create or overwrite with randomly-generated data required\n" 42 | " to produce a secret for the given passphrase.\n" 43 | "\n" 44 | "generate generate an HMAC across the data contained in , once it has\n" 45 | " been decrypted with the given passphrase.\n" 46 | "\n" 47 | " -d, --device REQUIRED for enrol. The path to the\n" 48 | " authenticator to enrol, e.g. /dev/hidraw0.\n" 49 | " This device MUST support the FIDO2\n" 50 | " hmac-secret extension (supported by most \n" 51 | " Yubico Security Keys and YubiKeys).\n" 52 | "\n" 53 | " -f, --file REQUIRED for enrol or generate. The file to\n" 54 | " write to (for enrol; this file will be\n" 55 | " overwritten), or read from (for generate).\n" 56 | "\n" 57 | " -p, --passphrase The passphrase to use. If neither this nor\n" 58 | " neither this nor --passphrase-file are\n" 59 | " specified, you will be prompted for a\n" 60 | " passphrase.\n" 61 | "\n" 62 | " -r, --passphrase-file A file containing the passphrase to use.\n" 63 | " Note that the whole file will be used,\n" 64 | " including any trailing newline. If\n" 65 | " neither this nor --passphrase are\n" 66 | " specified, you will be prompted for a\n" 67 | " passphrase.\n" 68 | "\n" 69 | " -n, --pin The authenticator PIN to use. If not\n" 70 | " specified, and your device requires it,\n" 71 | " you will be prompted for a PIN.\n" 72 | "\n" 73 | " -o, --obfuscate-device-info If specified for enrol, do not store the.\n" 74 | " device vendor and product ID in .\n" 75 | "\n" 76 | " -k, --kdf-hardness Specify the complexity of the key derivation\n" 77 | " function used to derive a cryptographic key\n" 78 | " from . Valid options are high,\n" 79 | " medium or low. If not specified, a value\n" 80 | " will be chosen automatically based on\n" 81 | " total system RAM.\n" 82 | "\n" 83 | " -m, --mixin Combine with the encrypted salt,\n" 84 | " so that the returned value depends on it.\n" 85 | " Note that setting to an empty\n" 86 | " string behaves differently to not using\n" 87 | " this argument at all.\n" 88 | "\n" 89 | "The output of this program on STDOUT (in either enrol or generate mode) will be\n" 90 | "a sequence of printable, URL-safe ASCII characters, that depend on the\n" 91 | "randomly generated parameters placed in the file, the authenticator device and\n" 92 | "the passphrase. This will be followed by a single newline.\n" 93 | // clang-format on 94 | ); 95 | } 96 | -------------------------------------------------------------------------------- /src/invocation.c: -------------------------------------------------------------------------------- 1 | #include "invocation.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "exit.h" 14 | #include "files.h" 15 | #include "help.h" 16 | #include "memory.h" 17 | 18 | invocation_state_t *parse_arguments_and_get_passphrase(int argc, char **argv) { 19 | if (argc < 2) { 20 | print_usage(argv[0]); 21 | exit(EXIT_BAD_INVOCATION); 22 | } 23 | 24 | invocation_state_t *result = 25 | malloc_or_exit(sizeof(invocation_state_t), "invocation state"); 26 | result->device = NULL; 27 | result->file = NULL; 28 | result->passphrase = NULL; 29 | result->authenticator_pin = NULL; 30 | result->obfuscate_device_info = false; 31 | result->kdf_hardness = kdf_hardness_unspecified; 32 | result->mixin = NULL; 33 | 34 | if (strcmp(argv[1], "help") == 0) { 35 | result->subcommand = subcommand_help; 36 | } else if (strcmp(argv[1], "version") == 0) { 37 | result->subcommand = subcommand_version; 38 | } else if (strcmp(argv[1], "enrol") == 0) { 39 | result->subcommand = subcommand_enrol; 40 | } else if (strcmp(argv[1], "generate") == 0) { 41 | result->subcommand = subcommand_generate; 42 | } else if (strcmp(argv[1], "enumerate") == 0) { 43 | result->subcommand = subcommand_enumerate; 44 | } else { 45 | print_usage(argv[0]); 46 | exit(EXIT_BAD_INVOCATION); 47 | } 48 | 49 | int c; 50 | bool invalid_invocation = false; 51 | while (1) { 52 | static struct option long_options[] = { 53 | {"device", required_argument, 0, 'd'}, 54 | {"file", required_argument, 0, 'f'}, 55 | {"passphrase", required_argument, 0, 'p'}, 56 | {"passphrase-file", required_argument, 0, 'r'}, 57 | {"pin", required_argument, 0, 'n'}, 58 | {"mixin", required_argument, 0, 'm'}, 59 | {"kdf-hardness", required_argument, 0, 'k'}, 60 | {"obfuscate-device", no_argument, 0, 'o'}, 61 | {"help", no_argument, 0, 'h'}, 62 | {NULL, 0, NULL, 0}, 63 | }; 64 | 65 | /* getopt_long stores the option index here. */ 66 | int option_index = 0; 67 | 68 | c = getopt_long(argc, argv, "d:f:p:r:m:k:n:oh", long_options, 69 | &option_index); 70 | 71 | if (c == -1) { 72 | break; 73 | } 74 | 75 | switch (LOWERCASE(c)) { 76 | case 'd': 77 | result->device = 78 | strdup_or_exit(optarg, "device path in invocation state"); 79 | break; 80 | 81 | case 'f': 82 | result->file = 83 | strdup_or_exit(optarg, "file path in invocation state"); 84 | break; 85 | 86 | case 'p': 87 | result->passphrase = 88 | strndup_or_exit(optarg, LONGEST_VALID_PASSPHRASE, 89 | "passphrase in invocation state"); 90 | break; 91 | 92 | case 'r': { 93 | encoded_file *f = read_file(optarg); 94 | result->passphrase = strndup_or_exit( 95 | (const char *)f->data, 96 | f->length > LONGEST_VALID_PASSPHRASE ? LONGEST_VALID_PASSPHRASE 97 | : f->length, 98 | "passphrase in invocation state"); 99 | free_encoded_file(f); 100 | } break; 101 | 102 | case 'n': 103 | result->authenticator_pin = 104 | strndup_or_exit(optarg, LONGEST_VALID_PIN, 105 | "authenticator PIN in invocation state"); 106 | break; 107 | 108 | case 'm': 109 | result->mixin = 110 | strdup_or_exit(optarg, "mixin data in invocation state"); 111 | break; 112 | 113 | case 'k': 114 | switch (LOWERCASE(optarg[0])) { 115 | case 'l': 116 | result->kdf_hardness = kdf_hardness_low; 117 | break; 118 | case 'm': 119 | result->kdf_hardness = kdf_hardness_medium; 120 | break; 121 | case 'h': 122 | result->kdf_hardness = kdf_hardness_high; 123 | break; 124 | default: 125 | result->kdf_hardness = kdf_hardness_invalid; 126 | break; 127 | } 128 | break; 129 | 130 | case 'o': 131 | result->obfuscate_device_info = true; 132 | break; 133 | 134 | case 'h': 135 | result->subcommand = subcommand_help; 136 | break; 137 | 138 | default: 139 | invalid_invocation = true; 140 | break; 141 | } 142 | } 143 | 144 | if (result->subcommand == subcommand_unknown && optind < argc) { 145 | if (strcmp(argv[optind], "help") == 0) { 146 | result->subcommand = subcommand_help; 147 | } else if (strcmp(argv[optind], "enrol") == 0) { 148 | result->subcommand = subcommand_enrol; 149 | } else if (strcmp(argv[optind], "generate") == 0) { 150 | result->subcommand = subcommand_generate; 151 | } 152 | } 153 | 154 | // Add 1 to optind to take account of the subcommand, if we've already seen 155 | // it 156 | optind += (result->subcommand == subcommand_unknown) ? 0 : 1; 157 | int extra_args = argc - optind; 158 | 159 | if (extra_args > 0) { 160 | char *program_name = strrchr(argv[0], '/'); 161 | if (program_name == NULL || program_name[1] == (char)0) { 162 | program_name = argv[0]; 163 | } else { 164 | program_name += 1; 165 | } 166 | fprintf(stderr, "%s: unrecognized argument%s -- ", program_name, 167 | extra_args > 1 ? "s" : ""); 168 | 169 | for (int i = optind; i < argc; i++) { 170 | fprintf(stderr, "'%s'%s", argv[i], i < (argc - 1) ? " " : "\n"); 171 | } 172 | 173 | invalid_invocation = true; 174 | } 175 | 176 | // Required arguments 177 | switch (result->subcommand) { 178 | case subcommand_enrol: 179 | invalid_invocation = invalid_invocation || result->device == NULL || 180 | result->file == NULL || result->mixin != NULL || 181 | result->kdf_hardness == kdf_hardness_invalid; 182 | break; 183 | case subcommand_generate: 184 | invalid_invocation = invalid_invocation || result->device != NULL || 185 | result->file == NULL || 186 | result->obfuscate_device_info || 187 | result->kdf_hardness != kdf_hardness_unspecified; 188 | break; 189 | case subcommand_enumerate: 190 | case subcommand_help: 191 | case subcommand_version: 192 | default: 193 | invalid_invocation = invalid_invocation || result->device != NULL || 194 | result->file != NULL || result->mixin != NULL || 195 | result->passphrase != NULL || 196 | result->obfuscate_device_info || 197 | result->kdf_hardness != kdf_hardness_unspecified; 198 | break; 199 | } 200 | 201 | if (result->subcommand != subcommand_help && invalid_invocation) { 202 | free_invocation(result); 203 | print_usage(argv[0]); 204 | exit(EXIT_BAD_INVOCATION); 205 | } 206 | 207 | if (result->subcommand == subcommand_enrol && 208 | result->kdf_hardness == kdf_hardness_unspecified) { 209 | long pages = sysconf(_SC_PHYS_PAGES); 210 | long page_size = sysconf(_SC_PAGE_SIZE); 211 | size_t available_memory = pages * page_size; 212 | if (available_memory > (crypto_pwhash_MEMLIMIT_SENSITIVE * 2)) { 213 | result->kdf_hardness = kdf_hardness_high; 214 | } else if (available_memory > (crypto_pwhash_MEMLIMIT_MODERATE * 2)) { 215 | result->kdf_hardness = kdf_hardness_medium; 216 | } else { 217 | result->kdf_hardness = kdf_hardness_low; 218 | } 219 | } 220 | 221 | if (result->subcommand == subcommand_enrol || 222 | result->subcommand == subcommand_generate) { 223 | if (result->passphrase == NULL) { 224 | result->passphrase = 225 | malloc_or_exit(LONGEST_VALID_PASSPHRASE + 1, "passphrase"); 226 | prompt_for_secret("passphrase", LONGEST_VALID_PASSPHRASE, 227 | result->passphrase); 228 | } 229 | } 230 | 231 | return result; 232 | } 233 | 234 | void prompt_for_secret(const char *description, size_t maximum_size, 235 | char *result) { 236 | if (isatty(STDIN_FILENO)) { 237 | struct termios terminal_settings; 238 | if (tcgetattr(STDIN_FILENO, &terminal_settings) != 0) { 239 | err(EXIT_UNABLE_TO_GET_USER_SECRET, "Unable to get %s", 240 | description); 241 | } 242 | tcflag_t previous_c_lflag = terminal_settings.c_lflag; 243 | terminal_settings.c_lflag &= ~(ECHO | ECHOE | ECHOK); 244 | terminal_settings.c_lflag |= ECHONL; 245 | if (tcsetattr(STDIN_FILENO, TCSANOW, &terminal_settings) != 0) { 246 | err(EXIT_UNABLE_TO_GET_USER_SECRET, "Unable to get %s", 247 | description); 248 | } 249 | fprintf(stderr, "%c%s: ", UPPERCASE(description[0]), description + 1); 250 | if (fgets(result, maximum_size, stdin) == NULL) { 251 | errx(EXIT_UNABLE_TO_GET_USER_SECRET, 252 | "Unable to get %s on STDIN: fgets error 0x%02x", description, 253 | ferror(stdin)); 254 | } 255 | 256 | // Remove trailing \n 257 | if (strlen(result) > 0 && 258 | result[strlen(result) - 1] == NL_CHARACTER_TO_STRIP) { 259 | result[strlen(result) - 1] = 0x00; 260 | } 261 | 262 | // Reset settings 263 | terminal_settings.c_lflag = previous_c_lflag; 264 | if (tcsetattr(STDIN_FILENO, TCSANOW, &terminal_settings) != 0) { 265 | errx(EXIT_UNABLE_TO_GET_USER_SECRET, 266 | "Unable to reset terminal after getting %s", description); 267 | } 268 | 269 | } else if (errno == ENOTTY) { 270 | if (fgets(result, maximum_size, stdin) == NULL) { 271 | errx(EXIT_UNABLE_TO_GET_USER_SECRET, 272 | "Unable to get %s on STDIN: fgets error 0x%02x", description, 273 | ferror(stdin)); 274 | } 275 | 276 | // Remove trailing \n 277 | if (result[strlen(result) - 1] == NL_CHARACTER_TO_STRIP) { 278 | result[strlen(result) - 1] = 0x00; 279 | } 280 | 281 | } else { 282 | err(EXIT_UNABLE_TO_GET_USER_SECRET, "Unable to get %s", description); 283 | } 284 | } 285 | 286 | void free_invocation(invocation_state_t *invocation) { 287 | if (invocation == NULL) { 288 | return; 289 | } 290 | 291 | if (invocation->passphrase != NULL) { 292 | sodium_memzero(invocation->passphrase, strlen(invocation->passphrase)); 293 | free(invocation->passphrase); 294 | } 295 | 296 | if (invocation->mixin != NULL) { 297 | free(invocation->mixin); 298 | } 299 | 300 | if (invocation->device != NULL) { 301 | free(invocation->device); 302 | } 303 | 304 | if (invocation->file != NULL) { 305 | free(invocation->file); 306 | } 307 | 308 | free(invocation); 309 | } 310 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "authenticator.h" 5 | #include "enrol.h" 6 | #include "enumerate.h" 7 | #include "exit.h" 8 | #include "generate.h" 9 | #include "help.h" 10 | #include "invocation.h" 11 | #include "memory.h" 12 | 13 | int main(int argc, char **argv) { 14 | lock_memory_and_drop_privileges(); 15 | 16 | unsigned short int print_secret_result; 17 | 18 | if (sodium_init() != 0) { 19 | errx(EXIT_CRYPTOGRAPHY_ERROR, "Unable to initialize libsodium"); 20 | } 21 | 22 | fido_init(0); 23 | 24 | invocation_state_t *invocation = 25 | parse_arguments_and_get_passphrase(argc, argv); 26 | 27 | devices_list_t *devices_list; 28 | 29 | switch (invocation->subcommand) { 30 | case subcommand_help: 31 | print_help(argv[0]); 32 | free_invocation(invocation); 33 | return EXIT_SUCCESS; 34 | 35 | case subcommand_version: 36 | print_version(); 37 | free_invocation(invocation); 38 | return EXIT_SUCCESS; 39 | 40 | case subcommand_enumerate: 41 | devices_list = list_devices(); 42 | print_devices_list(devices_list); 43 | free_devices_list(devices_list); 44 | free_invocation(invocation); 45 | return EXIT_SUCCESS; 46 | 47 | case subcommand_enrol: 48 | enrol_device(invocation); 49 | free_invocation(invocation); 50 | return EXIT_SUCCESS; 51 | 52 | case subcommand_generate: 53 | devices_list = list_devices(); 54 | print_secret_result = 55 | print_secret_consuming_invocation(invocation, devices_list); 56 | free_devices_list(devices_list); 57 | switch (print_secret_result) { 58 | case EXIT_NO_DEVICES: 59 | errx(EXIT_NO_DEVICES, 60 | "Unable to find an appropriate authenticator to generate a " 61 | "secret"); 62 | case EXIT_NO_VALID_AUTHENTICATOR: 63 | errx(EXIT_NO_VALID_AUTHENTICATOR, 64 | "No connected authenticator was able to generate a valid " 65 | "secret"); 66 | case EXIT_SUCCESS: 67 | return EXIT_SUCCESS; 68 | default: 69 | errx(EXIT_PROGRAMMER_ERROR, 70 | "BUG (%s:%d): unhandled return value from " 71 | "print_secret_consuming_invocation() (%d)", 72 | __func__, __LINE__, print_secret_result); 73 | } 74 | break; 75 | 76 | default: 77 | errx(EXIT_PROGRAMMER_ERROR, 78 | "BUG (%s:%d): unhandled but valid subcommand (%d)\n", __func__, 79 | __LINE__, invocation->subcommand); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/memory.c: -------------------------------------------------------------------------------- 1 | #include "memory.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "exit.h" 13 | 14 | void lock_memory_and_drop_privileges(void) { 15 | int r; 16 | 17 | // Prevent our memory from being swapped out 18 | r = mlockall(MCL_CURRENT | MCL_FUTURE); 19 | #if WARN_ON_MEMORY_LOCK_ERRORS 20 | if (r != 0) { 21 | warn("Unable to lock memory, which means secrets may be swapped to " 22 | "disk"); 23 | } 24 | #endif 25 | 26 | #ifndef DEBUG 27 | 28 | // Set memory to not-dumpable 29 | r = prctl(PR_SET_DUMPABLE, 0); 30 | #if WARN_ON_MEMORY_LOCK_ERRORS 31 | if (r != 0) { 32 | warn("Unable to set dumpable flag to 0, which means a core dump " 33 | "(including secrets) may be written to disk in the event of a " 34 | "crash"); 35 | } 36 | #endif 37 | 38 | // Limit core dump size to 0 bytes 39 | r = setrlimit(RLIMIT_CORE, &(struct rlimit){0, 0}); 40 | #if WARN_ON_MEMORY_LOCK_ERRORS 41 | if (r != 0) { 42 | warn("Unable to set RLIMIT_CORE to {0, 0}, which means a core dump " 43 | "(including secrets) may be written to disk in the event of a " 44 | "crash"); 45 | } 46 | #endif 47 | 48 | #endif // ifndef DEBUG 49 | } 50 | 51 | void *malloc_or_exit(size_t n, const char *what) { 52 | void *result = malloc(n); 53 | if (result == NULL) { 54 | errx(EXIT_OUT_OF_MEMORY, "Unable to allocate memory for %s", what); 55 | } 56 | return result; 57 | } 58 | 59 | char *strdup_or_exit(const char *str, const char *what) { 60 | char *result = strdup(str); 61 | if (result == NULL) { 62 | errx(EXIT_OUT_OF_MEMORY, "Unable to allocate memory for %s", what); 63 | } 64 | return result; 65 | } 66 | 67 | char *strndup_or_exit(const char *str, size_t n, const char *what) { 68 | char *result = strndup(str, n); 69 | if (result == NULL) { 70 | errx(EXIT_OUT_OF_MEMORY, "Unable to allocate memory for %s", what); 71 | } 72 | return result; 73 | } 74 | -------------------------------------------------------------------------------- /src/serialization.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "authenticator.h" 8 | #include "cryptography.h" 9 | #include "exit.h" 10 | #include "memory.h" 11 | #include "serialization.h" 12 | #include "serialization/v1.h" 13 | 14 | authenticator_parameters_t * 15 | build_authenticator_parameters_from_deserialized_cleartext_and_key_and_mixin( 16 | deserialized_cleartext *cleartext, unsigned char *key_bytes, char *mixin) { 17 | unsigned char *decrypted = malloc_or_exit(cleartext->encrypted_data_size - 18 | crypto_secretbox_MACBYTES, 19 | "encrypted data"); 20 | if (crypto_secretbox_open_easy(decrypted, cleartext->encrypted_data, 21 | cleartext->encrypted_data_size, 22 | cleartext->nonce, key_bytes) != 0) { 23 | errx(EXIT_BAD_PASSPHRASE, 24 | "Could not decrypt secrets; this likely means " 25 | "the passphrase was wrong"); 26 | } 27 | deserialized_secrets *secrets = load_secrets_from_bytes( 28 | decrypted, cleartext->encrypted_data_size - crypto_secretbox_MACBYTES); 29 | free(decrypted); 30 | 31 | authenticator_parameters_t *params = allocate_parameters_except_rpid( 32 | secrets->credential_id_size, secrets->salt_size); 33 | memcpy(params->credential_id, secrets->credential_id, 34 | secrets->credential_id_size); 35 | params->relying_party_id = 36 | strdup_or_exit(secrets->relying_party_id, 37 | "relying party id in authenticator parameters"); 38 | memcpy(params->salt, secrets->salt, secrets->salt_size); 39 | free_secrets(secrets); 40 | secrets = NULL; 41 | 42 | if (mixin != NULL) { 43 | unsigned char *hashed_mixin = 44 | malloc_or_exit(params->salt_size, "mixin salt"); 45 | if (crypto_generichash(hashed_mixin, params->salt_size, 46 | (unsigned char *)mixin, strlen(mixin), NULL, 47 | 0) != 0) { 48 | errx(EXIT_CRYPTOGRAPHY_ERROR, "Unable to hash mixin data"); 49 | } 50 | for (size_t i = 0; i < params->salt_size; i++) { 51 | params->salt[i] ^= hashed_mixin[i]; 52 | } 53 | free(hashed_mixin); 54 | } 55 | 56 | return params; 57 | } 58 | 59 | deserialized_cleartext * 60 | build_deserialized_cleartext_from_authenticator_parameters_and_key_spec( 61 | authenticator_parameters_t *authenticator_params, key_spec_t *key_spec) { 62 | deserialized_cleartext *cleartext = 63 | malloc_or_exit(sizeof(deserialized_cleartext), "encrypted keyfile"); 64 | cleartext->version = SERIALIZATION_MAX_VERSION; 65 | cleartext->opslimit = key_spec->opslimit; 66 | cleartext->memlimit = key_spec->memlimit; 67 | cleartext->algorithm = key_spec->algorithm; 68 | cleartext->kdf_salt = 69 | malloc_or_exit(key_spec->kdf_salt_size, "salt in encrypted keyfile"); 70 | memcpy(cleartext->kdf_salt, key_spec->kdf_salt, key_spec->kdf_salt_size); 71 | cleartext->kdf_salt_size = key_spec->kdf_salt_size; 72 | cleartext->nonce = 73 | malloc_or_exit(crypto_box_NONCEBYTES, "nonce in encrypted keyfile"); 74 | randombytes_buf(cleartext->nonce, crypto_box_NONCEBYTES); 75 | cleartext->nonce_size = crypto_box_NONCEBYTES; 76 | 77 | deserialized_secrets *secrets = 78 | malloc_or_exit(sizeof(deserialized_secrets), "secrets"); 79 | secrets->version = cleartext->version; 80 | secrets->relying_party_id = 81 | strdup_or_exit(authenticator_params->relying_party_id, 82 | "relying party id in encrypted keyfile"); 83 | secrets->credential_id = 84 | malloc_or_exit(authenticator_params->credential_id_size, 85 | "credential id in encrypted keyfile"); 86 | memcpy(secrets->credential_id, authenticator_params->credential_id, 87 | authenticator_params->credential_id_size); 88 | secrets->credential_id_size = authenticator_params->credential_id_size; 89 | secrets->salt = malloc_or_exit(authenticator_params->salt_size, 90 | "encrypted secret in encrypted keyfile"); 91 | memcpy(secrets->salt, authenticator_params->salt, 92 | authenticator_params->salt_size); 93 | secrets->salt_size = authenticator_params->salt_size; 94 | 95 | cbor_item_t *cbor_encoded_secrets = serialize_secrets_to_cbor_v1(secrets); 96 | free_secrets(secrets); 97 | secrets = NULL; 98 | 99 | unsigned char *serialized_unencrypted_secrets; 100 | size_t serialized_unencrypted_secrets_size; 101 | if (cbor_serialize_alloc(cbor_encoded_secrets, 102 | &serialized_unencrypted_secrets, 103 | &serialized_unencrypted_secrets_size) == 0) { 104 | errx(EXIT_OUT_OF_MEMORY, "Unable to serialize secrets"); 105 | } 106 | 107 | cleartext->encrypted_data = malloc_or_exit( 108 | serialized_unencrypted_secrets_size + crypto_secretbox_MACBYTES, 109 | "encrypted data blob in encrypted keyfile"); 110 | cleartext->encrypted_data_size = 111 | serialized_unencrypted_secrets_size + crypto_secretbox_MACBYTES; 112 | unsigned char *key_bytes = derive_key(key_spec); 113 | if (crypto_secretbox_easy(cleartext->encrypted_data, 114 | serialized_unencrypted_secrets, 115 | serialized_unencrypted_secrets_size, 116 | cleartext->nonce, key_bytes) != 0) { 117 | errx(EXIT_CRYPTOGRAPHY_ERROR, "Could not encrypt secrets"); 118 | } 119 | free(key_bytes); 120 | 121 | sodium_memzero(serialized_unencrypted_secrets, 122 | serialized_unencrypted_secrets_size); 123 | free(serialized_unencrypted_secrets); 124 | cbor_decref(&cbor_encoded_secrets); 125 | 126 | return cleartext; 127 | } 128 | 129 | void free_cleartext(deserialized_cleartext *clear) { 130 | if (clear == NULL) { 131 | return; 132 | } 133 | 134 | if (clear->kdf_salt != NULL) { 135 | free(clear->kdf_salt); 136 | } 137 | 138 | if (clear->nonce != NULL) { 139 | free(clear->nonce); 140 | } 141 | 142 | if (clear->encrypted_data != NULL) { 143 | free(clear->encrypted_data); 144 | } 145 | 146 | if (clear->device_aaguid != NULL) { 147 | free(clear->device_aaguid); 148 | } 149 | 150 | free(clear); 151 | } 152 | 153 | void free_secrets(deserialized_secrets *secret) { 154 | if (secret == NULL) { 155 | return; 156 | } 157 | 158 | sodium_memzero(secret->relying_party_id, strlen(secret->relying_party_id)); 159 | free(secret->relying_party_id); 160 | sodium_memzero(secret->credential_id, secret->credential_id_size); 161 | free(secret->credential_id); 162 | sodium_memzero(secret->salt, secret->salt_size); 163 | free(secret->salt); 164 | free(secret); 165 | } 166 | 167 | deserialized_secrets *load_secrets_from_bytes(unsigned char *decrypted, 168 | size_t decrypted_size) { 169 | struct cbor_load_result result; 170 | cbor_item_t *cbor_root = cbor_load(decrypted, decrypted_size, &result); 171 | 172 | if (result.error.code != CBOR_ERR_NONE) { 173 | errx( 174 | EXIT_DESERIALIZATION_ERROR, 175 | "Unable to deserialize secrets; is the data not CBOR-encoded? CBOR " 176 | "error code %d: %s", 177 | result.error.code, get_cbor_error_string(result.error.code)); 178 | } 179 | 180 | if (!cbor_isa_array(cbor_root)) { 181 | errx(EXIT_DESERIALIZATION_ERROR, 182 | "Secrets have the wrong format (should be a CBOR array at root)"); 183 | } 184 | 185 | cbor_item_t *cbor_version = cbor_array_get(cbor_root, 0); 186 | if (!cbor_isa_uint(cbor_version) || 187 | cbor_int_get_width(cbor_version) != CBOR_INT_8) { 188 | errx(EXIT_DESERIALIZATION_ERROR, 189 | "Secrets have the wrong format (first field should be a version " 190 | "number stored as an 8-bit unsigned integer)"); 191 | } 192 | 193 | uint8_t version = cbor_get_uint8(cbor_version); 194 | cbor_decref(&cbor_version); 195 | 196 | switch (version) { 197 | case 1: 198 | return deserialize_secrets_from_cbor_v1(cbor_root); 199 | default: 200 | errx(EXIT_DESERIALIZATION_ERROR, 201 | "Unrecognized secrets version (we only support up to %d, got " 202 | "version %d)", 203 | SERIALIZATION_MAX_VERSION, version); 204 | break; 205 | } 206 | } 207 | 208 | encoded_file *write_cleartext(deserialized_cleartext *cleartext, 209 | const char *path) { 210 | encoded_file *result = 211 | malloc_or_exit(sizeof(encoded_file), "encoded file structure"); 212 | result->path = strdup_or_exit(path, "encoded file path"); 213 | 214 | cbor_item_t *cbor_cleartext = serialize_cleartext_to_cbor_v1(cleartext); 215 | 216 | if (cbor_serialize_alloc(cbor_cleartext, &result->data, &result->length) == 217 | 0) { 218 | errx(EXIT_OUT_OF_MEMORY, "Unable to serialize cleartext"); 219 | } 220 | 221 | cbor_decref(&cbor_cleartext); 222 | 223 | return result; 224 | } 225 | 226 | deserialized_cleartext *load_cleartext(encoded_file *file) { 227 | struct cbor_load_result result; 228 | cbor_item_t *cbor_root = cbor_load(file->data, file->length, &result); 229 | 230 | if (result.error.code != CBOR_ERR_NONE) { 231 | errx(EXIT_DESERIALIZATION_ERROR, 232 | "Unable to deserialize %s; is it not CBOR-encoded? CBOR error " 233 | "code %d: %s", 234 | file->path, result.error.code, 235 | get_cbor_error_string(result.error.code)); 236 | } 237 | 238 | if (!cbor_isa_array(cbor_root)) { 239 | errx(EXIT_DESERIALIZATION_ERROR, 240 | "%s has the wrong format (should be a CBOR array at root)", 241 | file->path); 242 | } 243 | 244 | cbor_item_t *cbor_version = cbor_array_get(cbor_root, 0); 245 | if (!cbor_isa_uint(cbor_version) || 246 | cbor_int_get_width(cbor_version) != CBOR_INT_8) { 247 | errx(EXIT_DESERIALIZATION_ERROR, 248 | "%s has the wrong format (first field should be a version number " 249 | "stored as an 8-bit unsigned integer)", 250 | file->path); 251 | } 252 | 253 | uint8_t version = cbor_get_uint8(cbor_version); 254 | cbor_decref(&cbor_version); 255 | 256 | switch (version) { 257 | case 1: 258 | return deserialize_cleartext_from_cbor_v1(cbor_root); 259 | default: 260 | errx(EXIT_DESERIALIZATION_ERROR, 261 | "Unrecognized data version (we only support up to %d, got version " 262 | "%d)", 263 | SERIALIZATION_MAX_VERSION, version); 264 | break; 265 | } 266 | } 267 | 268 | const char *get_cbor_error_string(cbor_error_code code) { 269 | switch (code) { 270 | case CBOR_ERR_MALFORMATED: 271 | return "malformed data (CBOR_ERR_MALFORMATED)"; 272 | case CBOR_ERR_MEMERROR: 273 | return "memory error (CBOR_ERR_MEMERROR)"; 274 | case CBOR_ERR_NODATA: 275 | return "no data (CBOR_ERR_NODATA)"; 276 | case CBOR_ERR_NOTENOUGHDATA: 277 | return "not enough data (CBOR_ERR_NOTENOUGHDATA)"; 278 | case CBOR_ERR_SYNTAXERROR: 279 | return "syntax error in data (CBOR_ERR_SYNTAXERROR)"; 280 | default: 281 | return "unknown"; 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /src/serialization/v1.c: -------------------------------------------------------------------------------- 1 | #include "serialization/v1.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "exit.h" 9 | #include "memory.h" 10 | 11 | deserialized_cleartext * 12 | deserialize_cleartext_from_cbor_v1(cbor_item_t *cbor_root) { 13 | deserialized_cleartext *clear = 14 | malloc_or_exit(sizeof(deserialized_cleartext), "keyfile"); 15 | 16 | if (cbor_array_size(cbor_root) != CLEAR_COUNT_OF_FIELDS) { 17 | errx(EXIT_DESERIALIZATION_ERROR, 18 | "File has the wrong format for v1 (should be a CBOR array with %d " 19 | "elements at root)", 20 | CLEAR_COUNT_OF_FIELDS); 21 | } 22 | 23 | cbor_item_t *cbor_version = cbor_array_get(cbor_root, CLEAR_FIELD_VERSION); 24 | if (!cbor_isa_uint(cbor_version) || 25 | cbor_int_get_width(cbor_version) != CBOR_INT_8) { 26 | errx(EXIT_DESERIALIZATION_ERROR, 27 | "File has the wrong format (field %d should be a version number " 28 | "stored as an 8-bit unsigned integer)", 29 | CLEAR_FIELD_VERSION); 30 | } 31 | clear->version = cbor_get_uint8(cbor_version); 32 | if (clear->version != SERIALIZATION_VERSION) { 33 | errx(EXIT_PROGRAMMER_ERROR, 34 | "BUG (%s:%d): deserialize_cleartext_from_cbor_v1() called when " 35 | "file version is not %d (version is %d)", 36 | __func__, __LINE__, SERIALIZATION_VERSION, clear->version); 37 | } 38 | cbor_decref(&cbor_version); 39 | cbor_version = NULL; 40 | 41 | cbor_item_t *cbor_device_aaguid = 42 | cbor_array_get(cbor_root, CLEAR_FIELD_DEVICE_AAGUID); 43 | if (!cbor_isa_bytestring(cbor_device_aaguid) || 44 | !cbor_bytestring_is_definite(cbor_device_aaguid)) { 45 | errx(EXIT_DESERIALIZATION_ERROR, 46 | "File has the wrong format (field %d should be a AAGUID as a " 47 | "definite bytestring)", 48 | CLEAR_FIELD_DEVICE_AAGUID); 49 | } 50 | clear->device_aaguid_size = cbor_bytestring_length(cbor_device_aaguid); 51 | if (clear->device_aaguid_size > 0) { 52 | clear->device_aaguid = malloc_or_exit(clear->device_aaguid_size, 53 | "device AAGUID in keyfile"); 54 | memcpy(clear->device_aaguid, cbor_bytestring_handle(cbor_device_aaguid), 55 | clear->device_aaguid_size); 56 | } else { 57 | clear->device_aaguid = NULL; 58 | } 59 | cbor_decref(&cbor_device_aaguid); 60 | cbor_device_aaguid = NULL; 61 | 62 | cbor_item_t *cbor_kdf_salt = 63 | cbor_array_get(cbor_root, CLEAR_FIELD_KDF_SALT); 64 | if (!cbor_isa_bytestring(cbor_kdf_salt) || 65 | !cbor_bytestring_is_definite(cbor_kdf_salt)) { 66 | errx(EXIT_DESERIALIZATION_ERROR, 67 | "File has the wrong format (field %d should be a salt as a " 68 | "definite bytestring)", 69 | CLEAR_FIELD_KDF_SALT); 70 | } 71 | clear->kdf_salt_size = cbor_bytestring_length(cbor_kdf_salt); 72 | if (clear->kdf_salt_size > 0) { 73 | clear->kdf_salt = 74 | malloc_or_exit(clear->kdf_salt_size, "salt in keyfile"); 75 | memcpy(clear->kdf_salt, cbor_bytestring_handle(cbor_kdf_salt), 76 | clear->kdf_salt_size); 77 | } else { 78 | clear->kdf_salt = NULL; 79 | } 80 | cbor_decref(&cbor_kdf_salt); 81 | cbor_kdf_salt = NULL; 82 | 83 | cbor_item_t *cbor_opslimit = 84 | cbor_array_get(cbor_root, CLEAR_FIELD_OPSLIMIT); 85 | if (!cbor_isa_uint(cbor_opslimit) || 86 | cbor_int_get_width(cbor_opslimit) != CBOR_INT_64) { 87 | errx(EXIT_DESERIALIZATION_ERROR, 88 | "File has the wrong format (field %d should be a 64-bit unsigned " 89 | "integer)", 90 | CLEAR_FIELD_OPSLIMIT); 91 | } 92 | clear->opslimit = (unsigned long long)cbor_get_uint64(cbor_opslimit); 93 | cbor_decref(&cbor_opslimit); 94 | cbor_opslimit = NULL; 95 | 96 | cbor_item_t *cbor_memlimit = 97 | cbor_array_get(cbor_root, CLEAR_FIELD_MEMLIMIT); 98 | if (!cbor_isa_uint(cbor_memlimit) || 99 | cbor_int_get_width(cbor_memlimit) != CBOR_INT_64) { 100 | errx(EXIT_DESERIALIZATION_ERROR, 101 | "File has the wrong format (field %d should be a 64-bit unsigned " 102 | "integer)", 103 | CLEAR_FIELD_MEMLIMIT); 104 | } 105 | clear->memlimit = (size_t)cbor_get_uint64(cbor_memlimit); 106 | cbor_decref(&cbor_memlimit); 107 | cbor_memlimit = NULL; 108 | 109 | cbor_item_t *cbor_algorithm = 110 | cbor_array_get(cbor_root, CLEAR_FIELD_ALGORITHM); 111 | if (!cbor_isa_uint(cbor_algorithm) || 112 | cbor_int_get_width(cbor_algorithm) != CBOR_INT_16) { 113 | errx(EXIT_DESERIALIZATION_ERROR, 114 | "File has the wrong format (field %d should be a 16-bit unsigned " 115 | "integer)", 116 | CLEAR_FIELD_ALGORITHM); 117 | } 118 | clear->algorithm = (int)cbor_get_uint16(cbor_algorithm); 119 | cbor_decref(&cbor_algorithm); 120 | cbor_algorithm = NULL; 121 | 122 | cbor_item_t *cbor_nonce = cbor_array_get(cbor_root, CLEAR_FIELD_NONCE); 123 | if (!cbor_isa_bytestring(cbor_nonce) || 124 | !cbor_bytestring_is_definite(cbor_nonce)) { 125 | errx(EXIT_DESERIALIZATION_ERROR, 126 | "File has the wrong format (field %d should be a nonce as a " 127 | "definite bytestring)", 128 | CLEAR_FIELD_NONCE); 129 | } 130 | clear->nonce_size = cbor_bytestring_length(cbor_nonce); 131 | if (clear->nonce_size > 0) { 132 | clear->nonce = malloc_or_exit(clear->nonce_size, "nonce in keyfile"); 133 | memcpy(clear->nonce, cbor_bytestring_handle(cbor_nonce), 134 | clear->nonce_size); 135 | } else { 136 | clear->nonce = NULL; 137 | } 138 | cbor_decref(&cbor_nonce); 139 | cbor_nonce = NULL; 140 | 141 | cbor_item_t *cbor_encrypted_data = 142 | cbor_array_get(cbor_root, CLEAR_FIELD_ENCRYPTED_DATA); 143 | if (!cbor_isa_bytestring(cbor_encrypted_data) || 144 | !cbor_bytestring_is_definite(cbor_encrypted_data)) { 145 | errx( 146 | EXIT_DESERIALIZATION_ERROR, 147 | "File has the wrong format (field %d should be encrypted data as a " 148 | "definite bytestring)", 149 | CLEAR_FIELD_ENCRYPTED_DATA); 150 | } 151 | clear->encrypted_data_size = cbor_bytestring_length(cbor_encrypted_data); 152 | if (clear->encrypted_data_size > 0) { 153 | clear->encrypted_data = malloc_or_exit( 154 | clear->encrypted_data_size, "encrypted data blob in keyfile"); 155 | memcpy(clear->encrypted_data, 156 | cbor_bytestring_handle(cbor_encrypted_data), 157 | clear->encrypted_data_size); 158 | } else { 159 | clear->encrypted_data = NULL; 160 | } 161 | cbor_decref(&cbor_encrypted_data); 162 | cbor_encrypted_data = NULL; 163 | 164 | cbor_decref(&cbor_root); 165 | return clear; 166 | } 167 | 168 | cbor_item_t *serialize_cleartext_to_cbor_v1(deserialized_cleartext *clear) { 169 | cbor_item_t *root = cbor_new_definite_array(CLEAR_COUNT_OF_FIELDS); 170 | 171 | FIELD_COUNTER_ASSERT_START; 172 | 173 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_VERSION, __LINE__); 174 | cbor_item_t *version = cbor_build_uint8(clear->version); 175 | cbor_array_push(root, version); 176 | cbor_decref(&version); 177 | 178 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_DEVICE_AAGUID, __LINE__); 179 | cbor_item_t *device_aaguid = 180 | cbor_build_bytestring(clear->device_aaguid, clear->device_aaguid_size); 181 | cbor_array_push(root, device_aaguid); 182 | cbor_decref(&device_aaguid); 183 | 184 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_KDF_SALT, __LINE__); 185 | cbor_item_t *salt = 186 | cbor_build_bytestring(clear->kdf_salt, clear->kdf_salt_size); 187 | cbor_array_push(root, salt); 188 | cbor_decref(&salt); 189 | 190 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_OPSLIMIT, __LINE__); 191 | cbor_item_t *opslimit = cbor_build_uint64(clear->opslimit); 192 | cbor_array_push(root, opslimit); 193 | cbor_decref(&opslimit); 194 | 195 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_MEMLIMIT, __LINE__); 196 | cbor_item_t *memlimit = cbor_build_uint64(clear->memlimit); 197 | cbor_array_push(root, memlimit); 198 | cbor_decref(&memlimit); 199 | 200 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_ALGORITHM, __LINE__); 201 | cbor_item_t *algorithm = cbor_build_uint16(clear->algorithm); 202 | cbor_array_push(root, algorithm); 203 | cbor_decref(&algorithm); 204 | 205 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_NONCE, __LINE__); 206 | cbor_item_t *nonce = cbor_build_bytestring(clear->nonce, clear->nonce_size); 207 | cbor_array_push(root, nonce); 208 | cbor_decref(&nonce); 209 | 210 | FIELD_COUNTER_ASSERT(__func__, CLEAR_FIELD_ENCRYPTED_DATA, __LINE__); 211 | cbor_item_t *encrypted_data = cbor_build_bytestring( 212 | clear->encrypted_data, clear->encrypted_data_size); 213 | cbor_array_push(root, encrypted_data); 214 | cbor_decref(&encrypted_data); 215 | 216 | return root; 217 | } 218 | 219 | deserialized_secrets *deserialize_secrets_from_cbor_v1(cbor_item_t *cbor_root) { 220 | deserialized_secrets *secrets = 221 | malloc_or_exit(sizeof(deserialized_secrets), "decrypted secret blob"); 222 | 223 | if (cbor_array_size(cbor_root) != ENCRYPTED_COUNT_OF_FIELDS) { 224 | errx(EXIT_DESERIALIZATION_ERROR, 225 | "Decrypted blob has the wrong format for v1 (should be a CBOR " 226 | "array with %d elements at root)", 227 | ENCRYPTED_COUNT_OF_FIELDS); 228 | } 229 | 230 | cbor_item_t *cbor_version = 231 | cbor_array_get(cbor_root, ENCRYPTED_FIELD_VERSION); 232 | if (!cbor_isa_uint(cbor_version) || 233 | cbor_int_get_width(cbor_version) != CBOR_INT_8) { 234 | errx( 235 | EXIT_DESERIALIZATION_ERROR, 236 | "Decrypted blob has the wrong format (field %d should be a version " 237 | "number stored as an 8-bit unsigned integer)", 238 | ENCRYPTED_FIELD_VERSION); 239 | } 240 | secrets->version = cbor_get_uint8(cbor_version); 241 | if (secrets->version != SERIALIZATION_VERSION) { 242 | errx(EXIT_PROGRAMMER_ERROR, 243 | "BUG (%s:%d): deserialize_secrets_from_cbor_v1() called when file " 244 | "version is not %d (version is %d)", 245 | __func__, __LINE__, SERIALIZATION_VERSION, secrets->version); 246 | } 247 | cbor_decref(&cbor_version); 248 | cbor_version = NULL; 249 | 250 | cbor_item_t *cbor_relying_party_id = 251 | cbor_array_get(cbor_root, ENCRYPTED_FIELD_RP_ID); 252 | if (!cbor_isa_string(cbor_relying_party_id) || 253 | !cbor_string_is_definite(cbor_relying_party_id)) { 254 | errx( 255 | EXIT_DESERIALIZATION_ERROR, 256 | "Decrypted blob has the wrong format (field %d should be a relying " 257 | "party ID as a definite UTF-8 string)", 258 | ENCRYPTED_FIELD_RP_ID); 259 | } 260 | size_t relying_party_size = cbor_string_length(cbor_relying_party_id); 261 | if (relying_party_size > 0) { 262 | secrets->relying_party_id = 263 | malloc_or_exit(relying_party_size + 1, 264 | "relying party id in decrypted secret blob"); 265 | strncpy(secrets->relying_party_id, 266 | (const char *restrict)cbor_string_handle(cbor_relying_party_id), 267 | relying_party_size); // We explicitly add the null terminator in 268 | // the next line 269 | secrets->relying_party_id[relying_party_size] = (char)0; 270 | } else { 271 | secrets->relying_party_id = NULL; 272 | } 273 | cbor_decref(&cbor_relying_party_id); 274 | cbor_relying_party_id = NULL; 275 | 276 | cbor_item_t *cbor_credential_id = 277 | cbor_array_get(cbor_root, ENCRYPTED_FIELD_CREDENTIAL_ID); 278 | if (!cbor_isa_bytestring(cbor_credential_id) || 279 | !cbor_bytestring_is_definite(cbor_credential_id)) { 280 | errx(EXIT_DESERIALIZATION_ERROR, 281 | "Decrypted blob has the wrong format (field %d should be a " 282 | "credential ID as a definite bytestring)", 283 | ENCRYPTED_FIELD_CREDENTIAL_ID); 284 | } 285 | secrets->credential_id_size = cbor_bytestring_length(cbor_credential_id); 286 | if (secrets->credential_id_size > 0) { 287 | secrets->credential_id = 288 | malloc_or_exit(secrets->credential_id_size, 289 | "credential id in decrypted secret blob"); 290 | memcpy(secrets->credential_id, 291 | cbor_bytestring_handle(cbor_credential_id), 292 | secrets->credential_id_size); 293 | } else { 294 | secrets->credential_id = NULL; 295 | } 296 | cbor_decref(&cbor_credential_id); 297 | cbor_credential_id = NULL; 298 | 299 | cbor_item_t *cbor_salt = 300 | cbor_array_get(cbor_root, ENCRYPTED_FIELD_HMAC_SALT); 301 | if (!cbor_isa_bytestring(cbor_salt) || 302 | !cbor_bytestring_is_definite(cbor_salt)) { 303 | errx(EXIT_DESERIALIZATION_ERROR, 304 | "Decrypted blob has the wrong format (field %d should be a HMAC " 305 | "salt as a definite bytestring)", 306 | ENCRYPTED_FIELD_HMAC_SALT); 307 | } 308 | secrets->salt_size = cbor_bytestring_length(cbor_salt); 309 | if (secrets->salt_size > 0) { 310 | secrets->salt = 311 | malloc_or_exit(secrets->salt_size, "salt in decrypted secret blob"); 312 | memcpy(secrets->salt, cbor_bytestring_handle(cbor_salt), 313 | secrets->salt_size); 314 | } else { 315 | secrets->salt = NULL; 316 | } 317 | cbor_decref(&cbor_salt); 318 | cbor_salt = NULL; 319 | 320 | cbor_decref(&cbor_root); 321 | 322 | return secrets; 323 | } 324 | 325 | cbor_item_t *serialize_secrets_to_cbor_v1(deserialized_secrets *secrets) { 326 | cbor_item_t *root = cbor_new_definite_array(ENCRYPTED_COUNT_OF_FIELDS); 327 | 328 | FIELD_COUNTER_ASSERT_START; 329 | 330 | FIELD_COUNTER_ASSERT(__func__, ENCRYPTED_FIELD_VERSION, __LINE__); 331 | cbor_item_t *version = cbor_build_uint8(secrets->version); 332 | cbor_array_push(root, version); 333 | cbor_decref(&version); 334 | 335 | FIELD_COUNTER_ASSERT(__func__, ENCRYPTED_FIELD_RP_ID, __LINE__); 336 | cbor_item_t *relying_party_id = 337 | cbor_build_string(secrets->relying_party_id); 338 | cbor_array_push(root, relying_party_id); 339 | cbor_decref(&relying_party_id); 340 | 341 | FIELD_COUNTER_ASSERT(__func__, ENCRYPTED_FIELD_CREDENTIAL_ID, __LINE__); 342 | cbor_item_t *credential_id = cbor_build_bytestring( 343 | secrets->credential_id, secrets->credential_id_size); 344 | cbor_array_push(root, credential_id); 345 | cbor_decref(&credential_id); 346 | 347 | FIELD_COUNTER_ASSERT(__func__, ENCRYPTED_FIELD_HMAC_SALT, __LINE__); 348 | cbor_item_t *salt = 349 | cbor_build_bytestring(secrets->salt, secrets->salt_size); 350 | cbor_array_push(root, salt); 351 | cbor_decref(&salt); 352 | 353 | return root; 354 | } 355 | -------------------------------------------------------------------------------- /variables.m4: -------------------------------------------------------------------------------- 1 | m4_define(`m4_SSH_ASKPASS_DEFAULT_NOTIFY_COMMAND', `notify-send -t 5000')m4_dnl 2 | m4_define(`m4_SSH_ASKPASS_NOTIFY_ENV', `F2HS_SSH_ASKPASS_NOTIFY')m4_dnl 3 | m4_define(`m4_SSH_ASKPASS_ENCRYPTED_KEYFILE_ENV', `F2HS_SSH_ASKPASS_KEYFILE')m4_dnl 4 | m4_define(`m4_SSH_ASKPASS_DEFAULT_ENCRYPTED_KEYFILE', `$HOME/.ssh/'m4_APPNAME`-askpass-keyfile')m4_dnl 5 | m4_define(`m4_INITCPIO_DEFAULT_MAX_PASSPHRASE_ATTEMPTS', `3')m4_dnl 6 | m4_define(`m4_INITCPIO_DEFAULT_ENCRYPTED_KEYFILE_DIR', `/keyfiles')m4_dnl 7 | m4_define(`m4_INITCPIO_DEFAULT_KEYFILES_SOURCE_DIR', `/boot/keyfiles')m4_dnl 8 | --------------------------------------------------------------------------------