├── .github ├── ISSUE_TEMPLATE │ └── release-checklist.md ├── dependabot.yml └── workflows │ ├── require-release-note.yml │ └── rust.yml ├── .gitignore ├── .packit.yaml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── code_of_conduct.md ├── docs ├── development.md └── release-notes.md ├── examples └── inspect_rsa.rs ├── fixtures ├── dsa ├── dsa.pub ├── ecdsa ├── ecdsa.pub ├── ed25519 ├── ed25519.pub ├── rsa └── rsa.pub └── src ├── lib.rs ├── reader.rs └── writer.rs /.github/ISSUE_TEMPLATE/release-checklist.md: -------------------------------------------------------------------------------- 1 | --- 2 | # Template generated by https://github.com/coreos/repo-templates; do not edit downstream 3 | --- 4 | 5 | # Release process 6 | 7 | This project uses [cargo-release][cargo-release] in order to prepare new releases, tag and sign the relevant git commit, and publish the resulting artifacts to [crates.io][crates-io]. 8 | The release process follows the usual PR-and-review flow, allowing an external reviewer to have a final check before publishing. 9 | 10 | ## Requirements 11 | 12 | This guide requires: 13 | 14 | * A web browser (and network connectivity) 15 | * `git` 16 | * [GPG setup][GPG setup] and personal key for signing 17 | * `cargo` (suggested: latest stable toolchain from [rustup][rustup]) 18 | * `cargo-release` (suggested: `cargo install -f cargo-release`) 19 | * Write access to this GitHub project 20 | * A verified account on crates.io 21 | * Membership in the [Fedora CoreOS Crates Owners group](https://github.com/orgs/coreos/teams/fedora-coreos-crates-owners/members), which will give you upload access to crates.io 22 | 23 | ## Release checklist 24 | 25 | These steps show how to release version `x.y.z` on the `origin` remote (this can be checked via `git remote -av`). 26 | Push access to the upstream repository is required in order to publish the new tag and the PR branch. 27 | 28 | :warning:: if `origin` is not the name of the locally configured remote that points to the upstream git repository (i.e. `git@github.com:coreos/openssh-keys.git`), be sure to assign the correct remote name to the `UPSTREAM_REMOTE` variable. 29 | 30 | - prepare environment: 31 | - [ ] `RELEASE_VER=x.y.z` 32 | - [ ] `UPSTREAM_REMOTE=origin` 33 | - [ ] `git checkout -b pre-release-${RELEASE_VER}` 34 | 35 | - check `Cargo.toml` for unintended increases of lower version bounds: 36 | - [ ] `git diff $(git describe --abbrev=0) Cargo.toml` 37 | 38 | - write release notes: 39 | - [ ] write release notes in `docs/release-notes.md` 40 | - [ ] `git add docs/release-notes.md && git commit -m "docs/release-notes: update for release ${RELEASE_VER}"` 41 | 42 | - land the changes: 43 | - [ ] PR the changes, get them reviewed, approved and merged 44 | - [ ] if doing a branched release, also include a PR to merge the `docs/release-notes.md` changes into main 45 | 46 | - make sure the project is clean: 47 | - [ ] Make sure `cargo-release` is up to date: `cargo install cargo-release` 48 | - [ ] `git checkout main && git pull ${UPSTREAM_REMOTE} main` 49 | - [ ] `cargo test --all-features` 50 | - [ ] `cargo clean` 51 | - [ ] `git clean -fd` 52 | 53 | - create release commit on a dedicated branch and tag it (the commit and tag will be signed with the GPG signing key you configured): 54 | - [ ] `git checkout -b release-${RELEASE_VER}` 55 | - [ ] `cargo release --execute ${RELEASE_VER}` (and confirm the version when prompted) 56 | 57 | - open and merge a PR for this release: 58 | - [ ] `git push ${UPSTREAM_REMOTE} release-${RELEASE_VER}` 59 | - [ ] open a web browser and create a PR for the branch above 60 | - [ ] make sure the resulting PR contains exactly one commit 61 | - [ ] get the PR reviewed, approved and merged 62 | 63 | - publish the artifacts (tag and crate): 64 | - [ ] `git checkout v${RELEASE_VER}` 65 | - [ ] verify that `grep "^version = \"${RELEASE_VER}\"$" Cargo.toml` produces output 66 | - [ ] `git push ${UPSTREAM_REMOTE} v${RELEASE_VER}` 67 | - [ ] `cargo publish` 68 | 69 | - publish this release on GitHub: 70 | - [ ] find the new tag in the [GitHub tag list](https://github.com/coreos/openssh-keys/tags), click the triple dots menu, and create a release for it 71 | - [ ] copy in the changelog from the release notes doc 72 | - [ ] publish release 73 | 74 | - clean up the local environment (optional, but recommended): 75 | - [ ] `cargo clean` 76 | - [ ] `git checkout main` 77 | - [ ] `git pull ${UPSTREAM_REMOTE} main` 78 | - [ ] `git push ${UPSTREAM_REMOTE} :pre-release-${RELEASE_VER} :release-${RELEASE_VER}` 79 | - [ ] `git branch -d pre-release-${RELEASE_VER} release-${RELEASE_VER}` 80 | 81 | - Fedora packaging: 82 | - [ ] update the `rust-openssh-keys` spec file in [Fedora](https://src.fedoraproject.org/rpms/rust-openssh-keys) 83 | - bump the `Version` 84 | - switch the `Release` back to `1%{?dist}` 85 | - remove any patches obsoleted by the new release 86 | - update changelog 87 | - [ ] run `spectool -g -S rust-openssh-keys.spec` 88 | - [ ] run `kinit your_fas_account@FEDORAPROJECT.ORG` 89 | - [ ] run `fedpkg new-sources $(spectool -S rust-openssh-keys.spec | sed 's:.*/::')` 90 | - [ ] PR the changes in [Fedora](https://src.fedoraproject.org/rpms/rust-openssh-keys) 91 | - [ ] once the PR merges to rawhide, merge rawhide into the other relevant branches (e.g. f40) then push those, for example: 92 | ```bash 93 | git checkout rawhide 94 | git pull --ff-only 95 | git checkout f40 96 | git merge --ff-only rawhide 97 | git push origin f40 98 | ``` 99 | - [ ] on each of those branches run `fedpkg build` 100 | - [ ] once the builds have finished, submit them to [bodhi](https://bodhi.fedoraproject.org/updates/new), filling in: 101 | - `rust-openssh-keys` for `Packages` 102 | - selecting the build(s) that just completed, except for the rawhide one (which gets submitted automatically) 103 | - writing brief release notes like "New upstream release; see release notes at `link to GitHub release`" 104 | - leave `Update name` blank 105 | - `Type`, `Severity` and `Suggestion` can be left as `unspecified` unless it is a security release. In that case select `security` with the appropriate severity. 106 | - `Stable karma` and `Unstable` karma can be set to `2` and `-1`, respectively. 107 | 108 | [cargo-release]: https://github.com/sunng87/cargo-release 109 | [rustup]: https://rustup.rs/ 110 | [crates-io]: https://crates.io/ 111 | [GPG setup]: https://docs.github.com/en/github/authenticating-to-github/managing-commit-signature-verification 112 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Maintained in https://github.com/coreos/repo-templates 2 | # Do not edit downstream. 3 | 4 | version: 2 5 | updates: 6 | - package-ecosystem: cargo 7 | directory: / 8 | schedule: 9 | interval: monthly 10 | open-pull-requests-limit: 10 11 | labels: 12 | - dependency 13 | - skip-notes 14 | -------------------------------------------------------------------------------- /.github/workflows/require-release-note.yml: -------------------------------------------------------------------------------- 1 | # Maintained in https://github.com/coreos/repo-templates 2 | # Do not edit downstream. 3 | 4 | name: Release notes 5 | 6 | on: 7 | pull_request: 8 | branches: [main] 9 | types: [opened, synchronize, reopened, labeled, unlabeled] 10 | 11 | permissions: 12 | contents: read 13 | 14 | concurrency: 15 | group: release-note-${{ github.ref }} 16 | cancel-in-progress: true 17 | 18 | jobs: 19 | require-notes: 20 | name: Require release note 21 | runs-on: ubuntu-latest 22 | steps: 23 | - name: Require release-notes.md update 24 | uses: coreos/actions-lib/require-file-change@main 25 | with: 26 | path: docs/release-notes.md 27 | override-label: skip-notes 28 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | # Maintained in https://github.com/coreos/repo-templates 2 | # Do not edit downstream. 3 | 4 | name: Rust 5 | on: 6 | push: 7 | branches: [main] 8 | pull_request: 9 | branches: [main] 10 | permissions: 11 | contents: read 12 | 13 | # don't waste job slots on superseded code 14 | concurrency: 15 | group: ${{ github.workflow }}-${{ github.ref }} 16 | cancel-in-progress: true 17 | 18 | env: 19 | CARGO_TERM_COLOR: always 20 | # Pinned toolchain for linting 21 | ACTIONS_LINTS_TOOLCHAIN: 1.75.0 22 | 23 | jobs: 24 | tests-stable: 25 | name: Tests, stable toolchain 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: Check out repository 29 | uses: actions/checkout@v3 30 | - name: Install toolchain 31 | uses: dtolnay/rust-toolchain@v1 32 | with: 33 | toolchain: stable 34 | - name: Cache build artifacts 35 | uses: Swatinem/rust-cache@v2 36 | - name: cargo build 37 | run: cargo build --all-targets 38 | - name: cargo test 39 | run: cargo test --all-targets 40 | tests-release-stable: 41 | name: Tests (release), stable toolchain 42 | runs-on: ubuntu-latest 43 | steps: 44 | - name: Check out repository 45 | uses: actions/checkout@v3 46 | - name: Install toolchain 47 | uses: dtolnay/rust-toolchain@v1 48 | with: 49 | toolchain: stable 50 | - name: Cache build artifacts 51 | uses: Swatinem/rust-cache@v2 52 | - name: cargo build (release) 53 | run: cargo build --all-targets --release 54 | - name: cargo test (release) 55 | run: cargo test --all-targets --release 56 | tests-release-msrv: 57 | name: Tests (release), minimum supported toolchain 58 | runs-on: ubuntu-latest 59 | steps: 60 | - name: Check out repository 61 | uses: actions/checkout@v3 62 | - name: Detect crate MSRV 63 | run: | 64 | msrv=$(cargo metadata --format-version 1 --no-deps | \ 65 | jq -r '.packages[0].rust_version') 66 | echo "Crate MSRV: $msrv" 67 | echo "MSRV=$msrv" >> $GITHUB_ENV 68 | - name: Install toolchain 69 | uses: dtolnay/rust-toolchain@v1 70 | with: 71 | toolchain: ${{ env.MSRV }} 72 | - name: Cache build artifacts 73 | uses: Swatinem/rust-cache@v2 74 | - name: cargo build (release) 75 | run: cargo build --all-targets --release 76 | - name: cargo test (release) 77 | run: cargo test --all-targets --release 78 | linting: 79 | name: Lints, pinned toolchain 80 | runs-on: ubuntu-latest 81 | steps: 82 | - name: Check out repository 83 | uses: actions/checkout@v3 84 | - name: Install toolchain 85 | uses: dtolnay/rust-toolchain@v1 86 | with: 87 | toolchain: ${{ env.ACTIONS_LINTS_TOOLCHAIN }} 88 | components: rustfmt, clippy 89 | - name: Cache build artifacts 90 | uses: Swatinem/rust-cache@v2 91 | - name: cargo fmt (check) 92 | run: cargo fmt -- --check -l 93 | - name: cargo clippy (warnings) 94 | run: cargo clippy --all-targets -- -D warnings 95 | tests-other-channels: 96 | name: Tests, unstable toolchain 97 | runs-on: ubuntu-latest 98 | continue-on-error: true 99 | strategy: 100 | matrix: 101 | channel: [beta, nightly] 102 | steps: 103 | - name: Check out repository 104 | uses: actions/checkout@v3 105 | - name: Install toolchain 106 | uses: dtolnay/rust-toolchain@v1 107 | with: 108 | toolchain: ${{ matrix.channel }} 109 | - name: Cache build artifacts 110 | uses: Swatinem/rust-cache@v2 111 | - name: cargo build 112 | run: cargo build --all-targets 113 | - name: cargo test 114 | run: cargo test --all-targets 115 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | # IDEs and editors 13 | .idea 14 | .idea/* 15 | .vscode/* 16 | -------------------------------------------------------------------------------- /.packit.yaml: -------------------------------------------------------------------------------- 1 | # See the documentation for more information: 2 | # https://packit.dev/docs/configuration/ 3 | 4 | actions: 5 | changelog-entry: 6 | - bash -c 'echo "- New upstream release"' 7 | post-upstream-clone: 8 | - wget https://src.fedoraproject.org/rpms/rust-openssh-keys/raw/rawhide/f/rust-openssh-keys.spec 9 | prepare-files: 10 | - bash -c 'rust2rpm -s openssh-keys $PACKIT_PROJECT_VERSION' 11 | 12 | specfile_path: rust-openssh-keys.spec 13 | 14 | upstream_project_url: https://github.com/coreos/openssh-keys 15 | 16 | upstream_tag_template: v{version} 17 | 18 | # add or remove files that should be synced 19 | files_to_sync: 20 | - .packit.yaml 21 | - rust-openssh-keys.spec 22 | 23 | # name in upstream package repository or registry (e.g. in PyPI) 24 | upstream_package_name: openssh-keys 25 | # downstream (Fedora) RPM package name 26 | downstream_package_name: rust-openssh-keys 27 | 28 | jobs: 29 | 30 | - job: propose_downstream 31 | trigger: release 32 | dist_git_branches: 33 | - fedora-rawhide 34 | 35 | - job: koji_build 36 | trigger: commit 37 | dist_git_branches: 38 | - fedora-all 39 | 40 | - job: bodhi_update 41 | trigger: commit 42 | dist_git_branches: 43 | - fedora-all -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "openssh-keys" 3 | version = "0.6.4" 4 | edition = "2021" 5 | rust-version = "1.75.0" 6 | authors = ["Stephen Demos "] 7 | description = "read and write OpenSSH public keys" 8 | documentation = "https://docs.rs/openssh-keys" 9 | homepage = "https://github.com/coreos/openssh-keys" 10 | repository = "https://github.com/coreos/openssh-keys" 11 | readme = "README.md" 12 | keywords = ["ssh", "ssh-keys", "keys", "rsa", "openssh"] 13 | license = "MIT OR Apache-2.0" 14 | exclude = [".github", ".gitignore", "examples", "fixtures"] 15 | 16 | [dependencies] 17 | # Private dependencies. 18 | base64 = "0.21" 19 | byteorder = "1.1" 20 | # Do not use a range on the crates md-5 or sha2. RustCrypto crate 21 | # versions cannot be mixed and matched. Doing so will cause hard 22 | # to understand build failures. Read about it at 23 | # https://github.com/coreos/openssh-keys/issues/89 24 | md-5 = "0.10" 25 | sha2 = "0.10" 26 | thiserror = "1.0" 27 | # Public dependencies, exposed through library API. 28 | # 29 | 30 | [dev-dependencies] 31 | home = "~0.5" 32 | 33 | [package.metadata.release] 34 | publish = false 35 | push = false 36 | pre-release-commit-message = "cargo: openssh-keys release {{version}}" 37 | sign-commit = true 38 | sign-tag = true 39 | tag-message = "openssh-keys {{version}}" 40 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Stephen Demos 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # openssh-keys   [![Latest Version]][crates.io] [![Docs Badge]][docs] 2 | 3 | [Latest Version]: https://img.shields.io/crates/v/openssh-keys.svg 4 | [crates.io]: https://crates.io/crates/openssh-keys 5 | [Docs Badge]: https://docs.rs/openssh-keys/badge.svg 6 | [docs]: https://docs.rs/openssh-keys 7 | 8 | A pure-Rust library to handle OpenSSH public keys. 9 | 10 | `openssh-keys` can parse, print, and fingerprint OpenSSH public keys. 11 | It supports the following algorithms: 12 | 13 | * RSA 14 | * DSA 15 | * ECDSA (nistp256, nistp384, nistp521) 16 | * ED25519 17 | 18 | It can construct RSA and DSA keys from their components using the `PublicKey::from_rsa()` and 19 | `PublicKey::from_dsa()` functions respectively. 20 | 21 | ## Example 22 | 23 | ```rust 24 | extern crate openssh_keys; 25 | 26 | use std::{env, fs, io, path}; 27 | use std::io::BufRead; 28 | 29 | fn main() { 30 | let home = env::home_dir().unwrap_or(path::PathBuf::from("/home/core/")); 31 | let pub_path = home.join(".ssh").join("id_rsa.pub"); 32 | println!("Inspecting '{}':", pub_path.to_string_lossy()); 33 | let file = fs::File::open(&pub_path).expect("unable to open RSA pubkey"); 34 | let reader = io::BufReader::new(file); 35 | 36 | for (i, line) in reader.lines().enumerate() { 37 | let line = line.expect(&format!("unable to read key at line {}", i + 1)); 38 | let pubkey = openssh_keys::PublicKey::parse(&line).expect("unable to parse RSA pubkey"); 39 | println!(" * Pubkey #{} -> {}", i + 1, pubkey.to_fingerprint_string()); 40 | } 41 | } 42 | ``` 43 | 44 | Some more examples are available under [examples](examples). 45 | 46 | ## Release process 47 | 48 | Releases can be performed by [creating a new release ticket][new-release-ticket] and following the steps in the checklist there. 49 | 50 | ## License 51 | 52 | Licensed under either of 53 | 54 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 55 | http://www.apache.org/licenses/LICENSE-2.0) 56 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 57 | 58 | at your option. 59 | 60 | ## Contribution 61 | 62 | Unless you explicitly state otherwise, any contribution intentionally submitted 63 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 64 | dual licensed as above, without any additional terms or conditions. 65 | 66 | [new-release-ticket]: https://github.com/coreos/openssh-keys/issues/new?labels=release&template=release-checklist.md 67 | -------------------------------------------------------------------------------- /code_of_conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /docs/development.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | ## Release process 4 | 5 | Releases can be performed by [creating a new release ticket][new-release-ticket] and following the steps in the checklist there. 6 | 7 | [new-release-ticket]: https://github.com/coreos/openssh-keys/issues/new?template=release-checklist.md 8 | -------------------------------------------------------------------------------- /docs/release-notes.md: -------------------------------------------------------------------------------- 1 | # Release notes 2 | 3 | ## Upcoming openssh-keys 0.6.5 (unreleased) 4 | 5 | Fixes: 6 | 7 | - Allow parsing comments containing whitespace 8 | 9 | 10 | ## openssh-keys 0.6.4 (2024-07-10) 11 | 12 | Changes: 13 | 14 | - Add Packit support for Fedora packaging 15 | 16 | 17 | ## openssh-keys 0.6.3 (2024-04-30) 18 | 19 | Changes: 20 | 21 | - Require Rust ≥ 1.75.0 22 | 23 | ## openssh-keys 0.6.2 (2023-06-27) 24 | 25 | Changes: 26 | 27 | - Require `md-5` 0.10, `sha2` 0.10 to avoid mismatched Rust Crypto dependencies 28 | 29 | 30 | ## openssh-keys 0.6.1 (2023-06-01) 31 | 32 | Changes: 33 | 34 | - Require Rust ≥ 1.58.0 35 | - Require `base64` ≥ 0.21 36 | - Switch example code from `dirs` dependency to `home` 37 | - Add release notes doc 38 | 39 | 40 | ## openssh-keys 0.6.0 (2022-11-18) 41 | 42 | Changes: 43 | 44 | - cargo: allow md-5 and sha2 0.10 45 | - cargo: explicitly set `sign-tag` 46 | - dependabot: switch to weekly cadence 47 | - git: rename `master` branch to `main` 48 | - github/ISSUE_TEMPLATE: add release checklist 49 | - lib: Support Hardware Security Keys 50 | - templates: release process updates 51 | - workflows: bump MSRV and lint toolchain 52 | 53 | 54 | ## openssh-keys 0.5.0 (2021-03-16) 55 | 56 | - API change: Switch error-handling library from `error-chain` to `thiserror` 57 | - Update to Rust 2018 58 | - Fix build warnings with newer Rust 59 | - Update `base64` to 0.13 60 | - Exclude tooling configuration from packaged crate 61 | 62 | 63 | ## openssh-keys 0.4.2 (2020-06-22) 64 | 65 | Changes: 66 | 67 | - cargo: update all dependencies 68 | - cargo: update manifest and rustfmt whole project 69 | - dependabot: create config file 70 | - travis: update minimum and clippy toolchains 71 | 72 | 73 | ## openssh-keys 0.4.1 (2018-11-01) 74 | 75 | Changes: 76 | 77 | - Update base64 requirement from 0.9 to 0.10 78 | 79 | 80 | ## openssh-keys 0.4.0 (2018-10-24) 81 | 82 | Changes: 83 | 84 | - lib: clean all clippy warnings 85 | - cargo: update all dependencies to latest 86 | - travis: add minimum toolchain and clippy passes 87 | - remove appveyor ci 88 | - move repo under the coreos org on github 89 | 90 | 91 | ## openssh-keys 0.3.0 (2018-07-11) 92 | 93 | Changes: 94 | 95 | - update `error-chain` from `0.11.x` to `0.12.x` 96 | - update `base64` from `0.8.x` to `0.9.x` 97 | 98 | 99 | ## openssh-keys 0.2.2 (2017-12-14) 100 | 101 | Changes: 102 | 103 | - Make `PublicKey` fields public (#14, thanks @Trolldemorted!) 104 | - bump `base64` from `0.6.x` to `0.8.x` 105 | - bump `sha2` from `0.6.x` to `0.7.x` 106 | 107 | 108 | ## openssh-keys 0.2.1 (2017-12-05) 109 | 110 | Changes: 111 | 112 | - add md5 fingerprinting with `fingerprint_md5` and `to_fingerprint_md5_string` 113 | - move fingerprint algorithm label to `to_fingerprint_string` and `to_fingerprint_md5_string`, now `fingerprint` only prints the fingerprint without the hashing algorithm label 114 | 115 | 116 | ## openssh-keys 0.2.0 (2017-11-07) 117 | 118 | Changes: 119 | 120 | - respect authorized_keys file options and known_hosts hostnames (#7). this means that `read_keys` is now a valid `authorized_keys` file and `known_hosts` file parser. 121 | 122 | 123 | ## openssh-keys 0.1.2 (2017-11-07) 124 | 125 | Changes: 126 | 127 | - cleaned up release crate 128 | - added several trait derivations for exported datatypes 129 | - renamed `to_key_file` to `to_key_format` 130 | - added `read_keys` which reads multiple newline separated keys from a `Read`. it would be a fully featured authorized_keys file and known_hosts file parser except for #7. 131 | 132 | 133 | ## openssh-keys 0.1.1 (2017-09-20) 134 | 135 | Changes: 136 | 137 | - bumps `error-chain` to `v0.11.0` 138 | - uses `sha2` library instead of `rust-crypto` for `sha256` fingerprint hashes 139 | - adds docs and examples 140 | 141 | 142 | ## openssh-keys 0.1.0 (2017-09-01) 143 | 144 | `ssh-keys` can parse, write, and fingerprint all ssh public keys supported by `ssh-keygen` at the time of writing that can be used for public/private key authentication (eg not certs and sign-only keys). 145 | -------------------------------------------------------------------------------- /examples/inspect_rsa.rs: -------------------------------------------------------------------------------- 1 | use std::io::BufRead; 2 | use std::{fs, io, path}; 3 | 4 | fn main() { 5 | let home = home::home_dir().unwrap_or_else(|| path::PathBuf::from("/home/core/")); 6 | let pub_path = home.join(".ssh").join("id_rsa.pub"); 7 | println!("Inspecting '{}':", pub_path.to_string_lossy()); 8 | let file = fs::File::open(&pub_path).expect("unable to open RSA pubkey"); 9 | let reader = io::BufReader::new(file); 10 | 11 | for (i, line) in reader.lines().enumerate() { 12 | let line = line.unwrap_or_else(|_| panic!("unable to read key at line {}", i + 1)); 13 | let pubkey = openssh_keys::PublicKey::parse(&line).expect("unable to parse RSA pubkey"); 14 | println!(" * Pubkey #{} -> {}", i + 1, pubkey.to_fingerprint_string()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /fixtures/dsa: -------------------------------------------------------------------------------- 1 | -----BEGIN DSA PRIVATE KEY----- 2 | MIIBugIBAAKBgQCJHfQpKpXTNkrfH+d63yU+5D4IgPJXmWje4XWXePIWCcis1S6D 3 | 3QTGhhbjsBo79CJtyVqlgHsADXtMXi3HkC9K0hWzP5mVftYHNZ5tVprVcOCiSJS1 4 | 5d4EuzWH0PSLYeMBZ2Xf8YUc/UPjAbANQ4F3sNc8+HS2COOiphYrye1w8wIVALzP 5 | hUiEjgeUdO8HsV3AB+pay9w7AoGARKjyJFtxxw00hIVIYVdgJSDzcCP26mgl8ts2 6 | EOok096FIfjeMZUWgUr1vodjQve1PHMXe2NHVyG0Cj88Dc0V9SgNRfVgLjc68fSp 7 | KQoNk6al0oYafkrHm/periY7YSGDOv9Hb6/XAQzHhMWmzz4AaNxIotjS2xUqiHvO 8 | qmr/IWQCgYBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYC 9 | zReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwc 10 | tbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKgIUOmjp89F4 11 | h6iIjBslgZVHUlg5tss= 12 | -----END DSA PRIVATE KEY----- 13 | -------------------------------------------------------------------------------- /fixtures/dsa.pub: -------------------------------------------------------------------------------- 1 | ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== demos@siril 2 | -------------------------------------------------------------------------------- /fixtures/ecdsa: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MHcCAQEEIKzMDybrRGYetmJcJHkbzwpWyWXABWMlJm3v1Md8he7BoAoGCCqGSM49 3 | AwEHoUQDQgAEiF8tCvDDgOWFjNtJZehfdy05DSNWiy98d9b5BZWi2Sxs/MzZiCQi 4 | KROmgdR9mtikkpbHtZizlqp4uR0IN2T6OQ== 5 | -----END EC PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /fixtures/ecdsa.pub: -------------------------------------------------------------------------------- 1 | ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIhfLQrww4DlhYzbSWXoX3ctOQ0jVosvfHfW+QWVotksbPzM2YgkIikTpoHUfZrYpJKWx7WYs5aqeLkdCDdk+jk= demos@siril 2 | -------------------------------------------------------------------------------- /fixtures/ed25519: -------------------------------------------------------------------------------- 1 | -----BEGIN OPENSSH PRIVATE KEY----- 2 | b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW 3 | QyNTUxOQAAACAIQa+vvhUFwfJJIDjG3cQbsqx87l+R5BJbMKzeg0KDfwAAAJAjpN3BI6Td 4 | wQAAAAtzc2gtZWQyNTUxOQAAACAIQa+vvhUFwfJJIDjG3cQbsqx87l+R5BJbMKzeg0KDfw 5 | AAAEAd9gHFvnS2zqRZWLrq0xPS0/nQyVLKWF6Kv+z7dPP4fQhBr6++FQXB8kkgOMbdxBuy 6 | rHzuX5HkElswrN6DQoN/AAAAC2RlbW9zQHNpcmlsAQI= 7 | -----END OPENSSH PRIVATE KEY----- 8 | -------------------------------------------------------------------------------- /fixtures/ed25519.pub: -------------------------------------------------------------------------------- 1 | ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril 2 | -------------------------------------------------------------------------------- /fixtures/rsa: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEAmB97z1CU4c64lZVSpijoO9RDlWJtu+KEWuSi1hKCtB5ozHPa 3 | 7tI+KH6LqHlvwFZkVbo8X2iBkf/Hp/5VD5Ir+Q0njOml5w8+XBMTabawMv7DDy0I 4 | VQC0a6kPnZEvQrf2APgNS3uSz4eDCbu/YQgy08KknSqg7lHGEM0dDOwD7JWgwkfe 5 | s2PlVC+JSjm1FHeMLD96KXU0OhttKlxHq9eBDxq/Ted0v7viSRi6D5W9bjyB/eqC 6 | mOLf0niyEULKHHVYkWohfwKu5D81nf8gi1XVyUkbdwn7W6FeJCwRxrXk0uedSd9j 7 | CaKoxIuEPw7nFmK0H8eR96l1Qfvxth7qyjyBywIDAQABAoIBADMncyTVvhrovt1e 8 | JzrEysNDr65OOQRTOZqvA6rk8prLFwaZdueUP16ynxf6LgAJjRfe1mpm5BtKXcM6 9 | HTRtPOg06jXSY/18/MVNjNuhmUKstL8nr4OWBxWk9iFQLwpKfij5QM8/MLEkqoXd 10 | Yo+oiB75dw16xj8dtHL15mzv+KnXak0AD9IzjFVI33WqD36oc0oYaaO7pRD7HFgP 11 | UO8YQLS6755WYpt2wHVx4s9+YvEeMKUR/Q5OFoEeU/3aBqigzSU/w+ct0NO0vr7q 12 | WcCZ0PpKQ6clKS+zElkbjR0/Zq9F2nnE0GN8B9LHnM+TRLdHZBr/Au2c9SRU+wWs 13 | D/SiTNECgYEAxcvLcJxVr71zDsWGyZB7SQz8s8Q1JMbpKXqJjN+Q34PvcGKSZpAY 14 | OJ1uS491SlzacOaT6az4/NXo/BrG24mzQu5uIAP4bX7sHOYV6vHZ2ABkEp6K2bH0 15 | 3hLsXPfJXZPPG6yJyNF02IrMlvinpwY6Re8dBXtCrapqpJU2rEEXWo8CgYEAxOMV 16 | Js80U+vA6ElAlDL5VeNBJtsGS3nK1zkzkyiKwFaw3lG90s4pq1dN3ridUdPrcaGW 17 | jiNhOR54prJpkn6xAt03ywkiRyPKWB/FbGTp+reAk9R3yUC0uVtcrLzAA/ODirPy 18 | rRqlPKp6F+qQXlohGJjCLV1LWz5UaoiO9zoO8wUCgYEAvZ34QtVsg5Q/t/p+k77x 19 | oX9UxlUjiUUzAvOY57bvYIdPxFKK/M3ImoW51bAKhiZrtu4lAFA1RdUfjIdy+cWR 20 | V2nRotmLkBSr76xXeKsv5pXBWeQpQjcKgtZrR1i37wCi/Gm0kRLTTEALj/OCbWlX 21 | 9fEbxkR7EJedsnflOM8Rv1sCgYB3nBUPfLWnfgO1mjrXTZhX6zV7a3gJhjYKRj/k 22 | 2K5iZsgQZ8xQMtrxspomAjXgrkPMxoP2WdwInVBixOSKENlsigQJHsVqPn4Ax1xi 23 | m3Ph0nUUWfFjnCGusag9cHWecOOq8eMt8pALqO1/dgq6pzqP/M2KTbEn/1e9WLSx 24 | 0N2gGQKBgEoEbsKb2KF8rRrAPy29mPxGTxjmFTtcRuJPaQn8jZptIJe19bn15MOo 25 | lLd92YzoUg1ngkKkLCPwKZwrK8HlIzQ4OgiIkGi6V4Yai9vBB1ptMG2UIID1KE/9 26 | 66pa/JXan1ZD8QYwOktTMb+w9Iigj2X7wx53mztj6jOEoh9Rax2X 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /fixtures/rsa.pub: -------------------------------------------------------------------------------- 1 | ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCYH3vPUJThzriVlVKmKOg71EOVYm274oRa5KLWEoK0HmjMc9ru0j4ofouoeW/AVmRVujxfaIGR/8en/lUPkiv5DSeM6aXnDz5cExNptrAy/sMPLQhVALRrqQ+dkS9Ct/YA+A1Le5LPh4MJu79hCDLTwqSdKqDuUcYQzR0M7APslaDCR96zY+VUL4lKObUUd4wsP3opdTQ6G20qXEer14EPGr9N53S/u+JJGLoPlb1uPIH96oKY4t/SeLIRQsocdViRaiF/Aq7kPzWd/yCLVdXJSRt3CftboV4kLBHGteTS551J32MJoqjEi4Q/DucWYrQfx5H3qXVB+/G2HurKPIHL demos@siril 2 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A pure-Rust library to handle OpenSSH public keys. 2 | //! 3 | //! This crate supports parsing, manipulation, and some basic validation of 4 | //! SSH keys. It provides a struct for encapsulation of SSH keys in projects. 5 | //! 6 | //! `openssh-keys` does not have the ability to generate SSH keys. However, 7 | //! it does allow to construct RSA and DSA keys from their components, so if you 8 | //! generate the keys with another library (say, rust-openssl), then you can 9 | //! output the SSH public keys with this library. 10 | //! 11 | //! # Example 12 | //! 13 | //! ```rust 14 | //! use std::{env, fs, io, path}; 15 | //! use std::io::BufRead; 16 | //! 17 | //! fn inspect_rsa() { 18 | //! let home = env::home_dir().unwrap_or(path::PathBuf::from("/home/core/")); 19 | //! let pub_path = home.join(".ssh").join("id_rsa.pub"); 20 | //! println!("Inspecting '{}':", pub_path.to_string_lossy()); 21 | //! let file = fs::File::open(&pub_path).expect("unable to open RSA pubkey"); 22 | //! let reader = io::BufReader::new(file); 23 | //! 24 | //! for (i, line) in reader.lines().enumerate() { 25 | //! let line = line.expect(&format!("unable to read key at line {}", i + 1)); 26 | //! let pubkey = openssh_keys::PublicKey::parse(&line).expect("unable to parse RSA pubkey"); 27 | //! println!(" * Pubkey #{} -> {}", i + 1, pubkey.to_fingerprint_string()); 28 | //! } 29 | //! } 30 | 31 | mod reader; 32 | mod writer; 33 | 34 | pub mod errors { 35 | use thiserror::Error; 36 | 37 | pub type Result = std::result::Result; 38 | 39 | #[derive(Error, Debug)] 40 | pub enum OpenSSHKeyError { 41 | #[error("I/O error")] 42 | IO { 43 | #[from] 44 | source: std::io::Error, 45 | }, 46 | 47 | #[error("invalid UTF-8")] 48 | InvalidUtf8 { 49 | #[from] 50 | source: std::str::Utf8Error, 51 | }, 52 | 53 | // keep base64::DecodeError out of the public API 54 | #[error("invalid base64: {detail}")] 55 | InvalidBase64 { detail: String }, 56 | 57 | #[error("invalid key format")] 58 | InvalidFormat, 59 | 60 | #[error("unsupported keytype: {keytype}")] 61 | UnsupportedKeyType { keytype: String }, 62 | 63 | #[error("unsupported curve: {curve}")] 64 | UnsupportedCurve { curve: String }, 65 | } 66 | } 67 | 68 | use crate::errors::*; 69 | 70 | use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; 71 | use md5::Md5; 72 | use sha2::{Digest, Sha256}; 73 | 74 | use crate::reader::Reader; 75 | use crate::writer::Writer; 76 | 77 | use std::fmt; 78 | use std::io::{BufRead, BufReader, Read}; 79 | 80 | const SSH_RSA: &str = "ssh-rsa"; 81 | const SSH_DSA: &str = "ssh-dss"; 82 | const SSH_ED25519: &str = "ssh-ed25519"; 83 | const SSH_ED25519_SK: &str = "sk-ssh-ed25519@openssh.com"; 84 | const SSH_ECDSA_256: &str = "ecdsa-sha2-nistp256"; 85 | const SSH_ECDSA_384: &str = "ecdsa-sha2-nistp384"; 86 | const SSH_ECDSA_521: &str = "ecdsa-sha2-nistp521"; 87 | const SSH_ECDSA_SK: &str = "sk-ecdsa-sha2-nistp256@openssh.com"; 88 | const NISTP_256: &str = "nistp256"; 89 | const NISTP_384: &str = "nistp384"; 90 | const NISTP_521: &str = "nistp521"; 91 | 92 | /// Curves for ECDSA 93 | #[derive(Clone, Debug, Copy, PartialEq, Eq, Hash)] 94 | pub enum Curve { 95 | Nistp256, 96 | Nistp384, 97 | Nistp521, 98 | } 99 | 100 | impl Curve { 101 | /// get converts a curve name of the type in the format described in 102 | /// https://tools.ietf.org/html/rfc5656#section-10 and returns a curve 103 | /// object. 104 | fn get(curve: &str) -> Result { 105 | Ok(match curve { 106 | NISTP_256 => Curve::Nistp256, 107 | NISTP_384 => Curve::Nistp384, 108 | NISTP_521 => Curve::Nistp521, 109 | _ => { 110 | return Err(OpenSSHKeyError::UnsupportedCurve { 111 | curve: curve.to_string(), 112 | }) 113 | } 114 | }) 115 | } 116 | 117 | /// curvetype gets the curve name in the format described in 118 | /// https://tools.ietf.org/html/rfc5656#section-10 119 | fn curvetype(self) -> &'static str { 120 | match self { 121 | Curve::Nistp256 => NISTP_256, 122 | Curve::Nistp384 => NISTP_384, 123 | Curve::Nistp521 => NISTP_521, 124 | } 125 | } 126 | } 127 | 128 | impl fmt::Display for Curve { 129 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 130 | write!(f, "{}", self.curvetype()) 131 | } 132 | } 133 | 134 | /// Data is the representation of the data section of an ssh public key. it is 135 | /// an enum with all the different supported key algorithms. 136 | #[derive(Clone, Debug, PartialEq, Eq)] 137 | pub enum Data { 138 | Rsa { 139 | exponent: Vec, 140 | modulus: Vec, 141 | }, 142 | Dsa { 143 | p: Vec, 144 | q: Vec, 145 | g: Vec, 146 | pub_key: Vec, 147 | }, 148 | Ed25519 { 149 | key: Vec, 150 | }, 151 | Ed25519Sk { 152 | key: Vec, 153 | application: Vec, 154 | }, 155 | Ecdsa { 156 | curve: Curve, 157 | key: Vec, 158 | }, 159 | EcdsaSk { 160 | curve: Curve, 161 | key: Vec, 162 | application: Vec, 163 | }, 164 | } 165 | 166 | /// `PublicKey` is the struct representation of an ssh public key. 167 | #[derive(Clone, Debug, Eq)] 168 | pub struct PublicKey { 169 | pub options: Option, 170 | pub data: Data, 171 | pub comment: Option, 172 | } 173 | 174 | impl fmt::Display for PublicKey { 175 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 176 | write!(f, "{}", self.to_key_format()) 177 | } 178 | } 179 | 180 | /// Two public keys are equivalent if their data sections are equivalent, 181 | /// ignoring their comment section. 182 | impl core::cmp::PartialEq for PublicKey { 183 | fn eq(&self, other: &PublicKey) -> bool { 184 | self.data == other.data 185 | } 186 | } 187 | 188 | impl std::str::FromStr for PublicKey { 189 | type Err = OpenSSHKeyError; 190 | fn from_str(s: &str) -> Result { 191 | PublicKey::parse(s) 192 | } 193 | } 194 | 195 | impl PublicKey { 196 | /// parse takes a string and parses it as a public key from an authorized 197 | /// keys file. the format it expects is described here 198 | /// https://tools.ietf.org/html/rfc4253#section-6.6 and here 199 | /// https://man.openbsd.org/sshd#AUTHORIZED_KEYS_FILE_FORMAT 200 | /// 201 | /// sshd describes an additional, optional "options" field for public keys 202 | /// in the authorized_keys file. This field allows for passing of options to 203 | /// sshd that only apply to that particular public key. This means that a 204 | /// public key in an authorized keys file is a strict superset of the public 205 | /// key format described in rfc4253. Another superset of a public key is 206 | /// what is present in the known_hosts file. This file has a hostname as the 207 | /// first thing on the line. This parser treats the hostname the same as an 208 | /// option field. When one of these things is found at the beginning of a 209 | /// line, it is treated as a semi-opaque string that is carried with the 210 | /// public key and reproduced when the key is printed. It is not entirely 211 | /// opaque, since the parser needs to be aware of quoting semantics within 212 | /// the option fields, since options surrounded by double quotes can contain 213 | /// spaces, which are otherwise the main delimiter of the parts of a public 214 | /// key. 215 | /// 216 | /// You can parse and output ssh keys like this 217 | /// 218 | /// ``` 219 | /// let rsa_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCcMCOEryBa8IkxXacjIawaQPp08hR5h7+4vZePZ7DByTG3tqKgZYRJ86BaR+4fmdikFoQjvLJVUmwniq3wixhkP7VLCbqip3YHzxXrzxkbPC3w3O1Bdmifwn9cb8RcZXfXncCsSu+h5XCtQ5BOi41Iit3d13gIe/rfXVDURmRanV6R7Voljxdjmp/zyReuzc2/w5SI6Boi4tmcUlxAI7sFuP1kA3pABDhPtc3TDgAcPUIBoDCoY8q2egI197UuvbgsW2qraUcuQxbMvJOMSFg2FQrE2bpEqC4CtBn7+HiJrkVOHjV7bvSv7jd1SuX5XqkwMCRtdMuRpJr7CyZoFL5n demos@anduin"; 220 | /// let key = openssh_keys::PublicKey::parse(rsa_key).unwrap(); 221 | /// let out = key.to_string(); 222 | /// assert_eq!(rsa_key, out); 223 | /// ``` 224 | /// 225 | /// parse somewhat attempts to keep track of comments, but it doesn't fully 226 | /// comply with the rfc in that regard. 227 | pub fn parse(key: &str) -> Result { 228 | // trim leading and trailing whitespace 229 | let key = key.trim(); 230 | // try just parsing the keys straight up 231 | PublicKey::try_key_parse(key).or_else(|e| { 232 | // remove the preceeding string 233 | let mut key_start = 0; 234 | let mut escape = false; 235 | let mut quote = false; 236 | let mut marker = key.starts_with('@'); 237 | for (i, c) in key.chars().enumerate() { 238 | if c == '\\' { 239 | escape = true; 240 | continue; 241 | } 242 | if escape { 243 | escape = false; 244 | continue; 245 | } 246 | if c == '"' { 247 | quote = !quote; 248 | } 249 | if !quote && (c == ' ' || c == '\t') { 250 | if marker { 251 | marker = false; 252 | continue; 253 | } else { 254 | key_start = i + 1; 255 | break; 256 | } 257 | } 258 | } 259 | let mut parsed = PublicKey::try_key_parse(&key[key_start..]).map_err(|_| e)?; 260 | parsed.options = Some(key[..key_start - 1].into()); 261 | Ok(parsed) 262 | }) 263 | } 264 | 265 | fn try_key_parse(key: &str) -> Result { 266 | // then parse the key according to rfc4253 267 | let (keytype, remaining) = key 268 | .split_once(char::is_whitespace) 269 | .ok_or(OpenSSHKeyError::InvalidFormat)?; 270 | 271 | let (data, comment) = remaining 272 | .split_once(char::is_whitespace) 273 | .unwrap_or((remaining, "")); 274 | 275 | let comment = comment.trim(); 276 | if comment.contains('\n') { 277 | return Err(OpenSSHKeyError::InvalidFormat); 278 | } 279 | let comment = if comment.is_empty() { 280 | None 281 | } else { 282 | Some(comment.to_owned()) 283 | }; 284 | 285 | let buf = BASE64 286 | .decode(data) 287 | .map_err(|e| OpenSSHKeyError::InvalidBase64 { 288 | detail: format!("{}", e), 289 | })?; 290 | let mut reader = Reader::new(&buf); 291 | let data_keytype = reader.read_string()?; 292 | if keytype != data_keytype { 293 | return Err(OpenSSHKeyError::InvalidFormat); 294 | } 295 | 296 | let data = match keytype { 297 | SSH_RSA => { 298 | // the data for an rsa key consists of three pieces: 299 | // ssh-rsa public-exponent modulus 300 | // see ssh-rsa format in https://tools.ietf.org/html/rfc4253#section-6.6 301 | let e = reader.read_mpint()?; 302 | let n = reader.read_mpint()?; 303 | Data::Rsa { 304 | exponent: e.into(), 305 | modulus: n.into(), 306 | } 307 | } 308 | SSH_DSA => { 309 | // the data stored for a dsa key is, in order 310 | // ssh-dsa p q g public-key 311 | // p and q are primes 312 | // g = h^((p-1)/q) where 1 < h < p-1 313 | // public-key is the value that is actually generated in 314 | // relation to the secret key 315 | // see https://en.wikipedia.org/wiki/Digital_Signature_Algorithm 316 | // and ssh-dss format in https://tools.ietf.org/html/rfc4253#section-6.6 317 | // and https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L743 318 | let p = reader.read_mpint()?; 319 | let q = reader.read_mpint()?; 320 | let g = reader.read_mpint()?; 321 | let pub_key = reader.read_mpint()?; 322 | Data::Dsa { 323 | p: p.into(), 324 | q: q.into(), 325 | g: g.into(), 326 | pub_key: pub_key.into(), 327 | } 328 | } 329 | SSH_ED25519 => { 330 | // the data stored for an ed25519 is just the point on the curve 331 | // for now the exact specification of the point on that curve is 332 | // a mystery to me, instead of having to compute it, we just 333 | // assume the key we got is correct and copy that verbatim. this 334 | // also means we have to disallow arbitrary construction until 335 | // furthur notice. 336 | // see https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L772 337 | let key = reader.read_bytes()?; 338 | Data::Ed25519 { key: key.into() } 339 | } 340 | SSH_ED25519_SK => { 341 | // same as above 342 | let key = reader.read_bytes()?; 343 | let application = reader.read_bytes()?; 344 | Data::Ed25519Sk { 345 | key: key.into(), 346 | application: application.into(), 347 | } 348 | } 349 | SSH_ECDSA_256 | SSH_ECDSA_384 | SSH_ECDSA_521 => { 350 | // ecdsa is of the form 351 | // ecdsa-sha2-[identifier] [identifier] [data] 352 | // the identifier is one of nistp256, nistp384, nistp521 353 | // the data is some weird thing described in section 2.3.4 and 354 | // 2.3.4 of https://www.secg.org/sec1-v2.pdf so for now we 355 | // aren't going to bother actually computing it and instead we 356 | // will just not let you construct them. 357 | // 358 | // see the data definition at 359 | // https://tools.ietf.org/html/rfc5656#section-3.1 360 | // and the openssh output 361 | // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L753 362 | // and the openssh buffer writer implementation 363 | // https://github.com/openssh/openssh-portable/blob/master/sshbuf-getput-crypto.c#L192 364 | // and the openssl point2oct implementation 365 | // https://github.com/openssl/openssl/blob/aa8f3d76fcf1502586435631be16faa1bef3cdf7/crypto/ec/ec_oct.c#L82 366 | let curve = reader.read_string()?; 367 | let key = reader.read_bytes()?; 368 | Data::Ecdsa { 369 | curve: Curve::get(curve)?, 370 | key: key.into(), 371 | } 372 | } 373 | SSH_ECDSA_SK => { 374 | // same as above (like there, we don't assert that the curve matches what was specified in the keytype) 375 | let curve = reader.read_string()?; 376 | let key = reader.read_bytes()?; 377 | let application = reader.read_bytes()?; 378 | Data::EcdsaSk { 379 | curve: Curve::get(curve)?, 380 | key: key.into(), 381 | application: application.into(), 382 | } 383 | } 384 | _ => { 385 | return Err(OpenSSHKeyError::UnsupportedKeyType { 386 | keytype: keytype.to_string(), 387 | }) 388 | } 389 | }; 390 | 391 | Ok(PublicKey { 392 | options: None, 393 | data, 394 | comment, 395 | }) 396 | } 397 | 398 | /// read_keys takes a reader and parses it as an authorized_keys file. it 399 | /// returns an error if it can't read or parse any of the public keys in the 400 | /// list. 401 | pub fn read_keys(r: R) -> Result> 402 | where 403 | R: Read, 404 | { 405 | let keybuf = BufReader::new(r); 406 | // authorized_keys files are newline-separated lists of public keys 407 | let mut keys = vec![]; 408 | for key in keybuf.lines() { 409 | let key = key?; 410 | // skip any empty lines and any comment lines (prefixed with '#') 411 | if !key.is_empty() && !(key.trim().starts_with('#')) { 412 | keys.push(PublicKey::parse(&key)?); 413 | } 414 | } 415 | Ok(keys) 416 | } 417 | 418 | /// get an ssh public key from rsa components 419 | pub fn from_rsa(e: Vec, n: Vec) -> Self { 420 | PublicKey { 421 | options: None, 422 | data: Data::Rsa { 423 | exponent: e, 424 | modulus: n, 425 | }, 426 | comment: None, 427 | } 428 | } 429 | 430 | /// get an ssh public key from dsa components 431 | pub fn from_dsa(p: Vec, q: Vec, g: Vec, pkey: Vec) -> Self { 432 | PublicKey { 433 | options: None, 434 | data: Data::Dsa { 435 | p, 436 | q, 437 | g, 438 | pub_key: pkey, 439 | }, 440 | comment: None, 441 | } 442 | } 443 | 444 | /// keytype returns the type of key in the format described by rfc4253 445 | /// The output will be ssh-{type} where type is [rsa,ed25519,ecdsa,dsa] 446 | pub fn keytype(&self) -> &'static str { 447 | match self.data { 448 | Data::Rsa { .. } => SSH_RSA, 449 | Data::Dsa { .. } => SSH_DSA, 450 | Data::Ed25519 { .. } => SSH_ED25519, 451 | Data::Ed25519Sk { .. } => SSH_ED25519_SK, 452 | Data::Ecdsa { ref curve, .. } => match *curve { 453 | Curve::Nistp256 => SSH_ECDSA_256, 454 | Curve::Nistp384 => SSH_ECDSA_384, 455 | Curve::Nistp521 => SSH_ECDSA_521, 456 | }, 457 | Data::EcdsaSk { .. } => SSH_ECDSA_SK, 458 | } 459 | } 460 | 461 | /// data returns the data section of the key in the format described by rfc4253 462 | /// the contents of the data section depend on the keytype. For RSA keys it 463 | /// contains the keytype, exponent, and modulus in that order. Other types 464 | /// have other data sections. This function doesn't base64 encode the data, 465 | /// that task is left to the consumer of the output. 466 | pub fn data(&self) -> Vec { 467 | let mut writer = Writer::new(); 468 | writer.write_string(self.keytype()); 469 | match self.data { 470 | Data::Rsa { 471 | ref exponent, 472 | ref modulus, 473 | } => { 474 | // the data for an rsa key consists of three pieces: 475 | // ssh-rsa public-exponent modulus 476 | // see ssh-rsa format in https://tools.ietf.org/html/rfc4253#section-6.6 477 | writer.write_mpint(exponent.clone()); 478 | writer.write_mpint(modulus.clone()); 479 | } 480 | Data::Dsa { 481 | ref p, 482 | ref q, 483 | ref g, 484 | ref pub_key, 485 | } => { 486 | writer.write_mpint(p.clone()); 487 | writer.write_mpint(q.clone()); 488 | writer.write_mpint(g.clone()); 489 | writer.write_mpint(pub_key.clone()); 490 | } 491 | Data::Ed25519 { ref key } => { 492 | writer.write_bytes(key.clone()); 493 | } 494 | Data::Ed25519Sk { 495 | ref key, 496 | ref application, 497 | } => { 498 | writer.write_bytes(key.clone()); 499 | writer.write_bytes(application.clone()); 500 | } 501 | Data::Ecdsa { ref curve, ref key } => { 502 | writer.write_string(curve.curvetype()); 503 | writer.write_bytes(key.clone()); 504 | } 505 | Data::EcdsaSk { 506 | ref curve, 507 | ref key, 508 | ref application, 509 | } => { 510 | writer.write_string(curve.curvetype()); 511 | writer.write_bytes(key.clone()); 512 | writer.write_bytes(application.clone()); 513 | } 514 | } 515 | writer.into_vec() 516 | } 517 | 518 | pub fn set_comment(&mut self, comment: &str) { 519 | self.comment = Some(comment.to_string()); 520 | } 521 | 522 | /// to_key_format returns a string representation of the ssh key. this string 523 | /// output is appropriate to use as a public key file. it adheres to the 524 | /// format described in https://tools.ietf.org/html/rfc4253#section-6.6 525 | /// 526 | /// an ssh key consists of four pieces: 527 | /// 528 | /// [options] ssh-keytype data comment 529 | /// 530 | /// the output of the data section is described in the documentation for the 531 | /// data function. the options section is optional, and is not part of the 532 | /// spec. rather, it is a field present in authorized_keys files or 533 | /// known_hosts files. 534 | pub fn to_key_format(&self) -> String { 535 | let key = format!( 536 | "{} {} {}", 537 | self.keytype(), 538 | BASE64.encode(self.data()), 539 | self.comment.clone().unwrap_or_default() 540 | ); 541 | if let Some(ref options) = self.options { 542 | format!("{} {}", options, key) 543 | } else { 544 | key 545 | } 546 | } 547 | 548 | /// size returns the size of the stored ssh key. for rsa keys this is 549 | /// determined by the number of bits in the modulus. for dsa keys it's the 550 | /// number of bits in the prime p. 551 | /// 552 | /// see https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L261 553 | /// for more details 554 | pub fn size(&self) -> usize { 555 | match self.data { 556 | Data::Rsa { ref modulus, .. } => modulus.len() * 8, 557 | Data::Dsa { ref p, .. } => p.len() * 8, 558 | Data::Ed25519 { .. } | Data::Ed25519Sk { .. } => 256, // ?? 559 | Data::Ecdsa { ref curve, .. } | Data::EcdsaSk { ref curve, .. } => match *curve { 560 | Curve::Nistp256 => 256, 561 | Curve::Nistp384 => 384, 562 | Curve::Nistp521 => 521, 563 | }, 564 | } 565 | } 566 | 567 | /// fingerprint returns a string representing the fingerprint of the ssh key 568 | /// the format of the fingerprint is described tersely in 569 | /// https://tools.ietf.org/html/rfc4716#page-6. This uses the ssh-keygen 570 | /// defaults of a base64 encoded SHA256 hash. 571 | pub fn fingerprint(&self) -> String { 572 | let data = self.data(); 573 | let mut hasher = Sha256::new(); 574 | hasher.update(&data); 575 | let hashed = hasher.finalize(); 576 | let mut fingerprint = BASE64.encode(hashed); 577 | // trim padding characters off the end. I'm not clear on exactly what 578 | // this is doing but they do it here and the test fails without it 579 | // https://github.com/openssh/openssh-portable/blob/643c2ad82910691b2240551ea8b14472f60b5078/sshkey.c#L918 580 | if let Some(l) = fingerprint.find('=') { 581 | fingerprint.truncate(l); 582 | }; 583 | fingerprint 584 | } 585 | 586 | /// to_fingerprint_string prints out the fingerprint in the same format used 587 | /// by `ssh-keygen -l -f key`, specifically the implementation here - 588 | /// https://github.com/openssh/openssh-portable/blob/master/ssh-keygen.c#L842 589 | /// right now it just sticks with the defaults of a base64 encoded SHA256 590 | /// hash. 591 | pub fn to_fingerprint_string(&self) -> String { 592 | let keytype = match self.data { 593 | Data::Rsa { .. } => "RSA", 594 | Data::Dsa { .. } => "DSA", 595 | Data::Ed25519 { .. } => "ED25519", 596 | Data::Ed25519Sk { .. } => "ED25519_SK", 597 | Data::Ecdsa { .. } => "ECDSA", 598 | Data::EcdsaSk { .. } => "ECDSA_SK", 599 | }; 600 | 601 | let comment = self 602 | .comment 603 | .clone() 604 | .unwrap_or_else(|| "no comment".to_string()); 605 | format!( 606 | "{} SHA256:{} {} ({})", 607 | self.size(), 608 | self.fingerprint(), 609 | comment, 610 | keytype 611 | ) 612 | } 613 | 614 | /// fingerprint_m5 returns a string representing the fingerprint of the ssh key 615 | /// the format of the fingerprint is MD5, and the output looks like, 616 | /// `fb:a0:5b:a0:21:01:47:33:3b:8d:9e:14:1a:4c:db:6d` . 617 | pub fn fingerprint_md5(&self) -> String { 618 | let mut sh = Md5::default(); 619 | sh.update(self.data()); 620 | 621 | let md5: Vec = sh.finalize().iter().map(|n| format!("{:02x}", n)).collect(); 622 | md5.join(":") 623 | } 624 | 625 | /// to_fingerprint_m5_string prints out the fingerprint in the in hex format used 626 | /// by `ssh-keygen -l -E md5 -f key`, and the output looks like, 627 | /// `2048 MD5:fb:a0:5b:a0:21:01:47:33:3b:8d:9e:14:1a:4c:db:6d demos@anduin (RSA)` . 628 | pub fn to_fingerprint_md5_string(&self) -> String { 629 | let keytype = match self.data { 630 | Data::Rsa { .. } => "RSA", 631 | Data::Dsa { .. } => "DSA", 632 | Data::Ed25519 { .. } => "ED25519", 633 | Data::Ed25519Sk { .. } => "ED25519_SK", 634 | Data::Ecdsa { .. } => "ECDSA", 635 | Data::EcdsaSk { .. } => "ECDSA_SK", 636 | }; 637 | 638 | let comment = self 639 | .comment 640 | .clone() 641 | .unwrap_or_else(|| "no comment".to_string()); 642 | format!( 643 | "{} MD5:{} {} ({})", 644 | self.size(), 645 | self.fingerprint_md5(), 646 | comment, 647 | keytype 648 | ) 649 | } 650 | } 651 | 652 | #[cfg(test)] 653 | mod tests { 654 | use super::*; 655 | 656 | const TEST_RSA_KEY: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCYH3vPUJThzriVlVKmKOg71EOVYm274oRa5KLWEoK0HmjMc9ru0j4ofouoeW/AVmRVujxfaIGR/8en/lUPkiv5DSeM6aXnDz5cExNptrAy/sMPLQhVALRrqQ+dkS9Ct/YA+A1Le5LPh4MJu79hCDLTwqSdKqDuUcYQzR0M7APslaDCR96zY+VUL4lKObUUd4wsP3opdTQ6G20qXEer14EPGr9N53S/u+JJGLoPlb1uPIH96oKY4t/SeLIRQsocdViRaiF/Aq7kPzWd/yCLVdXJSRt3CftboV4kLBHGteTS551J32MJoqjEi4Q/DucWYrQfx5H3qXVB+/G2HurKPIHL demos@siril"; 657 | const TEST_RSA_COMMENT_KEY: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCYH3vPUJThzriVlVKmKOg71EOVYm274oRa5KLWEoK0HmjMc9ru0j4ofouoeW/AVmRVujxfaIGR/8en/lUPkiv5DSeM6aXnDz5cExNptrAy/sMPLQhVALRrqQ+dkS9Ct/YA+A1Le5LPh4MJu79hCDLTwqSdKqDuUcYQzR0M7APslaDCR96zY+VUL4lKObUUd4wsP3opdTQ6G20qXEer14EPGr9N53S/u+JJGLoPlb1uPIH96oKY4t/SeLIRQsocdViRaiF/Aq7kPzWd/yCLVdXJSRt3CftboV4kLBHGteTS551J32MJoqjEi4Q/DucWYrQfx5H3qXVB+/G2HurKPIHL test"; 658 | const TEST_DSA_KEY: &str = "ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== demos@siril"; 659 | const TEST_ED25519_KEY: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril"; 660 | const TEST_ED25519_SK_KEY: &str = "sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIEX/dQ0v4127bEo8eeG1EV0ApO2lWbSnN6RWusn/NjqIAAAABHNzaDo= demos@siril"; 661 | const TEST_ECDSA256_KEY: &str = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIhfLQrww4DlhYzbSWXoX3ctOQ0jVosvfHfW+QWVotksbPzM2YgkIikTpoHUfZrYpJKWx7WYs5aqeLkdCDdk+jk= demos@siril"; 662 | const TEST_ECDSA_SK_KEY: &str = "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBDZ+f5tSRhlB7EN39f93SscTN5PUvbD3UQsNrlE1ZdbwPMMRul2zlPiUvwAvnJitW0jlD/vwZOW2YN+q+iZ5c0MAAAAEc3NoOg== demos@siril"; 663 | 664 | #[test] 665 | fn rsa_parse_to_string() { 666 | let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 667 | let out = key.to_string(); 668 | assert_eq!(TEST_RSA_KEY, out); 669 | } 670 | 671 | #[test] 672 | fn rsa_size() { 673 | let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 674 | assert_eq!(2048, key.size()); 675 | } 676 | 677 | #[test] 678 | fn rsa_keytype() { 679 | let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 680 | assert_eq!("ssh-rsa", key.keytype()); 681 | } 682 | 683 | #[test] 684 | fn rsa_fingerprint() { 685 | let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 686 | assert_eq!( 687 | "YTw/JyJmeAAle1/7zuZkPP0C73BQ+6XrFEt2/Wy++2o", 688 | key.fingerprint() 689 | ); 690 | } 691 | 692 | #[test] 693 | fn rsa_fingerprint_string() { 694 | let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 695 | assert_eq!( 696 | "2048 SHA256:YTw/JyJmeAAle1/7zuZkPP0C73BQ+6XrFEt2/Wy++2o demos@siril (RSA)", 697 | key.to_fingerprint_string() 698 | ); 699 | } 700 | 701 | #[test] 702 | fn rsa_fingerprint_md5() { 703 | let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 704 | assert_eq!( 705 | "e9:a1:5b:cd:a3:69:d2:d9:17:cb:09:3e:78:e1:0d:dd", 706 | key.fingerprint_md5() 707 | ); 708 | } 709 | 710 | #[test] 711 | fn rsa_fingerprint_md5_string() { 712 | let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 713 | assert_eq!( 714 | "2048 MD5:e9:a1:5b:cd:a3:69:d2:d9:17:cb:09:3e:78:e1:0d:dd demos@siril (RSA)", 715 | key.to_fingerprint_md5_string() 716 | ); 717 | } 718 | 719 | #[test] 720 | fn rsa_set_comment() { 721 | let mut key = PublicKey::parse(TEST_RSA_KEY).unwrap(); 722 | key.set_comment("test"); 723 | let out = key.to_string(); 724 | assert_eq!(TEST_RSA_COMMENT_KEY, out); 725 | } 726 | 727 | #[test] 728 | fn dsa_parse_to_string() { 729 | let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); 730 | let out = key.to_string(); 731 | assert_eq!(TEST_DSA_KEY, out); 732 | } 733 | 734 | #[test] 735 | fn dsa_size() { 736 | let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); 737 | assert_eq!(1024, key.size()); 738 | } 739 | 740 | #[test] 741 | fn dsa_keytype() { 742 | let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); 743 | assert_eq!("ssh-dss", key.keytype()); 744 | } 745 | 746 | #[test] 747 | fn dsa_fingerprint() { 748 | let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); 749 | assert_eq!( 750 | "/Pyxrjot1Hs5PN2Dpg/4pK2wxxtP9Igc3sDTAWIEXT4", 751 | key.fingerprint() 752 | ); 753 | } 754 | 755 | #[test] 756 | fn dsa_fingerprint_string() { 757 | let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); 758 | assert_eq!( 759 | "1024 SHA256:/Pyxrjot1Hs5PN2Dpg/4pK2wxxtP9Igc3sDTAWIEXT4 demos@siril (DSA)", 760 | key.to_fingerprint_string() 761 | ); 762 | } 763 | 764 | #[test] 765 | fn ed25519_parse_to_string() { 766 | let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); 767 | let out = key.to_string(); 768 | assert_eq!(TEST_ED25519_KEY, out); 769 | } 770 | 771 | #[test] 772 | fn ed25519_size() { 773 | let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); 774 | assert_eq!(256, key.size()); 775 | } 776 | 777 | #[test] 778 | fn ed25519_keytype() { 779 | let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); 780 | assert_eq!("ssh-ed25519", key.keytype()); 781 | } 782 | 783 | #[test] 784 | fn ed25519_fingerprint() { 785 | let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); 786 | assert_eq!( 787 | "A/lHzXxsgbp11dcKKfSDyNQIdep7EQgZEoRYVDBfNdI", 788 | key.fingerprint() 789 | ); 790 | } 791 | 792 | #[test] 793 | fn ed25519_fingerprint_string() { 794 | let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); 795 | assert_eq!( 796 | "256 SHA256:A/lHzXxsgbp11dcKKfSDyNQIdep7EQgZEoRYVDBfNdI demos@siril (ED25519)", 797 | key.to_fingerprint_string() 798 | ); 799 | } 800 | 801 | #[test] 802 | fn ed25519_sk_parse_to_string() { 803 | let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); 804 | let out = key.to_string(); 805 | assert_eq!(TEST_ED25519_SK_KEY, out); 806 | } 807 | 808 | #[test] 809 | fn ed25519_sk_size() { 810 | let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); 811 | assert_eq!(256, key.size()); 812 | } 813 | 814 | #[test] 815 | fn ed25519_sk_keytype() { 816 | let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); 817 | assert_eq!("sk-ssh-ed25519@openssh.com", key.keytype()); 818 | } 819 | 820 | #[test] 821 | fn ed25519_sk_fingerprint() { 822 | let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); 823 | assert_eq!( 824 | "U8IKRkIHed6vFMTflwweA3HhIf2DWgZ8EFTm9fgwOUk", 825 | key.fingerprint() 826 | ); 827 | } 828 | 829 | #[test] 830 | fn ed25519_sk_fingerprint_string() { 831 | let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); 832 | assert_eq!( 833 | "256 SHA256:U8IKRkIHed6vFMTflwweA3HhIf2DWgZ8EFTm9fgwOUk demos@siril (ED25519_SK)", 834 | key.to_fingerprint_string() 835 | ); 836 | } 837 | 838 | #[test] 839 | fn ecdsa256_parse_to_string() { 840 | let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); 841 | let out = key.to_string(); 842 | assert_eq!(TEST_ECDSA256_KEY, out); 843 | } 844 | 845 | #[test] 846 | fn ecdsa256_size() { 847 | let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); 848 | assert_eq!(256, key.size()); 849 | } 850 | 851 | #[test] 852 | fn ecdsa256_keytype() { 853 | let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); 854 | assert_eq!("ecdsa-sha2-nistp256", key.keytype()); 855 | } 856 | 857 | #[test] 858 | fn ecdsa256_fingerprint() { 859 | let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); 860 | assert_eq!( 861 | "BzS5YXMW/d2vFk8Oqh+nKmvKr8X/FTLBfJgDGLu5GAs", 862 | key.fingerprint() 863 | ); 864 | } 865 | 866 | #[test] 867 | fn ecdsa256_fingerprint_string() { 868 | let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); 869 | assert_eq!( 870 | "256 SHA256:BzS5YXMW/d2vFk8Oqh+nKmvKr8X/FTLBfJgDGLu5GAs demos@siril (ECDSA)", 871 | key.to_fingerprint_string() 872 | ); 873 | } 874 | 875 | #[test] 876 | fn ecdsa_sk_parse_to_string() { 877 | let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); 878 | let out = key.to_string(); 879 | assert_eq!(TEST_ECDSA_SK_KEY, out); 880 | } 881 | 882 | #[test] 883 | fn ecdsa_sk_size() { 884 | let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); 885 | assert_eq!(256, key.size()); 886 | } 887 | 888 | #[test] 889 | fn ecdsa_sk_keytype() { 890 | let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); 891 | assert_eq!("sk-ecdsa-sha2-nistp256@openssh.com", key.keytype()); 892 | } 893 | 894 | #[test] 895 | fn ecdsa_sk_fingerprint() { 896 | let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); 897 | assert_eq!( 898 | "N0sNKBgWKK8usPuPegtgzHQQA9vQ/dRhAEhwFDAnLA4", 899 | key.fingerprint() 900 | ); 901 | } 902 | 903 | #[test] 904 | fn ecdsa_sk_fingerprint_string() { 905 | let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); 906 | assert_eq!( 907 | "256 SHA256:N0sNKBgWKK8usPuPegtgzHQQA9vQ/dRhAEhwFDAnLA4 demos@siril (ECDSA_SK)", 908 | key.to_fingerprint_string() 909 | ); 910 | } 911 | 912 | #[test] 913 | fn option_parse() { 914 | let key = PublicKey::parse("agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); 915 | assert_eq!(Some("agent-forwarding".into()), key.options); 916 | assert_eq!("agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); 917 | let key = PublicKey::parse("from=\"*.sales.example.net,!pc.sales.example.net\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); 918 | assert_eq!( 919 | Some("from=\"*.sales.example.net,!pc.sales.example.net\"".into()), 920 | key.options 921 | ); 922 | assert_eq!("from=\"*.sales.example.net,!pc.sales.example.net\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); 923 | let key = PublicKey::parse("permitopen=\"192.0.2.1:80\",permitopen=\"192.0.2.2:25\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); 924 | assert_eq!( 925 | Some("permitopen=\"192.0.2.1:80\",permitopen=\"192.0.2.2:25\"".into()), 926 | key.options 927 | ); 928 | assert_eq!("permitopen=\"192.0.2.1:80\",permitopen=\"192.0.2.2:25\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); 929 | let key = PublicKey::parse("command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); 930 | assert_eq!( 931 | Some("command=\"echo \\\"holy shell escaping batman\\\"\"".into()), 932 | key.options 933 | ); 934 | assert_eq!("command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); 935 | let key = PublicKey::parse("command=\"dump /home\",no-pty,no-port-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); 936 | assert_eq!( 937 | Some("command=\"dump /home\",no-pty,no-port-forwarding".into()), 938 | key.options 939 | ); 940 | assert_eq!("command=\"dump /home\",no-pty,no-port-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); 941 | } 942 | 943 | #[test] 944 | fn hostname_parse() { 945 | let key = PublicKey::parse("ec2-52-53-211-129.us-west-1.compute.amazonaws.com,52.53.211.129 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFHnC16I49ccjBo68lvN1+zpnAuTGbZjHFi2JRgPZK5o02UDCrFYCUhuS3oCh75+6YmVyReLZAyAM7S/5wjMzTY=").unwrap(); 946 | assert_eq!( 947 | Some("ec2-52-53-211-129.us-west-1.compute.amazonaws.com,52.53.211.129".into()), 948 | key.options 949 | ); 950 | assert_eq!("ec2-52-53-211-129.us-west-1.compute.amazonaws.com,52.53.211.129 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFHnC16I49ccjBo68lvN1+zpnAuTGbZjHFi2JRgPZK5o02UDCrFYCUhuS3oCh75+6YmVyReLZAyAM7S/5wjMzTY=", key.to_string().trim()); 951 | let key = PublicKey::parse("[fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAopjUBQqif5ILeoMHjJ9wGlGs2eNHEv3+OAiiEDHCapNm3guNa+T/ZMtedaC/0P8bLBCXMiyNQU04N/IRyN3Mp/SGhtGJl1PDENXzPB9aoxsB2HHc8s8P7mxal1G4BtCT/fJM5XywEHWAcHkzW91iTK+ApAdqt6AHj35ogil9maFlUNKcXz2aW27hdbDtC0fautvWd9RIITHPq00rdvaHjRcc2msv8LddhBkStP8FrB39RPu9M+ikBkTwdQTSGcIBDYJgt3la2KMwmU1F81cq17wb21lPriBwr626lBiir/WdrBsoAsANeZfyzpAm8K4ssI3eu9eklxpEKdAdNRJbpQ==").unwrap(); 952 | assert_eq!( 953 | Some("[fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090".into()), 954 | key.options 955 | ); 956 | assert_eq!("[fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAopjUBQqif5ILeoMHjJ9wGlGs2eNHEv3+OAiiEDHCapNm3guNa+T/ZMtedaC/0P8bLBCXMiyNQU04N/IRyN3Mp/SGhtGJl1PDENXzPB9aoxsB2HHc8s8P7mxal1G4BtCT/fJM5XywEHWAcHkzW91iTK+ApAdqt6AHj35ogil9maFlUNKcXz2aW27hdbDtC0fautvWd9RIITHPq00rdvaHjRcc2msv8LddhBkStP8FrB39RPu9M+ikBkTwdQTSGcIBDYJgt3la2KMwmU1F81cq17wb21lPriBwr626lBiir/WdrBsoAsANeZfyzpAm8K4ssI3eu9eklxpEKdAdNRJbpQ==", key.to_string().trim()); 957 | let key = PublicKey::parse("@revoked [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAopjUBQqif5ILeoMHjJ9wGlGs2eNHEv3+OAiiEDHCapNm3guNa+T/ZMtedaC/0P8bLBCXMiyNQU04N/IRyN3Mp/SGhtGJl1PDENXzPB9aoxsB2HHc8s8P7mxal1G4BtCT/fJM5XywEHWAcHkzW91iTK+ApAdqt6AHj35ogil9maFlUNKcXz2aW27hdbDtC0fautvWd9RIITHPq00rdvaHjRcc2msv8LddhBkStP8FrB39RPu9M+ikBkTwdQTSGcIBDYJgt3la2KMwmU1F81cq17wb21lPriBwr626lBiir/WdrBsoAsANeZfyzpAm8K4ssI3eu9eklxpEKdAdNRJbpQ==").unwrap(); 958 | assert_eq!( 959 | Some("@revoked [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090".into()), 960 | key.options 961 | ); 962 | assert_eq!("@revoked [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAopjUBQqif5ILeoMHjJ9wGlGs2eNHEv3+OAiiEDHCapNm3guNa+T/ZMtedaC/0P8bLBCXMiyNQU04N/IRyN3Mp/SGhtGJl1PDENXzPB9aoxsB2HHc8s8P7mxal1G4BtCT/fJM5XywEHWAcHkzW91iTK+ApAdqt6AHj35ogil9maFlUNKcXz2aW27hdbDtC0fautvWd9RIITHPq00rdvaHjRcc2msv8LddhBkStP8FrB39RPu9M+ikBkTwdQTSGcIBDYJgt3la2KMwmU1F81cq17wb21lPriBwr626lBiir/WdrBsoAsANeZfyzpAm8K4ssI3eu9eklxpEKdAdNRJbpQ==", key.to_string().trim()); 963 | let key = PublicKey::parse("@cert-authority [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAopjUBQqif5ILeoMHjJ9wGlGs2eNHEv3+OAiiEDHCapNm3guNa+T/ZMtedaC/0P8bLBCXMiyNQU04N/IRyN3Mp/SGhtGJl1PDENXzPB9aoxsB2HHc8s8P7mxal1G4BtCT/fJM5XywEHWAcHkzW91iTK+ApAdqt6AHj35ogil9maFlUNKcXz2aW27hdbDtC0fautvWd9RIITHPq00rdvaHjRcc2msv8LddhBkStP8FrB39RPu9M+ikBkTwdQTSGcIBDYJgt3la2KMwmU1F81cq17wb21lPriBwr626lBiir/WdrBsoAsANeZfyzpAm8K4ssI3eu9eklxpEKdAdNRJbpQ==").unwrap(); 964 | assert_eq!( 965 | Some("@cert-authority [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090".into()), 966 | key.options 967 | ); 968 | assert_eq!("@cert-authority [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAopjUBQqif5ILeoMHjJ9wGlGs2eNHEv3+OAiiEDHCapNm3guNa+T/ZMtedaC/0P8bLBCXMiyNQU04N/IRyN3Mp/SGhtGJl1PDENXzPB9aoxsB2HHc8s8P7mxal1G4BtCT/fJM5XywEHWAcHkzW91iTK+ApAdqt6AHj35ogil9maFlUNKcXz2aW27hdbDtC0fautvWd9RIITHPq00rdvaHjRcc2msv8LddhBkStP8FrB39RPu9M+ikBkTwdQTSGcIBDYJgt3la2KMwmU1F81cq17wb21lPriBwr626lBiir/WdrBsoAsANeZfyzpAm8K4ssI3eu9eklxpEKdAdNRJbpQ==", key.to_string().trim()); 969 | } 970 | 971 | #[test] 972 | fn read_keys() { 973 | let authorized_keys = "# authorized keys 974 | 975 | command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril 976 | agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril 977 | 978 | 979 | 980 | 981 | ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== 982 | "; 983 | let key1 = "command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril"; 984 | let key2 = "agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril"; 985 | let key3 = "ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== "; 986 | let keys = PublicKey::read_keys(authorized_keys.as_bytes()).unwrap(); 987 | assert_eq!(key1, keys[0].to_string()); 988 | assert_eq!(key2, keys[1].to_string()); 989 | assert_eq!(key3, keys[2].to_string()); 990 | } 991 | 992 | #[test] 993 | fn comment_should_be_none_when_absent() { 994 | let key = 995 | "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/"; 996 | let key = PublicKey::parse(key).unwrap(); 997 | assert!(key.comment.is_none()); 998 | } 999 | 1000 | #[test] 1001 | fn comment_should_be_none_when_empty_string() { 1002 | let key = 1003 | "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ "; 1004 | let key = PublicKey::parse(key).unwrap(); 1005 | assert!(key.comment.is_none()); 1006 | } 1007 | 1008 | #[test] 1009 | fn comment_should_preserve_special_characters() { 1010 | let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ !@#$%^&*()_+-={}|[]\\:\";'<>?,./"; 1011 | let key = PublicKey::parse(key).unwrap(); 1012 | assert_eq!(key.comment.unwrap(), "!@#$%^&*()_+-={}|[]\\:\";'<>?,./"); 1013 | } 1014 | 1015 | #[test] 1016 | fn comment_should_preserve_multiple_spaces() { 1017 | let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ comment with multiple spaces"; 1018 | let key = PublicKey::parse(key).unwrap(); 1019 | assert_eq!(key.comment.unwrap(), "comment with multiple spaces"); 1020 | } 1021 | 1022 | #[test] 1023 | fn comment_should_remove_leading_and_trailing_spaces_while_keeping_body_intact() { 1024 | let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ leading and trailing spaces are trimmed "; 1025 | let key = PublicKey::parse(key).unwrap(); 1026 | assert_eq!( 1027 | key.comment.unwrap(), 1028 | "leading and trailing spaces are trimmed" 1029 | ); 1030 | } 1031 | 1032 | #[test] 1033 | fn comment_should_not_preserve_newlines() { 1034 | let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ comment with\nnewlines"; 1035 | let key = PublicKey::parse(key); 1036 | assert!(key.is_err()); 1037 | } 1038 | 1039 | #[test] 1040 | fn comment_should_preserve_mixed_whitespace() { 1041 | let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ mixed white\t space"; 1042 | let key = PublicKey::parse(key).unwrap(); 1043 | assert_eq!(key.comment.unwrap(), "mixed white\t space"); 1044 | } 1045 | 1046 | #[test] 1047 | fn comment_should_preserve_unicode_characters() { 1048 | let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ comment with unicode: 中文, русский, عربى"; 1049 | let key = PublicKey::parse(key).unwrap(); 1050 | assert_eq!( 1051 | key.comment.unwrap(), 1052 | "comment with unicode: 中文, русский, عربى" 1053 | ); 1054 | } 1055 | } 1056 | -------------------------------------------------------------------------------- /src/reader.rs: -------------------------------------------------------------------------------- 1 | //! This module provides a struct for reading bytes in the OpenSSH public key format. 2 | 3 | use crate::errors::*; 4 | 5 | use byteorder::{BigEndian, ByteOrder}; 6 | 7 | pub struct Reader<'a> { 8 | data: &'a [u8], 9 | offset: usize, 10 | } 11 | 12 | impl<'a> Reader<'a> { 13 | pub fn new(data: &[u8]) -> Reader { 14 | Reader { data, offset: 0 } 15 | } 16 | 17 | pub fn peek_int(&mut self) -> Result { 18 | let cur = &self.data[self.offset..]; 19 | if cur.len() < 4 { 20 | return Err(OpenSSHKeyError::InvalidFormat); 21 | } 22 | Ok(BigEndian::read_u32(&cur[..4])) 23 | } 24 | 25 | pub fn read_string(&mut self) -> Result<&'a str> { 26 | Ok(std::str::from_utf8(self.read_bytes()?)?) 27 | } 28 | 29 | pub fn read_mpint(&mut self) -> Result<&'a [u8]> { 30 | // mpints might have an extra byte of zeros at the start. 31 | // if there is, we can just ignore it, since the number is big-endian 32 | let bytes = self.read_bytes()?; 33 | if bytes.first() == Some(&0) { 34 | Ok(&bytes[1..]) 35 | } else { 36 | Ok(bytes) 37 | } 38 | } 39 | 40 | pub fn read_bytes(&mut self) -> Result<&'a [u8]> { 41 | let cur = &self.data[self.offset..]; 42 | let len = self.peek_int()? as usize; 43 | if cur.len() < len + 4 { 44 | return Err(OpenSSHKeyError::InvalidFormat); 45 | } 46 | self.offset += len + 4; 47 | Ok(&cur[4..len + 4]) 48 | } 49 | } 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | 55 | #[test] 56 | fn reader_empty() { 57 | let data = vec![]; 58 | let mut rd = Reader::new(data.as_ref()); 59 | assert!(rd.peek_int().is_err()); 60 | assert!(rd.read_bytes().is_err()); 61 | assert!(rd.read_mpint().is_err()); 62 | assert!(rd.read_string().is_err()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/writer.rs: -------------------------------------------------------------------------------- 1 | //! This module provides a struct for writing bytes in the OpenSSH public key format. 2 | 3 | use byteorder::{BigEndian, WriteBytesExt}; 4 | 5 | pub struct Writer { 6 | data: Vec, 7 | } 8 | 9 | impl Writer { 10 | pub fn new() -> Writer { 11 | Writer { data: vec![] } 12 | } 13 | 14 | pub fn into_vec(self) -> Vec { 15 | self.data 16 | } 17 | 18 | pub fn write_int(&mut self, val: u32) { 19 | if self.data.write_u32::(val).is_err() { 20 | unreachable!() 21 | }; 22 | } 23 | 24 | pub fn write_bytes(&mut self, mut buf: Vec) { 25 | if buf.is_empty() { 26 | return; 27 | } 28 | // The first four bytes represent the length of the encoded data. 29 | self.write_int(buf.len() as u32); 30 | // the rest of the bytes are the data itself 31 | self.data.append(&mut buf); 32 | } 33 | 34 | // according to RFC 4251, the mpint datatype representation is a big-endian 35 | // arbitrary-precision integer encoded in two's complement and stored as a 36 | // string with the minimum possible number of characters. 37 | // see mpint definition in https://tools.ietf.org/html/rfc4251#section-5 38 | pub fn write_mpint(&mut self, mut num: Vec) { 39 | // If the number is positive then we are required to guarentee that the 40 | // most significant bit is set to zero if the first bit in the first 41 | // byte is going to be one. 42 | if num.first().unwrap_or(&0) & 0x80 != 0 { 43 | num.insert(0, 0); 44 | } 45 | // other than that it's just normal ssh encoding 46 | self.write_bytes(num) 47 | } 48 | 49 | pub fn write_string(&mut self, val: &str) { 50 | self.write_bytes(val.as_bytes().to_vec()) 51 | } 52 | } 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn writer_empty() { 60 | let w = Writer::new(); 61 | assert_eq!(w.into_vec().len(), 0); 62 | let mut w = Writer::new(); 63 | w.write_bytes(vec![]); 64 | assert_eq!(w.into_vec().len(), 0); 65 | let mut w = Writer::new(); 66 | w.write_mpint(vec![]); 67 | assert_eq!(w.into_vec().len(), 0); 68 | } 69 | } 70 | --------------------------------------------------------------------------------