openssh-keys-0.6.2/.cargo_vcs_info.json0000644000000001360000000000100134710ustar { "git": { "sha1": "d07d493a6941ceb9c02da4af4322a1722d5b8b23" }, "path_in_vcs": "" }openssh-keys-0.6.2/Cargo.lock0000644000000151010000000000100114420ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "base64" version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" [[package]] name = "block-buffer" version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" dependencies = [ "generic-array", ] [[package]] name = "byteorder" version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cpufeatures" version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03e69e28e9f7f77debdedbaafa2866e1de9ba56df55a8bd7cfc724c25a09987c" dependencies = [ "libc", ] [[package]] name = "crypto-common" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", "typenum", ] [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", ] [[package]] name = "generic-array" version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", ] [[package]] name = "home" version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" dependencies = [ "windows-sys", ] [[package]] name = "libc" version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" [[package]] name = "md-5" version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca" dependencies = [ "digest", ] [[package]] name = "openssh-keys" version = "0.6.2" dependencies = [ "base64", "byteorder", "home", "md-5", "sha2", "thiserror", ] [[package]] name = "proc-macro2" version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" dependencies = [ "proc-macro2", ] [[package]] name = "sha2" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" dependencies = [ "cfg-if", "cpufeatures", "digest", ] [[package]] name = "syn" version = "2.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2efbeae7acf4eabd6bcdcbd11c92f45231ddda7539edc7806bd1a04a03b24616" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "typenum" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" [[package]] name = "unicode-ident" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" [[package]] name = "windows_x86_64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" openssh-keys-0.6.2/Cargo.toml0000644000000026730000000000100114770ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.58.0" name = "openssh-keys" version = "0.6.2" authors = ["Stephen Demos "] exclude = [ ".github", ".gitignore", "examples", "fixtures", ] description = "read and write OpenSSH public keys" homepage = "https://github.com/coreos/openssh-keys" documentation = "https://docs.rs/openssh-keys" readme = "README.md" keywords = [ "ssh", "ssh-keys", "keys", "rsa", "openssh", ] license = "MIT OR Apache-2.0" repository = "https://github.com/coreos/openssh-keys" [package.metadata.release] pre-release-commit-message = "cargo: openssh-keys release {{version}}" publish = false push = false sign-commit = true sign-tag = true tag-message = "openssh-keys {{version}}" [dependencies.base64] version = "0.21" [dependencies.byteorder] version = "1.1" [dependencies.md-5] version = "0.10" [dependencies.sha2] version = "0.10" [dependencies.thiserror] version = "1.0" [dev-dependencies.home] version = "~0.5" openssh-keys-0.6.2/Cargo.toml.orig000064400000000000000000000022121046102023000151450ustar 00000000000000[package] name = "openssh-keys" version = "0.6.2" edition = "2021" rust-version = "1.58.0" authors = ["Stephen Demos "] description = "read and write OpenSSH public keys" documentation = "https://docs.rs/openssh-keys" homepage = "https://github.com/coreos/openssh-keys" repository = "https://github.com/coreos/openssh-keys" readme = "README.md" keywords = ["ssh", "ssh-keys", "keys", "rsa", "openssh"] license = "MIT OR Apache-2.0" exclude = [".github", ".gitignore", "examples", "fixtures"] [dependencies] # Private dependencies. base64 = "0.21" byteorder = "1.1" # Do not use a range on the crates md-5 or sha2. RustCrypto crate # versions cannot be mixed and matched. Doing so will cause hard # to understand build failures. Read about it at # https://github.com/coreos/openssh-keys/issues/89 md-5 = "0.10" sha2 = "0.10" thiserror = "1.0" # Public dependencies, exposed through library API. # [dev-dependencies] home = "~0.5" [package.metadata.release] publish = false push = false pre-release-commit-message = "cargo: openssh-keys release {{version}}" sign-commit = true sign-tag = true tag-message = "openssh-keys {{version}}" openssh-keys-0.6.2/LICENSE-APACHE000064400000000000000000000251371046102023000142150ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. openssh-keys-0.6.2/LICENSE-MIT000064400000000000000000000020401046102023000137110ustar 00000000000000Copyright (c) 2017 Stephen Demos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.openssh-keys-0.6.2/README.md000064400000000000000000000042741046102023000135470ustar 00000000000000# openssh-keys   [![Latest Version]][crates.io] [![Docs Badge]][docs] [Latest Version]: https://img.shields.io/crates/v/openssh-keys.svg [crates.io]: https://crates.io/crates/openssh-keys [Docs Badge]: https://docs.rs/openssh-keys/badge.svg [docs]: https://docs.rs/openssh-keys A pure-Rust library to handle OpenSSH public keys. `openssh-keys` can parse, print, and fingerprint OpenSSH public keys. It supports the following algorithms: * RSA * DSA * ECDSA (nistp256, nistp384, nistp521) * ED25519 It can construct RSA and DSA keys from their components using the `PublicKey::from_rsa()` and `PublicKey::from_dsa()` functions respectively. ## Example ```rust extern crate openssh_keys; use std::{env, fs, io, path}; use std::io::BufRead; fn main() { let home = env::home_dir().unwrap_or(path::PathBuf::from("/home/core/")); let pub_path = home.join(".ssh").join("id_rsa.pub"); println!("Inspecting '{}':", pub_path.to_string_lossy()); let file = fs::File::open(&pub_path).expect("unable to open RSA pubkey"); let reader = io::BufReader::new(file); for (i, line) in reader.lines().enumerate() { let line = line.expect(&format!("unable to read key at line {}", i + 1)); let pubkey = openssh_keys::PublicKey::parse(&line).expect("unable to parse RSA pubkey"); println!(" * Pubkey #{} -> {}", i + 1, pubkey.to_fingerprint_string()); } } ``` Some more examples are available under [examples](examples). ## Release process Releases can be performed by [creating a new release ticket][new-release-ticket] and following the steps in the checklist there. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [new-release-ticket]: https://github.com/coreos/openssh-keys/issues/new?labels=release&template=release-checklist.md openssh-keys-0.6.2/code_of_conduct.md000064400000000000000000000062361046102023000157270ustar 00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [INSERT EMAIL ADDRESS]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ openssh-keys-0.6.2/docs/development.md000064400000000000000000000004131046102023000160530ustar 00000000000000# Development ## Release process Releases can be performed by [creating a new release ticket][new-release-ticket] and following the steps in the checklist there. [new-release-ticket]: https://github.com/coreos/openssh-keys/issues/new?template=release-checklist.md openssh-keys-0.6.2/docs/release-notes.md000064400000000000000000000061351046102023000163060ustar 00000000000000# Release notes ## Upcoming openssh-keys 0.6.3 (unreleased) Changes: ## openssh-keys 0.6.2 (2023-06-27) Changes: - Require `md-5` 0.10, `sha2` 0.10 to avoid mismatched Rust Crypto dependencies ## openssh-keys 0.6.1 (2023-06-01) Changes: - Require Rust ≥ 1.58.0 - Require `base64` ≥ 0.21 - Switch example code from `dirs` dependency to `home` - Add release notes doc ## openssh-keys 0.6.0 (2022-11-18) Changes: - cargo: allow md-5 and sha2 0.10 - cargo: explicitly set `sign-tag` - dependabot: switch to weekly cadence - git: rename `master` branch to `main` - github/ISSUE_TEMPLATE: add release checklist - lib: Support Hardware Security Keys - templates: release process updates - workflows: bump MSRV and lint toolchain ## openssh-keys 0.5.0 (2021-03-16) - API change: Switch error-handling library from `error-chain` to `thiserror` - Update to Rust 2018 - Fix build warnings with newer Rust - Update `base64` to 0.13 - Exclude tooling configuration from packaged crate ## openssh-keys 0.4.2 (2020-06-22) Changes: - cargo: update all dependencies - cargo: update manifest and rustfmt whole project - dependabot: create config file - travis: update minimum and clippy toolchains ## openssh-keys 0.4.1 (2018-11-01) Changes: - Update base64 requirement from 0.9 to 0.10 ## openssh-keys 0.4.0 (2018-10-24) Changes: - lib: clean all clippy warnings - cargo: update all dependencies to latest - travis: add minimum toolchain and clippy passes - remove appveyor ci - move repo under the coreos org on github ## openssh-keys 0.3.0 (2018-07-11) Changes: - update `error-chain` from `0.11.x` to `0.12.x` - update `base64` from `0.8.x` to `0.9.x` ## openssh-keys 0.2.2 (2017-12-14) Changes: - Make `PublicKey` fields public (#14, thanks @Trolldemorted!) - bump `base64` from `0.6.x` to `0.8.x` - bump `sha2` from `0.6.x` to `0.7.x` ## openssh-keys 0.2.1 (2017-12-05) Changes: - add md5 fingerprinting with `fingerprint_md5` and `to_fingerprint_md5_string` - move fingerprint algorithm label to `to_fingerprint_string` and `to_fingerprint_md5_string`, now `fingerprint` only prints the fingerprint without the hashing algorithm label ## openssh-keys 0.2.0 (2017-11-07) Changes: - 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. ## openssh-keys 0.1.2 (2017-11-07) Changes: - cleaned up release crate - added several trait derivations for exported datatypes - renamed `to_key_file` to `to_key_format` - 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. ## openssh-keys 0.1.1 (2017-09-20) Changes: - bumps `error-chain` to `v0.11.0` - uses `sha2` library instead of `rust-crypto` for `sha256` fingerprint hashes - adds docs and examples ## openssh-keys 0.1.0 (2017-09-01) `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). openssh-keys-0.6.2/src/lib.rs000064400000000000000000001212231046102023000141650ustar 00000000000000//! A pure-Rust library to handle OpenSSH public keys. //! //! This crate supports parsing, manipulation, and some basic validation of //! SSH keys. It provides a struct for encapsulation of SSH keys in projects. //! //! `openssh-keys` does not have the ability to generate SSH keys. However, //! it does allow to construct RSA and DSA keys from their components, so if you //! generate the keys with another library (say, rust-openssl), then you can //! output the SSH public keys with this library. //! //! # Example //! //! ```rust //! use std::{env, fs, io, path}; //! use std::io::BufRead; //! //! fn inspect_rsa() { //! let home = env::home_dir().unwrap_or(path::PathBuf::from("/home/core/")); //! let pub_path = home.join(".ssh").join("id_rsa.pub"); //! println!("Inspecting '{}':", pub_path.to_string_lossy()); //! let file = fs::File::open(&pub_path).expect("unable to open RSA pubkey"); //! let reader = io::BufReader::new(file); //! //! for (i, line) in reader.lines().enumerate() { //! let line = line.expect(&format!("unable to read key at line {}", i + 1)); //! let pubkey = openssh_keys::PublicKey::parse(&line).expect("unable to parse RSA pubkey"); //! println!(" * Pubkey #{} -> {}", i + 1, pubkey.to_fingerprint_string()); //! } //! } mod reader; mod writer; pub mod errors { use thiserror::Error; pub type Result = std::result::Result; #[derive(Error, Debug)] pub enum OpenSSHKeyError { #[error("I/O error")] IO { #[from] source: std::io::Error, }, #[error("invalid UTF-8")] InvalidUtf8 { #[from] source: std::str::Utf8Error, }, // keep base64::DecodeError out of the public API #[error("invalid base64: {detail}")] InvalidBase64 { detail: String }, #[error("invalid key format")] InvalidFormat, #[error("unsupported keytype: {keytype}")] UnsupportedKeyType { keytype: String }, #[error("unsupported curve: {curve}")] UnsupportedCurve { curve: String }, } } use crate::errors::*; use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; use md5::Md5; use sha2::{Digest, Sha256}; use crate::reader::Reader; use crate::writer::Writer; use std::fmt; use std::io::{BufRead, BufReader, Read}; const SSH_RSA: &str = "ssh-rsa"; const SSH_DSA: &str = "ssh-dss"; const SSH_ED25519: &str = "ssh-ed25519"; const SSH_ED25519_SK: &str = "sk-ssh-ed25519@openssh.com"; const SSH_ECDSA_256: &str = "ecdsa-sha2-nistp256"; const SSH_ECDSA_384: &str = "ecdsa-sha2-nistp384"; const SSH_ECDSA_521: &str = "ecdsa-sha2-nistp521"; const SSH_ECDSA_SK: &str = "sk-ecdsa-sha2-nistp256@openssh.com"; const NISTP_256: &str = "nistp256"; const NISTP_384: &str = "nistp384"; const NISTP_521: &str = "nistp521"; /// Curves for ECDSA #[derive(Clone, Debug, Copy, PartialEq, Eq, Hash)] pub enum Curve { Nistp256, Nistp384, Nistp521, } impl Curve { /// get converts a curve name of the type in the format described in /// https://tools.ietf.org/html/rfc5656#section-10 and returns a curve /// object. fn get(curve: &str) -> Result { Ok(match curve { NISTP_256 => Curve::Nistp256, NISTP_384 => Curve::Nistp384, NISTP_521 => Curve::Nistp521, _ => { return Err(OpenSSHKeyError::UnsupportedCurve { curve: curve.to_string(), }) } }) } /// curvetype gets the curve name in the format described in /// https://tools.ietf.org/html/rfc5656#section-10 fn curvetype(self) -> &'static str { match self { Curve::Nistp256 => NISTP_256, Curve::Nistp384 => NISTP_384, Curve::Nistp521 => NISTP_521, } } } impl fmt::Display for Curve { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.curvetype()) } } /// Data is the representation of the data section of an ssh public key. it is /// an enum with all the different supported key algorithms. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Data { Rsa { exponent: Vec, modulus: Vec, }, Dsa { p: Vec, q: Vec, g: Vec, pub_key: Vec, }, Ed25519 { key: Vec, }, Ed25519Sk { key: Vec, application: Vec, }, Ecdsa { curve: Curve, key: Vec, }, EcdsaSk { curve: Curve, key: Vec, application: Vec, }, } /// `PublicKey` is the struct representation of an ssh public key. #[derive(Clone, Debug, Eq)] pub struct PublicKey { pub options: Option, pub data: Data, pub comment: Option, } impl fmt::Display for PublicKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_key_format()) } } /// Two public keys are equivalent if their data sections are equivalent, /// ignoring their comment section. impl core::cmp::PartialEq for PublicKey { fn eq(&self, other: &PublicKey) -> bool { self.data == other.data } } impl std::str::FromStr for PublicKey { type Err = OpenSSHKeyError; fn from_str(s: &str) -> Result { PublicKey::parse(s) } } impl PublicKey { /// parse takes a string and parses it as a public key from an authorized /// keys file. the format it expects is described here /// https://tools.ietf.org/html/rfc4253#section-6.6 and here /// https://man.openbsd.org/sshd#AUTHORIZED_KEYS_FILE_FORMAT /// /// sshd describes an additional, optional "options" field for public keys /// in the authorized_keys file. This field allows for passing of options to /// sshd that only apply to that particular public key. This means that a /// public key in an authorized keys file is a strict superset of the public /// key format described in rfc4253. Another superset of a public key is /// what is present in the known_hosts file. This file has a hostname as the /// first thing on the line. This parser treats the hostname the same as an /// option field. When one of these things is found at the beginning of a /// line, it is treated as a semi-opaque string that is carried with the /// public key and reproduced when the key is printed. It is not entirely /// opaque, since the parser needs to be aware of quoting semantics within /// the option fields, since options surrounded by double quotes can contain /// spaces, which are otherwise the main delimiter of the parts of a public /// key. /// /// You can parse and output ssh keys like this /// /// ``` /// let rsa_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCcMCOEryBa8IkxXacjIawaQPp08hR5h7+4vZePZ7DByTG3tqKgZYRJ86BaR+4fmdikFoQjvLJVUmwniq3wixhkP7VLCbqip3YHzxXrzxkbPC3w3O1Bdmifwn9cb8RcZXfXncCsSu+h5XCtQ5BOi41Iit3d13gIe/rfXVDURmRanV6R7Voljxdjmp/zyReuzc2/w5SI6Boi4tmcUlxAI7sFuP1kA3pABDhPtc3TDgAcPUIBoDCoY8q2egI197UuvbgsW2qraUcuQxbMvJOMSFg2FQrE2bpEqC4CtBn7+HiJrkVOHjV7bvSv7jd1SuX5XqkwMCRtdMuRpJr7CyZoFL5n demos@anduin"; /// let key = openssh_keys::PublicKey::parse(rsa_key).unwrap(); /// let out = key.to_string(); /// assert_eq!(rsa_key, out); /// ``` /// /// parse somewhat attempts to keep track of comments, but it doesn't fully /// comply with the rfc in that regard. pub fn parse(key: &str) -> Result { // trim leading and trailing whitespace let key = key.trim(); // try just parsing the keys straight up PublicKey::try_key_parse(key).or_else(|e| { // remove the preceeding string let mut key_start = 0; let mut escape = false; let mut quote = false; let mut marker = key.starts_with('@'); for (i, c) in key.chars().enumerate() { if c == '\\' { escape = true; continue; } if escape { escape = false; continue; } if c == '"' { quote = !quote; } if !quote && (c == ' ' || c == '\t') { if marker { marker = false; continue; } else { key_start = i + 1; break; } } } let mut parsed = PublicKey::try_key_parse(&key[key_start..]).map_err(|_| e)?; parsed.options = Some(key[..key_start - 1].into()); Ok(parsed) }) } fn try_key_parse(key: &str) -> Result { // then parse the key according to rfc4253 let mut parts = key.split_whitespace(); let keytype = parts.next().ok_or(OpenSSHKeyError::InvalidFormat)?; let data = parts.next().ok_or(OpenSSHKeyError::InvalidFormat)?; // comment is not required. if we get an empty comment (because of a // trailing space) throw it out. let comment = parts.next().and_then(|c| { if c.is_empty() { None } else { Some(c.to_string()) } }); let buf = BASE64 .decode(data) .map_err(|e| OpenSSHKeyError::InvalidBase64 { detail: format!("{}", e), })?; let mut reader = Reader::new(&buf); let data_keytype = reader.read_string()?; if keytype != data_keytype { return Err(OpenSSHKeyError::InvalidFormat); } let data = match keytype { SSH_RSA => { // the data for an rsa key consists of three pieces: // ssh-rsa public-exponent modulus // see ssh-rsa format in https://tools.ietf.org/html/rfc4253#section-6.6 let e = reader.read_mpint()?; let n = reader.read_mpint()?; Data::Rsa { exponent: e.into(), modulus: n.into(), } } SSH_DSA => { // the data stored for a dsa key is, in order // ssh-dsa p q g public-key // p and q are primes // g = h^((p-1)/q) where 1 < h < p-1 // public-key is the value that is actually generated in // relation to the secret key // see https://en.wikipedia.org/wiki/Digital_Signature_Algorithm // and ssh-dss format in https://tools.ietf.org/html/rfc4253#section-6.6 // and https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L743 let p = reader.read_mpint()?; let q = reader.read_mpint()?; let g = reader.read_mpint()?; let pub_key = reader.read_mpint()?; Data::Dsa { p: p.into(), q: q.into(), g: g.into(), pub_key: pub_key.into(), } } SSH_ED25519 => { // the data stored for an ed25519 is just the point on the curve // for now the exact specification of the point on that curve is // a mystery to me, instead of having to compute it, we just // assume the key we got is correct and copy that verbatim. this // also means we have to disallow arbitrary construction until // furthur notice. // see https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L772 let key = reader.read_bytes()?; Data::Ed25519 { key: key.into() } } SSH_ED25519_SK => { // same as above let key = reader.read_bytes()?; let application = reader.read_bytes()?; Data::Ed25519Sk { key: key.into(), application: application.into(), } } SSH_ECDSA_256 | SSH_ECDSA_384 | SSH_ECDSA_521 => { // ecdsa is of the form // ecdsa-sha2-[identifier] [identifier] [data] // the identifier is one of nistp256, nistp384, nistp521 // the data is some weird thing described in section 2.3.4 and // 2.3.4 of https://www.secg.org/sec1-v2.pdf so for now we // aren't going to bother actually computing it and instead we // will just not let you construct them. // // see the data definition at // https://tools.ietf.org/html/rfc5656#section-3.1 // and the openssh output // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L753 // and the openssh buffer writer implementation // https://github.com/openssh/openssh-portable/blob/master/sshbuf-getput-crypto.c#L192 // and the openssl point2oct implementation // https://github.com/openssl/openssl/blob/aa8f3d76fcf1502586435631be16faa1bef3cdf7/crypto/ec/ec_oct.c#L82 let curve = reader.read_string()?; let key = reader.read_bytes()?; Data::Ecdsa { curve: Curve::get(curve)?, key: key.into(), } } SSH_ECDSA_SK => { // same as above (like there, we don't assert that the curve matches what was specified in the keytype) let curve = reader.read_string()?; let key = reader.read_bytes()?; let application = reader.read_bytes()?; Data::EcdsaSk { curve: Curve::get(curve)?, key: key.into(), application: application.into(), } } _ => { return Err(OpenSSHKeyError::UnsupportedKeyType { keytype: keytype.to_string(), }) } }; Ok(PublicKey { options: None, data, comment, }) } /// read_keys takes a reader and parses it as an authorized_keys file. it /// returns an error if it can't read or parse any of the public keys in the /// list. pub fn read_keys(r: R) -> Result> where R: Read, { let keybuf = BufReader::new(r); // authorized_keys files are newline-separated lists of public keys let mut keys = vec![]; for key in keybuf.lines() { let key = key?; // skip any empty lines and any comment lines (prefixed with '#') if !key.is_empty() && !(key.trim().starts_with('#')) { keys.push(PublicKey::parse(&key)?); } } Ok(keys) } /// get an ssh public key from rsa components pub fn from_rsa(e: Vec, n: Vec) -> Self { PublicKey { options: None, data: Data::Rsa { exponent: e, modulus: n, }, comment: None, } } /// get an ssh public key from dsa components pub fn from_dsa(p: Vec, q: Vec, g: Vec, pkey: Vec) -> Self { PublicKey { options: None, data: Data::Dsa { p, q, g, pub_key: pkey, }, comment: None, } } /// keytype returns the type of key in the format described by rfc4253 /// The output will be ssh-{type} where type is [rsa,ed25519,ecdsa,dsa] pub fn keytype(&self) -> &'static str { match self.data { Data::Rsa { .. } => SSH_RSA, Data::Dsa { .. } => SSH_DSA, Data::Ed25519 { .. } => SSH_ED25519, Data::Ed25519Sk { .. } => SSH_ED25519_SK, Data::Ecdsa { ref curve, .. } => match *curve { Curve::Nistp256 => SSH_ECDSA_256, Curve::Nistp384 => SSH_ECDSA_384, Curve::Nistp521 => SSH_ECDSA_521, }, Data::EcdsaSk { .. } => SSH_ECDSA_SK, } } /// data returns the data section of the key in the format described by rfc4253 /// the contents of the data section depend on the keytype. For RSA keys it /// contains the keytype, exponent, and modulus in that order. Other types /// have other data sections. This function doesn't base64 encode the data, /// that task is left to the consumer of the output. pub fn data(&self) -> Vec { let mut writer = Writer::new(); writer.write_string(self.keytype()); match self.data { Data::Rsa { ref exponent, ref modulus, } => { // the data for an rsa key consists of three pieces: // ssh-rsa public-exponent modulus // see ssh-rsa format in https://tools.ietf.org/html/rfc4253#section-6.6 writer.write_mpint(exponent.clone()); writer.write_mpint(modulus.clone()); } Data::Dsa { ref p, ref q, ref g, ref pub_key, } => { writer.write_mpint(p.clone()); writer.write_mpint(q.clone()); writer.write_mpint(g.clone()); writer.write_mpint(pub_key.clone()); } Data::Ed25519 { ref key } => { writer.write_bytes(key.clone()); } Data::Ed25519Sk { ref key, ref application, } => { writer.write_bytes(key.clone()); writer.write_bytes(application.clone()); } Data::Ecdsa { ref curve, ref key } => { writer.write_string(curve.curvetype()); writer.write_bytes(key.clone()); } Data::EcdsaSk { ref curve, ref key, ref application, } => { writer.write_string(curve.curvetype()); writer.write_bytes(key.clone()); writer.write_bytes(application.clone()); } } writer.into_vec() } pub fn set_comment(&mut self, comment: &str) { self.comment = Some(comment.to_string()); } /// to_key_format returns a string representation of the ssh key. this string /// output is appropriate to use as a public key file. it adheres to the /// format described in https://tools.ietf.org/html/rfc4253#section-6.6 /// /// an ssh key consists of four pieces: /// /// [options] ssh-keytype data comment /// /// the output of the data section is described in the documentation for the /// data function. the options section is optional, and is not part of the /// spec. rather, it is a field present in authorized_keys files or /// known_hosts files. pub fn to_key_format(&self) -> String { let key = format!( "{} {} {}", self.keytype(), BASE64.encode(self.data()), self.comment.clone().unwrap_or_default() ); if let Some(ref options) = self.options { format!("{} {}", options, key) } else { key } } /// size returns the size of the stored ssh key. for rsa keys this is /// determined by the number of bits in the modulus. for dsa keys it's the /// number of bits in the prime p. /// /// see https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L261 /// for more details pub fn size(&self) -> usize { match self.data { Data::Rsa { ref modulus, .. } => modulus.len() * 8, Data::Dsa { ref p, .. } => p.len() * 8, Data::Ed25519 { .. } | Data::Ed25519Sk { .. } => 256, // ?? Data::Ecdsa { ref curve, .. } | Data::EcdsaSk { ref curve, .. } => match *curve { Curve::Nistp256 => 256, Curve::Nistp384 => 384, Curve::Nistp521 => 521, }, } } /// fingerprint returns a string representing the fingerprint of the ssh key /// the format of the fingerprint is described tersely in /// https://tools.ietf.org/html/rfc4716#page-6. This uses the ssh-keygen /// defaults of a base64 encoded SHA256 hash. pub fn fingerprint(&self) -> String { let data = self.data(); let mut hasher = Sha256::new(); hasher.update(&data); let hashed = hasher.finalize(); let mut fingerprint = BASE64.encode(hashed); // trim padding characters off the end. I'm not clear on exactly what // this is doing but they do it here and the test fails without it // https://github.com/openssh/openssh-portable/blob/643c2ad82910691b2240551ea8b14472f60b5078/sshkey.c#L918 if let Some(l) = fingerprint.find('=') { fingerprint.truncate(l); }; fingerprint } /// to_fingerprint_string prints out the fingerprint in the same format used /// by `ssh-keygen -l -f key`, specifically the implementation here - /// https://github.com/openssh/openssh-portable/blob/master/ssh-keygen.c#L842 /// right now it just sticks with the defaults of a base64 encoded SHA256 /// hash. pub fn to_fingerprint_string(&self) -> String { let keytype = match self.data { Data::Rsa { .. } => "RSA", Data::Dsa { .. } => "DSA", Data::Ed25519 { .. } => "ED25519", Data::Ed25519Sk { .. } => "ED25519_SK", Data::Ecdsa { .. } => "ECDSA", Data::EcdsaSk { .. } => "ECDSA_SK", }; let comment = self .comment .clone() .unwrap_or_else(|| "no comment".to_string()); format!( "{} SHA256:{} {} ({})", self.size(), self.fingerprint(), comment, keytype ) } /// fingerprint_m5 returns a string representing the fingerprint of the ssh key /// the format of the fingerprint is MD5, and the output looks like, /// `fb:a0:5b:a0:21:01:47:33:3b:8d:9e:14:1a:4c:db:6d` . pub fn fingerprint_md5(&self) -> String { let mut sh = Md5::default(); sh.update(&self.data()); let md5: Vec = sh.finalize().iter().map(|n| format!("{:02x}", n)).collect(); md5.join(":") } /// to_fingerprint_m5_string prints out the fingerprint in the in hex format used /// by `ssh-keygen -l -E md5 -f key`, and the output looks like, /// `2048 MD5:fb:a0:5b:a0:21:01:47:33:3b:8d:9e:14:1a:4c:db:6d demos@anduin (RSA)` . pub fn to_fingerprint_md5_string(&self) -> String { let keytype = match self.data { Data::Rsa { .. } => "RSA", Data::Dsa { .. } => "DSA", Data::Ed25519 { .. } => "ED25519", Data::Ed25519Sk { .. } => "ED25519_SK", Data::Ecdsa { .. } => "ECDSA", Data::EcdsaSk { .. } => "ECDSA_SK", }; let comment = self .comment .clone() .unwrap_or_else(|| "no comment".to_string()); format!( "{} MD5:{} {} ({})", self.size(), self.fingerprint_md5(), comment, keytype ) } } #[cfg(test)] mod tests { use super::*; 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"; 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"; const TEST_DSA_KEY: &str = "ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== demos@siril"; const TEST_ED25519_KEY: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril"; const TEST_ED25519_SK_KEY: &str = "sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIEX/dQ0v4127bEo8eeG1EV0ApO2lWbSnN6RWusn/NjqIAAAABHNzaDo= demos@siril"; const TEST_ECDSA256_KEY: &str = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIhfLQrww4DlhYzbSWXoX3ctOQ0jVosvfHfW+QWVotksbPzM2YgkIikTpoHUfZrYpJKWx7WYs5aqeLkdCDdk+jk= demos@siril"; const TEST_ECDSA_SK_KEY: &str = "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBDZ+f5tSRhlB7EN39f93SscTN5PUvbD3UQsNrlE1ZdbwPMMRul2zlPiUvwAvnJitW0jlD/vwZOW2YN+q+iZ5c0MAAAAEc3NoOg== demos@siril"; #[test] fn rsa_parse_to_string() { let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); let out = key.to_string(); assert_eq!(TEST_RSA_KEY, out); } #[test] fn rsa_size() { let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); assert_eq!(2048, key.size()); } #[test] fn rsa_keytype() { let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); assert_eq!("ssh-rsa", key.keytype()); } #[test] fn rsa_fingerprint() { let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); assert_eq!( "YTw/JyJmeAAle1/7zuZkPP0C73BQ+6XrFEt2/Wy++2o", key.fingerprint() ); } #[test] fn rsa_fingerprint_string() { let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); assert_eq!( "2048 SHA256:YTw/JyJmeAAle1/7zuZkPP0C73BQ+6XrFEt2/Wy++2o demos@siril (RSA)", key.to_fingerprint_string() ); } #[test] fn rsa_fingerprint_md5() { let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); assert_eq!( "e9:a1:5b:cd:a3:69:d2:d9:17:cb:09:3e:78:e1:0d:dd", key.fingerprint_md5() ); } #[test] fn rsa_fingerprint_md5_string() { let key = PublicKey::parse(TEST_RSA_KEY).unwrap(); assert_eq!( "2048 MD5:e9:a1:5b:cd:a3:69:d2:d9:17:cb:09:3e:78:e1:0d:dd demos@siril (RSA)", key.to_fingerprint_md5_string() ); } #[test] fn rsa_set_comment() { let mut key = PublicKey::parse(TEST_RSA_KEY).unwrap(); key.set_comment("test"); let out = key.to_string(); assert_eq!(TEST_RSA_COMMENT_KEY, out); } #[test] fn dsa_parse_to_string() { let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); let out = key.to_string(); assert_eq!(TEST_DSA_KEY, out); } #[test] fn dsa_size() { let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); assert_eq!(1024, key.size()); } #[test] fn dsa_keytype() { let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); assert_eq!("ssh-dss", key.keytype()); } #[test] fn dsa_fingerprint() { let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); assert_eq!( "/Pyxrjot1Hs5PN2Dpg/4pK2wxxtP9Igc3sDTAWIEXT4", key.fingerprint() ); } #[test] fn dsa_fingerprint_string() { let key = PublicKey::parse(TEST_DSA_KEY).unwrap(); assert_eq!( "1024 SHA256:/Pyxrjot1Hs5PN2Dpg/4pK2wxxtP9Igc3sDTAWIEXT4 demos@siril (DSA)", key.to_fingerprint_string() ); } #[test] fn ed25519_parse_to_string() { let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); let out = key.to_string(); assert_eq!(TEST_ED25519_KEY, out); } #[test] fn ed25519_size() { let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); assert_eq!(256, key.size()); } #[test] fn ed25519_keytype() { let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); assert_eq!("ssh-ed25519", key.keytype()); } #[test] fn ed25519_fingerprint() { let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); assert_eq!( "A/lHzXxsgbp11dcKKfSDyNQIdep7EQgZEoRYVDBfNdI", key.fingerprint() ); } #[test] fn ed25519_fingerprint_string() { let key = PublicKey::parse(TEST_ED25519_KEY).unwrap(); assert_eq!( "256 SHA256:A/lHzXxsgbp11dcKKfSDyNQIdep7EQgZEoRYVDBfNdI demos@siril (ED25519)", key.to_fingerprint_string() ); } #[test] fn ed25519_sk_parse_to_string() { let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); let out = key.to_string(); assert_eq!(TEST_ED25519_SK_KEY, out); } #[test] fn ed25519_sk_size() { let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); assert_eq!(256, key.size()); } #[test] fn ed25519_sk_keytype() { let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); assert_eq!("sk-ssh-ed25519@openssh.com", key.keytype()); } #[test] fn ed25519_sk_fingerprint() { let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); assert_eq!( "U8IKRkIHed6vFMTflwweA3HhIf2DWgZ8EFTm9fgwOUk", key.fingerprint() ); } #[test] fn ed25519_sk_fingerprint_string() { let key = PublicKey::parse(TEST_ED25519_SK_KEY).unwrap(); assert_eq!( "256 SHA256:U8IKRkIHed6vFMTflwweA3HhIf2DWgZ8EFTm9fgwOUk demos@siril (ED25519_SK)", key.to_fingerprint_string() ); } #[test] fn ecdsa256_parse_to_string() { let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); let out = key.to_string(); assert_eq!(TEST_ECDSA256_KEY, out); } #[test] fn ecdsa256_size() { let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); assert_eq!(256, key.size()); } #[test] fn ecdsa256_keytype() { let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); assert_eq!("ecdsa-sha2-nistp256", key.keytype()); } #[test] fn ecdsa256_fingerprint() { let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); assert_eq!( "BzS5YXMW/d2vFk8Oqh+nKmvKr8X/FTLBfJgDGLu5GAs", key.fingerprint() ); } #[test] fn ecdsa256_fingerprint_string() { let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap(); assert_eq!( "256 SHA256:BzS5YXMW/d2vFk8Oqh+nKmvKr8X/FTLBfJgDGLu5GAs demos@siril (ECDSA)", key.to_fingerprint_string() ); } #[test] fn ecdsa_sk_parse_to_string() { let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); let out = key.to_string(); assert_eq!(TEST_ECDSA_SK_KEY, out); } #[test] fn ecdsa_sk_size() { let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); assert_eq!(256, key.size()); } #[test] fn ecdsa_sk_keytype() { let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); assert_eq!("sk-ecdsa-sha2-nistp256@openssh.com", key.keytype()); } #[test] fn ecdsa_sk_fingerprint() { let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); assert_eq!( "N0sNKBgWKK8usPuPegtgzHQQA9vQ/dRhAEhwFDAnLA4", key.fingerprint() ); } #[test] fn ecdsa_sk_fingerprint_string() { let key = PublicKey::parse(TEST_ECDSA_SK_KEY).unwrap(); assert_eq!( "256 SHA256:N0sNKBgWKK8usPuPegtgzHQQA9vQ/dRhAEhwFDAnLA4 demos@siril (ECDSA_SK)", key.to_fingerprint_string() ); } #[test] fn option_parse() { let key = PublicKey::parse("agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); assert_eq!(Some("agent-forwarding".into()), key.options); assert_eq!("agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); let key = PublicKey::parse("from=\"*.sales.example.net,!pc.sales.example.net\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); assert_eq!( Some("from=\"*.sales.example.net,!pc.sales.example.net\"".into()), key.options ); assert_eq!("from=\"*.sales.example.net,!pc.sales.example.net\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); let key = PublicKey::parse("permitopen=\"192.0.2.1:80\",permitopen=\"192.0.2.2:25\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); assert_eq!( Some("permitopen=\"192.0.2.1:80\",permitopen=\"192.0.2.2:25\"".into()), key.options ); assert_eq!("permitopen=\"192.0.2.1:80\",permitopen=\"192.0.2.2:25\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); let key = PublicKey::parse("command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); assert_eq!( Some("command=\"echo \\\"holy shell escaping batman\\\"\"".into()), key.options ); assert_eq!("command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); let key = PublicKey::parse("command=\"dump /home\",no-pty,no-port-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril").unwrap(); assert_eq!( Some("command=\"dump /home\",no-pty,no-port-forwarding".into()), key.options ); assert_eq!("command=\"dump /home\",no-pty,no-port-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril", key.to_string()); } #[test] fn hostname_parse() { 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(); assert_eq!( Some("ec2-52-53-211-129.us-west-1.compute.amazonaws.com,52.53.211.129".into()), key.options ); 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()); 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(); assert_eq!( Some("[fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090".into()), key.options ); 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()); 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(); assert_eq!( Some("@revoked [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090".into()), key.options ); 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()); 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(); assert_eq!( Some("@cert-authority [fangorn.csh.rit.edu]:9090,[129.21.50.131]:9090".into()), key.options ); 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()); } #[test] fn read_keys() { let authorized_keys = "# authorized keys command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== "; let key1 = "command=\"echo \\\"holy shell escaping batman\\\"\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril"; let key2 = "agent-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril"; let key3 = "ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== "; let keys = PublicKey::read_keys(authorized_keys.as_bytes()).unwrap(); assert_eq!(key1, keys[0].to_string()); assert_eq!(key2, keys[1].to_string()); assert_eq!(key3, keys[2].to_string()); } } openssh-keys-0.6.2/src/reader.rs000064400000000000000000000032221046102023000146570ustar 00000000000000//! This module provides a struct for reading bytes in the OpenSSH public key format. use crate::errors::*; use byteorder::{BigEndian, ByteOrder}; pub struct Reader<'a> { data: &'a [u8], offset: usize, } impl<'a> Reader<'a> { pub fn new(data: &[u8]) -> Reader { Reader { data, offset: 0 } } pub fn peek_int(&mut self) -> Result { let cur = &self.data[self.offset..]; if cur.len() < 4 { return Err(OpenSSHKeyError::InvalidFormat); } Ok(BigEndian::read_u32(&cur[..4])) } pub fn read_string(&mut self) -> Result<&'a str> { Ok(std::str::from_utf8(self.read_bytes()?)?) } pub fn read_mpint(&mut self) -> Result<&'a [u8]> { // mpints might have an extra byte of zeros at the start. // if there is, we can just ignore it, since the number is big-endian let bytes = self.read_bytes()?; if bytes.first() == Some(&0) { Ok(&bytes[1..]) } else { Ok(bytes) } } pub fn read_bytes(&mut self) -> Result<&'a [u8]> { let cur = &self.data[self.offset..]; let len = self.peek_int()? as usize; if cur.len() < len + 4 { return Err(OpenSSHKeyError::InvalidFormat); } self.offset += len + 4; Ok(&cur[4..len + 4]) } } #[cfg(test)] mod tests { use super::*; #[test] fn reader_empty() { let data = vec![]; let mut rd = Reader::new(data.as_ref()); assert!(rd.peek_int().is_err()); assert!(rd.read_bytes().is_err()); assert!(rd.read_mpint().is_err()); assert!(rd.read_string().is_err()); } } openssh-keys-0.6.2/src/writer.rs000064400000000000000000000037361046102023000147430ustar 00000000000000//! This module provides a struct for writing bytes in the OpenSSH public key format. use byteorder::{BigEndian, WriteBytesExt}; pub struct Writer { data: Vec, } impl Writer { pub fn new() -> Writer { Writer { data: vec![] } } pub fn into_vec(self) -> Vec { self.data } pub fn write_int(&mut self, val: u32) { if let Err(..) = self.data.write_u32::(val) { unreachable!() }; } pub fn write_bytes(&mut self, mut buf: Vec) { if buf.is_empty() { return; } // The first four bytes represent the length of the encoded data. self.write_int(buf.len() as u32); // the rest of the bytes are the data itself self.data.append(&mut buf); } // according to RFC 4251, the mpint datatype representation is a big-endian // arbitrary-precision integer encoded in two's complement and stored as a // string with the minimum possible number of characters. // see mpint definition in https://tools.ietf.org/html/rfc4251#section-5 pub fn write_mpint(&mut self, mut num: Vec) { // If the number is positive then we are required to guarentee that the // most significant bit is set to zero if the first bit in the first // byte is going to be one. if num.first().unwrap_or(&0) & 0x80 != 0 { num.insert(0, 0); } // other than that it's just normal ssh encoding self.write_bytes(num) } pub fn write_string(&mut self, val: &str) { self.write_bytes(val.as_bytes().to_vec()) } } #[cfg(test)] mod tests { use super::*; #[test] fn writer_empty() { let w = Writer::new(); assert_eq!(w.into_vec().len(), 0); let mut w = Writer::new(); w.write_bytes(vec![]); assert_eq!(w.into_vec().len(), 0); let mut w = Writer::new(); w.write_mpint(vec![]); assert_eq!(w.into_vec().len(), 0); } }