├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── feature_request.md │ └── question.md ├── PULL_REQUEST_TEMPLATE.md ├── actions-rs │ └── grcov.yml └── workflows │ ├── build.yml │ └── coverage.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE ├── README.md ├── assets └── ssh.config ├── build ├── define_parser.rs ├── main.rs ├── openssh.rs └── src_writer.rs ├── examples ├── client.rs ├── print.rs └── query.rs ├── rustfmt.toml └── src ├── default_algorithms.rs ├── default_algorithms └── openssh.rs ├── host.rs ├── lib.rs ├── params.rs ├── params └── algos.rs ├── parser.rs ├── parser └── field.rs └── serializer.rs /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report of the bug you've encountered 4 | title: "[BUG] - ISSUE_TITLE" 5 | labels: bug 6 | assignees: veeso 7 | 8 | --- 9 | 10 | ## Description 11 | 12 | A clear and concise description of what the bug is. 13 | 14 | ## Steps to reproduce 15 | 16 | Steps to reproduce the bug you encountered 17 | 18 | ## Expected behaviour 19 | 20 | A clear and concise description of what you expected to happen. 21 | 22 | ## Environment 23 | 24 | - OS: [e.g. GNU/Linux Debian 10] 25 | - Architecture [Arm, x86_64, ...] 26 | - Rust version 27 | - remotefs version 28 | - Protocol used 29 | - Remote server version and name 30 | 31 | ## Additional information 32 | 33 | Add any other context about the problem here. 34 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea to improve ssh2-config 4 | title: "[Feature Request] - FEATURE_TITLE" 5 | labels: "new feature" 6 | assignees: veeso 7 | 8 | --- 9 | 10 | ## Description 11 | 12 | Put here a brief introduction to your suggestion. 13 | 14 | ### Changes 15 | 16 | The following changes to the application are expected 17 | 18 | - ... 19 | 20 | ## Implementation 21 | 22 | Provide any kind of suggestion you propose on how to implement the feature. 23 | If you have none, delete this section. 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Ask what you want about the project 4 | title: "[QUESTION] - TITLE" 5 | labels: question 6 | assignees: veeso 7 | 8 | --- 9 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # ISSUE _NUMBER_ - PULL_REQUEST_TITLE 2 | 3 | Fixes # (issue) 4 | 5 | ## Description 6 | 7 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. 8 | 9 | List here your changes 10 | 11 | - I made this... 12 | - I made also that... 13 | 14 | ## Type of change 15 | 16 | Please select relevant options. 17 | 18 | - [ ] Bug fix (non-breaking change which fixes an issue) 19 | - [ ] New feature (non-breaking change which adds functionality) 20 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 21 | - [ ] This change requires a documentation update 22 | 23 | ## Checklist 24 | 25 | - [ ] My code follows the contribution guidelines of this project 26 | - [ ] I have performed a self-review of my own code 27 | - [ ] I have commented my code, particularly in hard-to-understand areas 28 | - [ ] My changes generate no new warnings 29 | - [ ] I formatted the code with `cargo fmt` 30 | - [ ] I checked my code using `cargo clippy` and reports no warnings 31 | - [ ] I have added tests that prove my fix is effective or that my feature works 32 | - [ ] The changes I've made are Windows, MacOS, Linux compatible (or I've handled them using `cfg target_os`) 33 | - [ ] I increased or maintained the code coverage for the project, compared to the previous commit 34 | 35 | ## Acceptance tests 36 | 37 | wait for a *project maintainer* to fulfill this section... 38 | 39 | - [ ] regression test: ... 40 | -------------------------------------------------------------------------------- /.github/actions-rs/grcov.yml: -------------------------------------------------------------------------------- 1 | branch: false 2 | ignore-not-existing: true 3 | llvm: true 4 | output-type: lcov 5 | ignore: 6 | - "/*" 7 | - "C:/*" 8 | - "../*" 9 | - src/lib.rs 10 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | env: 6 | CARGO_TERM_COLOR: always 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: Swatinem/rust-cache@v2 15 | with: 16 | cache-on-failure: true 17 | - uses: dtolnay/rust-toolchain@stable 18 | - name: Set up environment for tests 19 | run: mkdir -p $HOME/.ssh && touch $HOME/.ssh/config 20 | - name: build 21 | run: cargo build --verbose 22 | - name: Style check 23 | run: cargo fmt --all --check 24 | - name: Run tests 25 | run: cargo test 26 | - name: Clippy 27 | run: cargo clippy -- -Dwarnings 28 | -------------------------------------------------------------------------------- /.github/workflows/coverage.yml: -------------------------------------------------------------------------------- 1 | name: Coverage 2 | 3 | on: [push, pull_request] 4 | 5 | env: 6 | CARGO_TERM_COLOR: always 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: dtolnay/rust-toolchain@stable 15 | - uses: taiki-e/install-action@cargo-llvm-cov 16 | - name: Set up environment for tests 17 | run: mkdir -p $HOME/.ssh && touch $HOME/.ssh/config 18 | - name: Generate code coverage 19 | run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info 20 | - name: Upload coverage artifact 21 | uses: actions/upload-artifact@v4 22 | with: 23 | path: lcov.info 24 | - name: Coveralls 25 | uses: coverallsapp/github-action@v2.3.4 26 | with: 27 | github-token: ${{ secrets.GITHUB_TOKEN }} 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | .rpm/ 3 | 4 | # Created by https://www.gitignore.io/api/rust 5 | # Edit at https://www.gitignore.io/?templates=rust 6 | 7 | ### Rust ### 8 | # Generated by Cargo 9 | # will have compiled files and executables 10 | /target/ 11 | # for libs 12 | Cargo.lock 13 | 14 | # These are backup files generated by rustfmt 15 | **/*.rs.bk 16 | 17 | # End of https://www.gitignore.io/api/rust 18 | 19 | # Distributions 20 | *.rpm 21 | *.deb 22 | dist/pkgs/arch/*.tar.gz 23 | 24 | # Macos 25 | .DS_Store 26 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | - [Changelog](#changelog) 4 | - [0.5.4](#054) 5 | - [0.5.1](#051) 6 | - [0.5.0](#050) 7 | - [0.4.0](#040) 8 | - [0.3.0](#030) 9 | - [0.2.3](#023) 10 | - [0.2.2](#022) 11 | - [0.2.1](#021) 12 | - [0.2.0](#020) 13 | - [0.1.6](#016) 14 | - [0.1.5](#015) 15 | - [0.1.4](#014) 16 | - [0.1.3](#013) 17 | - [0.1.2](#012) 18 | - [0.1.1](#011) 19 | - [0.1.0](#010) 20 | 21 | --- 22 | 23 | ## 0.5.4 24 | 25 | Released on 27/03/2025 26 | 27 | - on docsrs DON'T build algos. It's not allowed by docs.rs 28 | - added `RELOAD_SSH_ALGO` env variable to rebuild algos. 29 | 30 | ## 0.5.1 31 | 32 | Released on 27/03/2025 33 | 34 | - build was not included in the package. Fixed that. 35 | 36 | ## 0.5.0 37 | 38 | Released on 27/03/2025 39 | 40 | - [issue 22](https://github.com/veeso/ssh2-config/issues/22): should parse tokens with `=` and quotes (`"`) 41 | - [issue 21](https://github.com/veeso/ssh2-config/issues/21): Finally fixed how parameters are applied to host patterns 42 | - Replaced algorithms `Vec` with `Algorithms` type. 43 | - The new type is a variant with `Append`, `Head`, `Exclude` and `Set`. 44 | - This allows to **ACTUALLY** handle algorithms correctly. 45 | - To pass to ssh options, use `algorithms()` method 46 | - Beware that when accessing the internal vec, you MUST care of what it means for that variant. 47 | - Replaced `HostParams::merge` with `HostParams::overwrite_if_none` to avoid overwriting existing values. 48 | - Added default Algorithms to the SshConfig structure. See readme for details on how to use it. 49 | 50 | ## 0.4.0 51 | 52 | Released on 15/03/2025 53 | 54 | - Added support for `Include` directive. 55 | - Fixed ordering in appliance of options. **It's always top-bottom**. 56 | - Added logging to parser. You can now disable logging by using `nolog` feature. 57 | - `parse_default_file` is now available to Windows users 58 | - Added `Display` and `ToString` traits for `SshConfig` which serializes the configuration into ssh2 format 59 | 60 | ## 0.3.0 61 | 62 | Released on 19/12/2024 63 | 64 | - thiserror `2.0` 65 | - ‼️ **BREAKING CHANGE**: Added support for unsupported fields: 66 | 67 | `AddressFamily, BatchMode, CanonicalDomains, CanonicalizeFallbackLock, CanonicalizeHostname, CanonicalizeMaxDots, CanonicalizePermittedCNAMEs, CheckHostIP, ClearAllForwardings, ControlMaster, ControlPath, ControlPersist, DynamicForward, EnableSSHKeysign, EscapeChar, ExitOnForwardFailure, FingerprintHash, ForkAfterAuthentication, ForwardAgent, ForwardX11, ForwardX11Timeout, ForwardX11Trusted, GatewayPorts, GlobalKnownHostsFile, GSSAPIAuthentication, GSSAPIDelegateCredentials, HashKnownHosts, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostKeyAlias, HostbasedKeyTypes, IdentitiesOnly, IdentityAgent, Include, IPQoS, KbdInteractiveAuthentication, KbdInteractiveDevices, KnownHostsCommand, LocalCommand, LocalForward, LogLevel, LogVerbose, NoHostAuthenticationForLocalhost, NumberOfPasswordPrompts, PasswordAuthentication, PermitLocalCommand, PermitRemoteOpen, PKCS11Provider, PreferredAuthentications, ProxyCommand, ProxyJump, ProxyUseFdpass, PubkeyAcceptedKeyTypes, RekeyLimit, RequestTTY, RevokedHostKeys, SecruityKeyProvider, SendEnv, ServerAliveCountMax, SessionType, SetEnv, StdinNull, StreamLocalBindMask, StrictHostKeyChecking, SyslogFacility, UpdateHostKeys, UserKnownHostsFile, VerifyHostKeyDNS, VisualHostKey, XAuthLocation` 68 | 69 | If you want to keep the behaviour as-is, use `ParseRule::STRICT | ParseRule::ALLOW_UNSUPPORTED_FIELDS` when calling `parse()` if you were using `ParseRule::STRICT` before. 70 | 71 | Otherwise you can now access unsupported fields by using the `unsupported_fields` field on the `HostParams` structure like this: 72 | 73 | ```rust 74 | use ssh2_config::{ParseRule, SshConfig}; 75 | use std::fs::File; 76 | use std::io::BufReader; 77 | 78 | let mut reader = BufReader::new(File::open(config_path).expect("Could not open configuration file")); 79 | let config = SshConfig::default().parse(&mut reader, ParseRule::ALLOW_UNSUPPORTED_FIELDS).expect("Failed to parse configuration"); 80 | 81 | // Query attributes for a certain host 82 | let params = config.query("192.168.1.2"); 83 | let forwards = params.unsupported_fields.get("dynamicforward"); 84 | ``` 85 | 86 | ## 0.2.3 87 | 88 | Released on 05/12/2023 89 | 90 | - Fixed the order of appliance of configuration argument when overriding occurred. Thanks @LeoniePhiline 91 | 92 | ## 0.2.2 93 | 94 | Released on 31/07/2023 95 | 96 | - Exposed `ignored_fields` as `Map>` (KeyName => Args) for `HostParams` 97 | 98 | ## 0.2.1 99 | 100 | Released on 28/07/2023 101 | 102 | - Added `parse_default_file` to parse directly the default ssh config file at `$HOME/.ssh/config` 103 | - Added `get_hosts` to retrieve current configuration's hosts 104 | 105 | ## 0.2.0 106 | 107 | Released on 09/05/2023 108 | 109 | - Added `ParseRule` field to `parse()` method to specify some rules for parsing. ❗ To keep the behaviour as-is use `ParseRule::STRICT` 110 | 111 | ## 0.1.6 112 | 113 | Released on 03/03/2023 114 | 115 | - Added legacy field support 116 | - HostbasedKeyTypes 117 | - PubkeyAcceptedKeyTypes 118 | 119 | ## 0.1.5 120 | 121 | Released on 27/02/2023 122 | 123 | - Fixed comments not being properly stripped 124 | 125 | ## 0.1.4 126 | 127 | Released on 02/02/2023 128 | 129 | - Fixed [issue 2](https://github.com/veeso/ssh2-config/issues/2) hosts not being sorted by priority in host query 130 | 131 | ## 0.1.3 132 | 133 | Released on 29/01/2022 134 | 135 | - Added missing `ForwardX11Trusted` field to known fields 136 | 137 | ## 0.1.2 138 | 139 | Released on 11/01/2022 140 | 141 | - Implemented `IgnoreUnknown` parameter 142 | - Added `UseKeychain` support for MacOS 143 | 144 | ## 0.1.1 145 | 146 | Released on 02/01/2022 147 | 148 | - Added `IdentityFile` parameter 149 | 150 | ## 0.1.0 151 | 152 | Released on 04/12/2021 153 | 154 | - First release 155 | -------------------------------------------------------------------------------- /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, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and 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 christian.visintin1997@gmail.com. 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 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Before contributing to this repository, please first discuss the change you wish to make via issue of this repository before making a change. 4 | Please note we have a [code of conduct](CODE_OF_CONDUCT.md), please follow it in all your interactions with the project. 5 | 6 | - [Contributing](#contributing) 7 | - [Open an issue](#open-an-issue) 8 | - [Questions](#questions) 9 | - [Bug reports](#bug-reports) 10 | - [Feature requests](#feature-requests) 11 | - [Preferred contributions](#preferred-contributions) 12 | - [Pull Request Process](#pull-request-process) 13 | - [Software guidelines](#software-guidelines) 14 | 15 | --- 16 | 17 | ## Open an issue 18 | 19 | Open an issue when: 20 | 21 | - You have questions or concerns regarding the project or the application itself. 22 | - You have a bug to report. 23 | - You have a feature or a suggestion to improve ssh2-config to submit. 24 | 25 | ### Questions 26 | 27 | If you have a question open an issue using the `Question` template. 28 | By default your question should already be labeled with the `question` label, if you need help with your installation, please also add the `help wanted` label. 29 | Check the issue is always assigned to `veeso`. 30 | 31 | ### Bug reports 32 | 33 | If you want to report an issue or a bug you've encountered while using ssh2-config, open an issue using the `Bug report` template. 34 | The `Bug` label should already be set and the issue should already be assigned to `veeso`. 35 | Don't set other labels to your issue, not even priority. 36 | 37 | When you open a bug try to be the most precise as possible in describing your issue. I'm not saying you should always be that precise, since sometimes it's very easy for maintainers to understand what you're talking about. Just try to be reasonable to understand sometimes we might not know what you're talking about or we just don't have the technical knowledge you might think. 38 | Please always provide the environment you're working on and consider that we don't provide any support for older version of ssh2-config, at least for those not classified as LTS (if we'll ever have them). 39 | If you can, provide the log file or the snippet involving your issue. You can find in the [user manual](docs/man.md) the location of the log file. 40 | Last but not least: the template I've written must be used. Full stop. 41 | 42 | Maintainers will may add additional labels to your issue: 43 | 44 | - **duplicate**: the issue is duplicated; the reference to the related issue will be added to your description. Your issue will be closed. 45 | - **priority**: this must be fixed asap 46 | - **sorcery**: it is not possible to find out what's causing your bug, nor is reproducible on our test environments. 47 | - **wontfix**: your bug has a very high ratio between the difficulty to fix it and the probability to encounter it, or it just isn't a bug, but a feature. 48 | 49 | ### Feature requests 50 | 51 | Whenever you have a good idea which chould improve the project, it is a good idea to submit it to the project owner. 52 | The first thing you should do though, is not starting to write the code, but is to become concern about how ssh2-config works, what kind 53 | of contribution I appreciate and what kind of contribution I won't consider. 54 | Said so, follow these steps: 55 | 56 | - Read the contributing guidelines, entirely 57 | - Think on whether your idea would fit in the project mission and guidelines or not 58 | - Think about the impact your idea would have on the project 59 | - Open an issue using the `feature request` template describing with accuracy your suggestion 60 | - Wait for the maintainer feedback on your idea 61 | 62 | If you want to implement the feature by yourself and your suggestion gets approved, start writing the code. Remember that on [docs.rs](https://docs.rs/ssh2-config) there is the documentation for the project. Open a PR related to your issue. See [Pull request process for more details](#pull-request-process) 63 | 64 | It is very important to follow these steps, since it will prevent you from working on a feature that will be rejected and trust me, none of us wants to deal with this situation. 65 | 66 | Always mind that your suggestion, may be rejected: I'll always provide a feedback on the reasons that brought me to reject your feature, just try not to get mad about that. 67 | 68 | --- 69 | 70 | ## Preferred contributions 71 | 72 | At the moment, these kind of contributions are more appreciated and should be preferred: 73 | 74 | - Fix for issues described in [Known Issues](./README.md#known-issues-) or [issues reported by the community](https://github.com/veeso/ssh2-config/issues) 75 | - New file transfers: for further details see [Implementing File Transfer](#implementing-file-transfers) 76 | - Code optimizations: any optimization to the code is welcome 77 | 78 | For any other kind of contribution, especially for new features, please submit a new issue first. 79 | 80 | ## Pull Request Process 81 | 82 | Let's make it simple and clear: 83 | 84 | 1. Open a PR with an **appropriate label** (e.g. bug, enhancement, ...). 85 | 2. Write a **properly documentation** for your software compliant with **rustdoc** standard. 86 | 3. Write tests for your code. This doesn't apply necessarily for implementation regarding the user-interface module (`ui/activities`) and (if a test server is not available) for file transfers. 87 | 4. Check your code with `cargo clippy`. 88 | 5. Check if the CI for your commits reports three-green. 89 | 6. Report changes to the PR you opened, writing a report of what you changed and what you have introduced. 90 | 7. Update the `CHANGELOG.md` file with details of changes to the application. In changelog report changes under a chapter called `PR{PULL_REQUEST_NUMBER}` (e.g. PR12). 91 | 8. Assign a maintainer to the reviewers. 92 | 9. Wait for a maintainer to fullfil the acceptance tests 93 | 10. Wait for a maintainer to complete the acceptance tests 94 | 11. Request maintainers to merge your changes. 95 | 96 | ### Software guidelines 97 | 98 | In addition to the process described for the PRs, I've also decided to introduce a list of guidelines to follow when writing the code, that should be followed: 99 | 100 | 1. **Let's stop the NPM apocalypse**: personally I'm against the abuse of dependencies we make in software projects and I think that NodeJS has opened the way to this drama (and has already gone too far). Nowadays nobody cares about adding hundreds of dependencies to their projects. Don't misunderstand me: I think that package managers are cool, but I'm totally against the abuse we're making of them. I think when we work on a project, we should try to use the minor quantity of dependencies as possible, especially because it's not hard to see how many libraries are getting abandoned right now, causing compatibility issues after a while. So please, when working on ssh2-config, try not to add useless dependencies. 101 | 2. **Test units matter**: Whenever you implement something new to this project, always implement test units which cover the most cases as possible. 102 | 3. **Comments are useful**: Many people say that the code should be that simple to talk by itself about what it does, and comments should then be useless. I personally don't agree. I'm not saying they're wrong, but I'm just saying that this approach has, in my personal opinion, many aspects which are underrated: 103 | 1. What's obvious for me, might not be for the others. 104 | 2. Our capacity to work on a code depends mostly on **time and experience**, not on complexity: I'm not denying complexity matter, but the most decisive factor when working on code is the experience we've acquired working on it and the time we've spent. As the author of the project, I know the project like the back of my hands, but if I didn't work on it for a year, then I would probably have some problems in working on it again as the same speed as before. And do you know what's really time-saving in these cases? Comments. 105 | 106 | --- 107 | 108 | Thank you for any contribution! 109 | Christian Visintin 110 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Christian Visintin "] 3 | categories = ["network-programming"] 4 | description = "an ssh configuration parser for ssh2-rs" 5 | documentation = "https://docs.rs/ssh2-config" 6 | edition = "2024" 7 | homepage = "https://veeso.github.io/ssh2-config/" 8 | include = [ 9 | "build/**/*", 10 | "examples/**/*", 11 | "src/**/*", 12 | "LICENSE", 13 | "README.md", 14 | "CHANGELOG.md", 15 | ] 16 | keywords = ["ssh2", "ssh", "ssh-config", "ssh-config-parser"] 17 | license = "MIT" 18 | name = "ssh2-config" 19 | readme = "README.md" 20 | repository = "https://github.com/veeso/ssh2-config" 21 | version = "0.5.4" 22 | build = "build/main.rs" 23 | 24 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 25 | 26 | [dependencies] 27 | bitflags = "^2" 28 | dirs = "^6" 29 | log = "^0.4" 30 | glob = "0.3" 31 | thiserror = "^2" 32 | wildmatch = "^2" 33 | 34 | [dev-dependencies] 35 | env_logger = "^0.11" 36 | pretty_assertions = "^1" 37 | rpassword = "^7" 38 | ssh2 = "^0.9" 39 | tempfile = "^3" 40 | 41 | [build-dependencies] 42 | anyhow = "1" 43 | git2 = "0.20" 44 | 45 | [features] 46 | default = [] 47 | nolog = ["log/max_level_off"] 48 | 49 | [[example]] 50 | name = "client" 51 | path = "examples/client.rs" 52 | 53 | [[example]] 54 | name = "query" 55 | path = "examples/query.rs" 56 | 57 | [[example]] 58 | name = "print" 59 | path = "examples/print.rs" 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021-2025 Christian Visintin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ssh2-config 2 | 3 |

4 | Changelog 5 | · 6 | Get started 7 | · 8 | Documentation 9 |

10 | 11 |

Developed by @veeso

12 |

Current version: 0.5.4 (27/03/2025)

13 | 14 |

15 | License-MIT 20 | Repo stars 25 | Downloads counter 30 | Latest version 35 | 36 | Ko-fi 40 |

41 |

42 | Build 47 | Coveralls 52 | Docs 57 |

58 | 59 | --- 60 | 61 | - [ssh2-config](#ssh2-config) 62 | - [About ssh2-config](#about-ssh2-config) 63 | - [Exposed attributes](#exposed-attributes) 64 | - [Missing features](#missing-features) 65 | - [Get started 🚀](#get-started-) 66 | - [Reading unsupported fields](#reading-unsupported-fields) 67 | - [How host parameters are resolved](#how-host-parameters-are-resolved) 68 | - [Resolvers examples](#resolvers-examples) 69 | - [Configuring default algorithms](#configuring-default-algorithms) 70 | - [Examples](#examples) 71 | - [Support the developer ☕](#support-the-developer-) 72 | - [Contributing and issues 🤝🏻](#contributing-and-issues-) 73 | - [Changelog ⏳](#changelog-) 74 | - [License 📃](#license-) 75 | 76 | --- 77 | 78 | ## About ssh2-config 79 | 80 | ssh2-config a library which provides a parser for the SSH configuration file, to be used in pair with the [ssh2](https://github.com/alexcrichton/ssh2-rs) crate. 81 | 82 | This library provides a method to parse the configuration file and returns the configuration parsed into a structure. 83 | The `SshConfig` structure provides all the attributes which **can** be used to configure the **ssh2 Session** and to resolve 84 | the host, port and username. 85 | 86 | Once the configuration has been parsed you can use the `query(&str)` method to query configuration for a certain host, based on the configured patterns. 87 | 88 | Even if many attributes are not exposed, since not supported, there is anyway a validation of the configuration, so invalid configuration will result in a parsing error. 89 | 90 | ### Exposed attributes 91 | 92 | - **BindAddress**: you can use this attribute to bind the socket to a certain address 93 | - **BindInterface**: you can use this attribute to bind the socket to a certain network interface 94 | - **CASignatureAlgorithms**: you can use this attribute to handle CA certificates 95 | - **CertificateFile**: you can use this attribute to parse the certificate file in case is necessary 96 | - **Ciphers**: you can use this attribute to set preferred methods with the session method `session.method_pref(MethodType::CryptCs, ...)` and `session.method_pref(MethodType::CryptSc, ...)` 97 | - **Compression**: you can use this attribute to set whether compression is enabled with `session.set_compress(value)` 98 | - **ConnectionAttempts**: you can use this attribute to cycle over connect in order to retry 99 | - **ConnectTimeout**: you can use this attribute to set the connection timeout for the socket 100 | - **HostName**: you can use this attribute to get the real name of the host to connect to 101 | - **IdentityFile**: you can use this attribute to set the keys to try when connecting to remote host. 102 | - **KexAlgorithms**: you can use this attribute to configure Key exchange methods with `session.method_pref(MethodType::Kex, algos.to_string().as_str())` 103 | - **MACs**: you can use this attribute to configure the MAC algos with `session.method_pref(MethodType::MacCs, algos..to_string().as_str())` and `session.method_pref(MethodType::MacSc, algos..to_string().as_str())` 104 | - **Port**: you can use this attribute to resolve the port to connect to 105 | - **PubkeyAuthentication**: you can use this attribute to set whether to use the pubkey authentication 106 | - **RemoteForward**: you can use this method to implement port forwarding with `session.channel_forward_listen()` 107 | - **ServerAliveInterval**: you can use this method to implement keep alive message interval 108 | - **TcpKeepAlive**: you can use this method to tell whether to send keep alive message 109 | - **UseKeychain**: (macos only) used to tell whether to use keychain to decrypt ssh keys 110 | - **User**: you can use this method to resolve the user to use to log in as 111 | 112 | ### Missing features 113 | 114 | - [Match patterns](http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5#Match) (Host patterns are supported!!!) 115 | - [Tokens](http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5#TOKENS) 116 | 117 | --- 118 | 119 | ## Get started 🚀 120 | 121 | First of all, add ssh2-config to your dependencies 122 | 123 | ```toml 124 | [dependencies] 125 | ssh2-config = "^0.5" 126 | ``` 127 | 128 | then parse the configuration 129 | 130 | ```rust 131 | use ssh2_config::{ParseRule, SshConfig}; 132 | use std::fs::File; 133 | use std::io::BufReader; 134 | 135 | let mut reader = BufReader::new(File::open(config_path).expect("Could not open configuration file")); 136 | let config = SshConfig::default().parse(&mut reader, ParseRule::STRICT).expect("Failed to parse configuration"); 137 | 138 | // Query attributes for a certain host 139 | let params = config.query("192.168.1.2"); 140 | ``` 141 | 142 | then you can use the parsed parameters to configure the session: 143 | 144 | ```rust 145 | use ssh2::Session; 146 | use ssh2_config::{HostParams}; 147 | 148 | fn configure_session(session: &mut Session, params: &HostParams) { 149 | if let Some(compress) = params.compression { 150 | session.set_compress(compress); 151 | } 152 | if params.tcp_keep_alive.unwrap_or(false) && params.server_alive_interval.is_some() { 153 | let interval = params.server_alive_interval.unwrap().as_secs() as u32; 154 | session.set_keepalive(true, interval); 155 | } 156 | // KEX 157 | if let Err(err) = session.method_pref( 158 | MethodType::Kex, 159 | params.kex_algorithms.algorithms().join(",").as_str(), 160 | ) { 161 | panic!("Could not set KEX algorithms: {}", err); 162 | } 163 | 164 | // host key 165 | if let Err(err) = session.method_pref( 166 | MethodType::HostKey, 167 | params.host_key_algorithms.algorithms().join(",").as_str(), 168 | ) { 169 | panic!("Could not set host key algorithms: {}", err); 170 | } 171 | 172 | // ciphers 173 | if let Err(err) = session.method_pref( 174 | MethodType::CryptCs, 175 | params.ciphers.algorithms().join(",").as_str(), 176 | ) { 177 | panic!("Could not set crypt algorithms (client-server): {}", err); 178 | } 179 | if let Err(err) = session.method_pref( 180 | MethodType::CryptSc, 181 | params.ciphers.algorithms().join(",").as_str(), 182 | ) { 183 | panic!("Could not set crypt algorithms (server-client): {}", err); 184 | } 185 | 186 | // mac 187 | if let Err(err) = session.method_pref( 188 | MethodType::MacCs, 189 | params.mac.algorithms().join(",").as_str(), 190 | ) { 191 | panic!("Could not set MAC algorithms (client-server): {}", err); 192 | } 193 | if let Err(err) = session.method_pref( 194 | MethodType::MacSc, 195 | params.mac.algorithms().join(",").as_str(), 196 | ) { 197 | panic!("Could not set MAC algorithms (server-client): {}", err); 198 | } 199 | } 200 | 201 | fn auth_with_rsakey( 202 | session: &mut Session, 203 | params: &HostParams, 204 | username: &str, 205 | password: Option<&str> 206 | ) { 207 | for identity_file in params.identity_file.unwrap_or_default().iter() { 208 | if let Ok(_) = session.userauth_pubkey_file(username, None, identity_file, password) { 209 | break; 210 | } 211 | } 212 | } 213 | 214 | ``` 215 | 216 | ### Reading unsupported fields 217 | 218 | As outlined above, ssh2-config does not support all parameters available in the man page of the SSH configuration file. 219 | 220 | If you require these fields you may still access them through the `unsupported_fields` field on the `HostParams` structure like this: 221 | 222 | ```rust 223 | use ssh2_config::{ParseRule, SshConfig}; 224 | use std::fs::File; 225 | use std::io::BufReader; 226 | 227 | let mut reader = BufReader::new(File::open(config_path).expect("Could not open configuration file")); 228 | let config = SshConfig::default().parse(&mut reader, ParseRule::ALLOW_UNSUPPORTED_FIELDS).expect("Failed to parse configuration"); 229 | 230 | // Query attributes for a certain host 231 | let params = config.query("192.168.1.2"); 232 | let forwards = params.unsupported_fields.get("dynamicforward"); 233 | ``` 234 | 235 | --- 236 | 237 | ## How host parameters are resolved 238 | 239 | This topic has been debated a lot over the years, so finally since 0.5 this has been fixed to follow the official ssh configuration file rules, as described in the MAN . 240 | 241 | > Unless noted otherwise, for each parameter, the first obtained value will be used. The configuration files contain sections separated by Host specifications, and that section is only applied for hosts that match one of the patterns given in the specification. The matched host name is usually the one given on the command line (see the CanonicalizeHostname option for exceptions). 242 | > 243 | > Since the first obtained value for each parameter is used, more host-specific declarations should be given near the beginning of the file, and general defaults at the end. 244 | 245 | This means that: 246 | 247 | 1. The first obtained value parsing the configuration top-down will be used 248 | 2. Host specific rules ARE not overriding default ones if they are not the first obtained value 249 | 3. If you want to achieve default values to be less specific than host specific ones, you should put the default values at the end of the configuration file using `Host *`. 250 | 4. Algorithms, so `KexAlgorithms`, `Ciphers`, `MACs` and `HostKeyAlgorithms` use a different resolvers which supports appending, excluding and heading insertions, as described in the man page at ciphers: . They are in case appended to default algorithms, which are either fetched from the openssh source code or set with a constructor. See [configuring default algorithms](#configuring-default-algorithms) for more information. 251 | 252 | ### Resolvers examples 253 | 254 | ```ssh 255 | Compression yes 256 | 257 | Host 192.168.1.1 258 | Compression no 259 | ``` 260 | 261 | If we get rules for `192.168.1.1`, compression will be `yes`, because it's the first obtained value. 262 | 263 | ```ssh 264 | Host 192.168.1.1 265 | Compression no 266 | 267 | Host * 268 | Compression yes 269 | ``` 270 | 271 | If we get rules for `192.168.1.1`, compression will be `no`, because it's the first obtained value. 272 | 273 | If we get rules for `172.168.1.1`, compression will be `yes`, because it's the first obtained value MATCHING the host rule. 274 | 275 | ```ssh 276 | Host 192.168.1.1 277 | Ciphers +c 278 | ``` 279 | 280 | If we get rules for `192.168.1.1`, ciphers will be `a,b,c`, because default is set to `a,b` and `+c` means append `c` to the list. 281 | 282 | --- 283 | 284 | ## Configuring default algorithms 285 | 286 | To reload algos, build ssh2-config with `RELOAD_SSH_ALGO` env variable set. 287 | 288 | When you invoke `SshConfig::default`, the default algorithms are set from openssh source code, which are the following: 289 | 290 | ```txt 291 | ca_signature_algorithms: 292 | "ssh-ed25519", 293 | "ecdsa-sha2-nistp256", 294 | "ecdsa-sha2-nistp384", 295 | "ecdsa-sha2-nistp521", 296 | "sk-ssh-ed25519@openssh.com", 297 | "sk-ecdsa-sha2-nistp256@openssh.com", 298 | "rsa-sha2-512", 299 | "rsa-sha2-256", 300 | 301 | ciphers: 302 | "chacha20-poly1305@openssh.com", 303 | "aes128-ctr,aes192-ctr,aes256-ctr", 304 | "aes128-gcm@openssh.com,aes256-gcm@openssh.com", 305 | 306 | host_key_algorithms: 307 | "ssh-ed25519-cert-v01@openssh.com", 308 | "ecdsa-sha2-nistp256-cert-v01@openssh.com", 309 | "ecdsa-sha2-nistp384-cert-v01@openssh.com", 310 | "ecdsa-sha2-nistp521-cert-v01@openssh.com", 311 | "sk-ssh-ed25519-cert-v01@openssh.com", 312 | "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", 313 | "rsa-sha2-512-cert-v01@openssh.com", 314 | "rsa-sha2-256-cert-v01@openssh.com", 315 | "ssh-ed25519", 316 | "ecdsa-sha2-nistp256", 317 | "ecdsa-sha2-nistp384", 318 | "ecdsa-sha2-nistp521", 319 | "sk-ssh-ed25519@openssh.com", 320 | "sk-ecdsa-sha2-nistp256@openssh.com", 321 | "rsa-sha2-512", 322 | "rsa-sha2-256", 323 | 324 | kex_algorithms: 325 | "sntrup761x25519-sha512", 326 | "sntrup761x25519-sha512@openssh.com", 327 | "mlkem768x25519-sha256", 328 | "curve25519-sha256", 329 | "curve25519-sha256@libssh.org", 330 | "ecdh-sha2-nistp256", 331 | "ecdh-sha2-nistp384", 332 | "ecdh-sha2-nistp521", 333 | "diffie-hellman-group-exchange-sha256", 334 | "diffie-hellman-group16-sha512", 335 | "diffie-hellman-group18-sha512", 336 | "diffie-hellman-group14-sha256", 337 | "ssh-ed25519-cert-v01@openssh.com", 338 | "ecdsa-sha2-nistp256-cert-v01@openssh.com", 339 | "ecdsa-sha2-nistp384-cert-v01@openssh.com", 340 | "ecdsa-sha2-nistp521-cert-v01@openssh.com", 341 | "sk-ssh-ed25519-cert-v01@openssh.com", 342 | "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", 343 | "rsa-sha2-512-cert-v01@openssh.com", 344 | "rsa-sha2-256-cert-v01@openssh.com", 345 | "ssh-ed25519", 346 | "ecdsa-sha2-nistp256", 347 | "ecdsa-sha2-nistp384", 348 | "ecdsa-sha2-nistp521", 349 | "sk-ssh-ed25519@openssh.com", 350 | "sk-ecdsa-sha2-nistp256@openssh.com", 351 | "rsa-sha2-512", 352 | "rsa-sha2-256", 353 | "chacha20-poly1305@openssh.com", 354 | "aes128-ctr,aes192-ctr,aes256-ctr", 355 | "aes128-gcm@openssh.com,aes256-gcm@openssh.com", 356 | "chacha20-poly1305@openssh.com", 357 | "aes128-ctr,aes192-ctr,aes256-ctr", 358 | "aes128-gcm@openssh.com,aes256-gcm@openssh.com", 359 | "umac-64-etm@openssh.com", 360 | "umac-128-etm@openssh.com", 361 | "hmac-sha2-256-etm@openssh.com", 362 | "hmac-sha2-512-etm@openssh.com", 363 | "hmac-sha1-etm@openssh.com", 364 | "umac-64@openssh.com", 365 | "umac-128@openssh.com", 366 | "hmac-sha2-256", 367 | "hmac-sha2-512", 368 | "hmac-sha1", 369 | "umac-64-etm@openssh.com", 370 | "umac-128-etm@openssh.com", 371 | "hmac-sha2-256-etm@openssh.com", 372 | "hmac-sha2-512-etm@openssh.com", 373 | "hmac-sha1-etm@openssh.com", 374 | "umac-64@openssh.com", 375 | "umac-128@openssh.com", 376 | "hmac-sha2-256", 377 | "hmac-sha2-512", 378 | "hmac-sha1", 379 | "none,zlib@openssh.com", 380 | "none,zlib@openssh.com", 381 | 382 | mac: 383 | "umac-64-etm@openssh.com", 384 | "umac-128-etm@openssh.com", 385 | "hmac-sha2-256-etm@openssh.com", 386 | "hmac-sha2-512-etm@openssh.com", 387 | "hmac-sha1-etm@openssh.com", 388 | "umac-64@openssh.com", 389 | "umac-128@openssh.com", 390 | "hmac-sha2-256", 391 | "hmac-sha2-512", 392 | "hmac-sha1", 393 | 394 | pubkey_accepted_algorithms: 395 | "ssh-ed25519-cert-v01@openssh.com", 396 | "ecdsa-sha2-nistp256-cert-v01@openssh.com", 397 | "ecdsa-sha2-nistp384-cert-v01@openssh.com", 398 | "ecdsa-sha2-nistp521-cert-v01@openssh.com", 399 | "sk-ssh-ed25519-cert-v01@openssh.com", 400 | "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", 401 | "rsa-sha2-512-cert-v01@openssh.com", 402 | "rsa-sha2-256-cert-v01@openssh.com", 403 | "ssh-ed25519", 404 | "ecdsa-sha2-nistp256", 405 | "ecdsa-sha2-nistp384", 406 | "ecdsa-sha2-nistp521", 407 | "sk-ssh-ed25519@openssh.com", 408 | "sk-ecdsa-sha2-nistp256@openssh.com", 409 | "rsa-sha2-512", 410 | "rsa-sha2-256", 411 | ``` 412 | 413 | If you want you can use a custom constructor `SshConfig::default().default_algorithms(prefs)` to set your own default algorithms. 414 | 415 | --- 416 | 417 | ### Examples 418 | 419 | You can view a working examples of an implementation of ssh2-config with ssh2 in the examples folder at [client.rs](examples/client.rs). 420 | 421 | You can run the example with 422 | 423 | ```sh 424 | cargo run --example client -- [config-file-path] 425 | ``` 426 | 427 | --- 428 | 429 | ## Support the developer ☕ 430 | 431 | If you like ssh2-config and you're grateful for the work I've done, please consider a little donation 🥳 432 | 433 | You can make a donation with one of these platforms: 434 | 435 | [![ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/veeso) 436 | [![PayPal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/chrisintin) 437 | 438 | --- 439 | 440 | ## Contributing and issues 🤝🏻 441 | 442 | Contributions, bug reports, new features and questions are welcome! 😉 443 | If you have any question or concern, or you want to suggest a new feature, or you want just want to improve ssh2-config, feel free to open an issue or a PR. 444 | 445 | Please follow [our contributing guidelines](CONTRIBUTING.md) 446 | 447 | --- 448 | 449 | ## Changelog ⏳ 450 | 451 | View ssh2-config's changelog [HERE](CHANGELOG.md) 452 | 453 | --- 454 | 455 | ## License 📃 456 | 457 | ssh2-config is licensed under the MIT license. 458 | 459 | You can read the entire license [HERE](LICENSE) 460 | -------------------------------------------------------------------------------- /assets/ssh.config: -------------------------------------------------------------------------------- 1 | # ssh config example 2 | 3 | # Command line options, overriding host-specific options 4 | Compression yes 5 | ConnectionAttempts 10 6 | ConnectTimeout 60 7 | ServerAliveInterval 40 8 | TcpKeepAlive yes 9 | 10 | # Host configuration 11 | 12 | Host 192.168.*.* 172.26.*.* !192.168.1.30 13 | User omar 14 | ForwardAgent yes 15 | BindAddress 10.8.0.10 16 | BindInterface tun0 17 | Ciphers +aes128-cbc,aes192-cbc,aes256-cbc 18 | Macs +hmac-sha1-etm@openssh.com 19 | 20 | Host tostapane 21 | User ciro-esposito 22 | HostName 192.168.24.32 23 | RemoteForward 88 24 | Compression no 25 | Port 2222 26 | 27 | Host 192.168.1.30 28 | User nutellaro 29 | RemoteForward 123 30 | 31 | Host * 32 | Ciphers aes128-ctr,aes192-ctr,aes256-ctr 33 | KexAlgorithms diffie-hellman-group-exchange-sha256 34 | MACs hmac-sha2-512,hmac-sha2-256,hmac-ripemd160 35 | -------------------------------------------------------------------------------- /build/define_parser.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::io::BufRead; 3 | 4 | struct Scope { 5 | name: String, 6 | tokens: Vec, 7 | } 8 | 9 | pub fn parse_defines(reader: impl BufRead) -> anyhow::Result> { 10 | let mut defines = HashMap::new(); 11 | 12 | // iterate over each line in the reader 13 | let mut scope: Option = None; 14 | 15 | for line in reader.lines() { 16 | let line = line?; 17 | // check if the line is a define 18 | if line.trim().starts_with("#define") { 19 | if let Some(prev_scope) = scope.take() { 20 | // if we have a previous scope, store it 21 | defines.insert(prev_scope.name, prev_scope.tokens.join(" ")); 22 | } 23 | // start a new scope 24 | let mut tokens = line.split_whitespace(); 25 | let name = tokens 26 | .nth(1) 27 | .ok_or_else(|| anyhow::anyhow!("Expected a name after #define"))? 28 | .to_string(); 29 | 30 | let mut tokens = tokens.collect::>(); 31 | let mut single_line = true; 32 | 33 | // if last token is a \; remove it 34 | if let Some(last) = tokens.last() { 35 | if *last == "\\" { 36 | tokens.pop(); 37 | single_line = false; 38 | } 39 | } 40 | 41 | // get tokens after the name 42 | let mut parsed_tokens: Vec = vec![]; 43 | for token in tokens { 44 | let parsed = parse_token(&defines, token, false)?; 45 | parsed_tokens.extend(parsed); 46 | } 47 | 48 | scope = Some(Scope { 49 | name, 50 | tokens: parsed_tokens, 51 | }); 52 | 53 | // if is single line, push to defines and set scope to None 54 | if single_line { 55 | if let Some(scope) = scope.take() { 56 | defines.insert(scope.name, scope.tokens.join(" ")); 57 | } 58 | } 59 | } else { 60 | // if we are in a scope, add the line to the tokens 61 | let Some(inner_scope) = scope.as_mut() else { 62 | continue; 63 | }; 64 | 65 | let tokens = line.split_whitespace(); 66 | let mut tokens: Vec = tokens.map(|s| s.to_string()).collect(); 67 | 68 | // check if it ends with a \, if so, remove it 69 | let mut last_line = true; 70 | if let Some(last) = tokens.last() { 71 | if last == "\\" { 72 | tokens.pop(); 73 | last_line = false; 74 | } 75 | } 76 | 77 | // parse tokens 78 | for token in tokens { 79 | let parsed = parse_token(&defines, &token, false)?; 80 | inner_scope.tokens.extend(parsed); 81 | } 82 | 83 | // if last line, push to defines and set scope to None 84 | if last_line { 85 | if let Some(scope) = scope.take() { 86 | defines.insert(scope.name, scope.tokens.join(" ")); 87 | } 88 | } 89 | } 90 | } 91 | 92 | // put last scope 93 | if let Some(scope) = scope { 94 | defines.insert(scope.name, scope.tokens.join(" ")); 95 | } 96 | 97 | Ok(defines) 98 | } 99 | 100 | /// Parse token 101 | fn parse_token( 102 | defines: &HashMap, 103 | token: &str, 104 | nested: bool, 105 | ) -> anyhow::Result> { 106 | let token = token.trim().trim_end_matches(','); 107 | 108 | // if token is a define, parse it 109 | if let Some(value) = defines.get(token) { 110 | return parse_token(defines, value, true); 111 | } 112 | 113 | // otherwise, check if it is a string 114 | if token.starts_with('"') && token.ends_with('"') { 115 | return Ok(vec![ 116 | token[1..token.len() - 1].trim_end_matches(',').to_string(), 117 | ]); 118 | } 119 | 120 | // check if it is a number 121 | if token.parse::().is_ok() { 122 | return Ok(vec![token.to_string()]); 123 | } 124 | 125 | if nested { 126 | return Ok(vec![token.to_string()]); 127 | } 128 | 129 | anyhow::bail!("Unknown token: {token}; defines: {defines:#?}",) 130 | } 131 | -------------------------------------------------------------------------------- /build/main.rs: -------------------------------------------------------------------------------- 1 | mod define_parser; 2 | mod openssh; 3 | mod src_writer; 4 | 5 | fn main() -> anyhow::Result<()> { 6 | // If reload SSH ALGO is not set, we don't need to do anything 7 | if std::env::var("RELOAD_SSH_ALGO").is_err() { 8 | return Ok(()); 9 | } 10 | 11 | let prefs = openssh::get_my_prefs()?; 12 | src_writer::write_source(prefs)?; 13 | 14 | Ok(()) 15 | } 16 | -------------------------------------------------------------------------------- /build/openssh.rs: -------------------------------------------------------------------------------- 1 | use std::path::{Path, PathBuf}; 2 | 3 | use crate::define_parser::parse_defines; 4 | 5 | const OPENSSH_TAG: &str = "V_9_9_P2"; 6 | 7 | /// Default algorithms for ssh. 8 | #[derive(Debug, Default, Clone, PartialEq, Eq)] 9 | pub struct MyPrefs { 10 | pub ca_signature_algorithms: Vec, 11 | pub ciphers: Vec, 12 | pub host_key_algorithms: Vec, 13 | pub kex_algorithms: Vec, 14 | pub mac: Vec, 15 | pub pubkey_accepted_algorithms: Vec, 16 | } 17 | 18 | pub fn get_my_prefs() -> anyhow::Result { 19 | let out_dir = std::env::var_os("OUT_DIR") 20 | .map(|s| PathBuf::from(s).join("openssh")) 21 | .ok_or_else(|| anyhow::anyhow!("OUT_DIR not set"))?; 22 | let build_dir = out_dir.join("build"); 23 | let inner_dir = build_dir.join("src"); 24 | 25 | std::fs::remove_dir_all(&build_dir).ok(); 26 | std::fs::create_dir_all(&inner_dir).ok(); 27 | 28 | clone_openssh(&inner_dir)?; 29 | 30 | let my_proposal_path = inner_dir.join("myproposal.h"); 31 | 32 | let reader = std::io::BufReader::new(std::fs::File::open(my_proposal_path)?); 33 | let defines = parse_defines(reader)?; 34 | 35 | let ca_signature_algorithms = defines 36 | .get("SSH_ALLOWED_CA_SIGALGS") 37 | .map(|s| s.split_whitespace().map(|s| format!(r#""{s}""#)).collect()) 38 | .unwrap_or_default(); 39 | 40 | let ciphers = defines 41 | .get("KEX_CLIENT_ENCRYPT") 42 | .map(|s| s.split_whitespace().map(|s| format!(r#""{s}""#)).collect()) 43 | .unwrap_or_default(); 44 | 45 | let host_key_algorithms = defines 46 | .get("KEX_DEFAULT_PK_ALG") 47 | .map(|s| s.split_whitespace().map(|s| format!(r#""{s}""#)).collect()) 48 | .unwrap_or_default(); 49 | 50 | let kex_algorithms = defines 51 | .get("KEX_CLIENT") 52 | .map(|s| s.split_whitespace().map(|s| format!(r#""{s}""#)).collect()) 53 | .unwrap_or_default(); 54 | 55 | let mac = defines 56 | .get("KEX_CLIENT_MAC") 57 | .map(|s| s.split_whitespace().map(|s| format!(r#""{s}""#)).collect()) 58 | .unwrap_or_default(); 59 | 60 | let pubkey_accepted_algorithms = defines 61 | .get("KEX_DEFAULT_PK_ALG") 62 | .map(|s| s.split_whitespace().map(|s| format!(r#""{s}""#)).collect()) 63 | .unwrap_or_default(); 64 | 65 | Ok(MyPrefs { 66 | ca_signature_algorithms, 67 | ciphers, 68 | host_key_algorithms, 69 | kex_algorithms, 70 | mac, 71 | pubkey_accepted_algorithms, 72 | }) 73 | } 74 | 75 | fn clone_openssh(path: &Path) -> anyhow::Result<()> { 76 | let repo_url = "https://github.com/openssh/openssh-portable.git"; 77 | let repo = git2::Repository::clone(repo_url, path)?; 78 | 79 | let obj = repo.revparse_single(OPENSSH_TAG)?; 80 | 81 | let commit = obj.peel_to_commit()?; 82 | 83 | repo.checkout_tree(&obj, None)?; 84 | 85 | repo.set_head_detached(commit.id())?; 86 | 87 | Ok(()) 88 | } 89 | -------------------------------------------------------------------------------- /build/src_writer.rs: -------------------------------------------------------------------------------- 1 | use std::io::Write as _; 2 | use std::path::PathBuf; 3 | 4 | use crate::openssh::MyPrefs; 5 | 6 | pub fn write_source(prefs: MyPrefs) -> anyhow::Result<()> { 7 | let SrcPaths { src_dir, src_path } = src_path(); 8 | 9 | // create dir 10 | if !src_dir.exists() { 11 | std::fs::create_dir_all(&src_dir)?; 12 | } 13 | 14 | // open file 15 | let mut file = std::fs::File::create(src_path)?; 16 | 17 | writeln!( 18 | file, 19 | r#"//! This file is autogenerated at build-time when `RELOAD_SSH_ALGO` is set to environment."# 20 | )?; 21 | writeln!(file)?; 22 | 23 | writeln!(file, "use crate::DefaultAlgorithms;")?; 24 | writeln!(file,)?; 25 | 26 | writeln!(file, r#"/// Default algorithms for ssh."#)?; 27 | writeln!(file, r#"pub fn defaults() -> DefaultAlgorithms {{"#)?; 28 | writeln!(file, r#" DefaultAlgorithms {{"#)?; 29 | write_vec( 30 | &mut file, 31 | "ca_signature_algorithms", 32 | &prefs.ca_signature_algorithms, 33 | )?; 34 | write_vec(&mut file, "ciphers", &prefs.ciphers)?; 35 | write_vec(&mut file, "host_key_algorithms", &prefs.host_key_algorithms)?; 36 | write_vec(&mut file, "kex_algorithms", &prefs.kex_algorithms)?; 37 | write_vec(&mut file, "mac", &prefs.mac)?; 38 | write_vec( 39 | &mut file, 40 | "pubkey_accepted_algorithms", 41 | &prefs.pubkey_accepted_algorithms, 42 | )?; 43 | writeln!(file, r#" }}"#)?; 44 | writeln!(file, r#"}}"#)?; 45 | 46 | Ok(()) 47 | } 48 | 49 | fn write_vec(file: &mut std::fs::File, name: &str, vec: &[String]) -> anyhow::Result<()> { 50 | writeln!(file, r#" {name}: vec!["#)?; 51 | for item in vec { 52 | writeln!(file, r#" {item}.to_string(),"#,)?; 53 | } 54 | writeln!(file, r#" ],"#)?; 55 | Ok(()) 56 | } 57 | 58 | struct SrcPaths { 59 | src_dir: PathBuf, 60 | src_path: PathBuf, 61 | } 62 | 63 | fn src_path() -> SrcPaths { 64 | let src_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) 65 | .join("src") 66 | .join("default_algorithms"); 67 | let src_path = src_dir.join("openssh.rs"); 68 | 69 | SrcPaths { src_dir, src_path } 70 | } 71 | -------------------------------------------------------------------------------- /examples/client.rs: -------------------------------------------------------------------------------- 1 | //! # client 2 | //! 3 | //! Ssh2-config implementation with a ssh2 client 4 | 5 | use std::env::args; 6 | use std::fs::File; 7 | use std::io::BufReader; 8 | use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; 9 | use std::path::{Path, PathBuf}; 10 | use std::process::exit; 11 | use std::time::Duration; 12 | 13 | use dirs::home_dir; 14 | use ssh2::{MethodType, Session}; 15 | use ssh2_config::{HostParams, ParseRule, SshConfig}; 16 | 17 | fn main() { 18 | // get args 19 | let args: Vec = args().collect(); 20 | let address = match args.get(1) { 21 | Some(addr) => addr.to_string(), 22 | None => { 23 | usage(); 24 | exit(255) 25 | } 26 | }; 27 | // check path 28 | let config_path = match args.get(2) { 29 | Some(p) => PathBuf::from(p), 30 | None => { 31 | let mut p = home_dir().expect("Failed to get home_dir for guest OS"); 32 | p.extend(Path::new(".ssh/config")); 33 | p 34 | } 35 | }; 36 | // Open config file 37 | let config = read_config(config_path.as_path()); 38 | let params = config.query(address.as_str()); 39 | connect(address.as_str(), ¶ms); 40 | } 41 | 42 | fn usage() { 43 | eprintln!("Usage: cargo run --example client -- [config-path]"); 44 | } 45 | 46 | fn read_config(p: &Path) -> SshConfig { 47 | let mut reader = match File::open(p) { 48 | Ok(f) => BufReader::new(f), 49 | Err(err) => panic!("Could not open file '{}': {}", p.display(), err), 50 | }; 51 | match SshConfig::default().parse(&mut reader, ParseRule::STRICT) { 52 | Ok(config) => config, 53 | Err(err) => panic!("Failed to parse configuration: {}", err), 54 | } 55 | } 56 | 57 | fn connect(host: &str, params: &HostParams) { 58 | // Resolve host 59 | let host = match params.host_name.as_deref() { 60 | Some(h) => h, 61 | None => host, 62 | }; 63 | let port = params.port.unwrap_or(22); 64 | let host = match host.contains(':') { 65 | true => host.to_string(), 66 | false => format!("{}:{}", host, port), 67 | }; 68 | println!("Connecting to host {}...", host); 69 | let socket_addresses: Vec = match host.to_socket_addrs() { 70 | Ok(s) => s.collect(), 71 | Err(err) => { 72 | panic!("Could not parse host: {}", err); 73 | } 74 | }; 75 | let mut tcp: Option = None; 76 | // Try addresses 77 | for socket_addr in socket_addresses.iter() { 78 | match TcpStream::connect_timeout( 79 | socket_addr, 80 | params.connect_timeout.unwrap_or(Duration::from_secs(30)), 81 | ) { 82 | Ok(stream) => { 83 | println!("Established connection with {}", socket_addr); 84 | tcp = Some(stream); 85 | break; 86 | } 87 | Err(_) => continue, 88 | } 89 | } 90 | // If stream is None, return connection timeout 91 | let stream: TcpStream = match tcp { 92 | Some(t) => t, 93 | None => { 94 | panic!("No suitable socket address found; connection timeout"); 95 | } 96 | }; 97 | let mut session: Session = match Session::new() { 98 | Ok(s) => s, 99 | Err(err) => { 100 | panic!("Could not create session: {}", err); 101 | } 102 | }; 103 | // Configure session 104 | configure_session(&mut session, params); 105 | // Connect 106 | session.set_tcp_stream(stream); 107 | if let Err(err) = session.handshake() { 108 | panic!("Handshake failed: {}", err); 109 | } 110 | // Get username 111 | let username = match params.user.as_ref() { 112 | Some(u) => { 113 | println!("Using username '{}'", u); 114 | u.clone() 115 | } 116 | None => read_secret("Username: "), 117 | }; 118 | let password = read_secret("Password: "); 119 | if let Err(err) = session.userauth_password(username.as_str(), password.as_str()) { 120 | panic!("Authentication failed: {}", err); 121 | } 122 | if let Some(banner) = session.banner() { 123 | println!("{}", banner); 124 | } 125 | println!("Connection OK!"); 126 | if let Err(err) = session.disconnect(None, "mandi mandi!", None) { 127 | panic!("Disconnection failed: {}", err); 128 | } 129 | } 130 | 131 | fn configure_session(session: &mut Session, params: &HostParams) { 132 | println!("Configuring session..."); 133 | if let Some(compress) = params.compression { 134 | println!("compression: {}", compress); 135 | session.set_compress(compress); 136 | } 137 | if params.tcp_keep_alive.unwrap_or(false) && params.server_alive_interval.is_some() { 138 | let interval = params.server_alive_interval.unwrap().as_secs() as u32; 139 | println!("keepalive interval: {} seconds", interval); 140 | session.set_keepalive(true, interval); 141 | } 142 | 143 | // KEX 144 | if let Err(err) = session.method_pref( 145 | MethodType::Kex, 146 | params.kex_algorithms.algorithms().join(",").as_str(), 147 | ) { 148 | panic!("Could not set KEX algorithms: {}", err); 149 | } 150 | 151 | // host key 152 | if let Err(err) = session.method_pref( 153 | MethodType::HostKey, 154 | params.host_key_algorithms.algorithms().join(",").as_str(), 155 | ) { 156 | panic!("Could not set host key algorithms: {}", err); 157 | } 158 | 159 | // ciphers 160 | if let Err(err) = session.method_pref( 161 | MethodType::CryptCs, 162 | params.ciphers.algorithms().join(",").as_str(), 163 | ) { 164 | panic!("Could not set crypt algorithms (client-server): {}", err); 165 | } 166 | if let Err(err) = session.method_pref( 167 | MethodType::CryptSc, 168 | params.ciphers.algorithms().join(",").as_str(), 169 | ) { 170 | panic!("Could not set crypt algorithms (server-client): {}", err); 171 | } 172 | 173 | // mac 174 | if let Err(err) = session.method_pref( 175 | MethodType::MacCs, 176 | params.mac.algorithms().join(",").as_str(), 177 | ) { 178 | panic!("Could not set MAC algorithms (client-server): {}", err); 179 | } 180 | if let Err(err) = session.method_pref( 181 | MethodType::MacSc, 182 | params.mac.algorithms().join(",").as_str(), 183 | ) { 184 | panic!("Could not set MAC algorithms (server-client): {}", err); 185 | } 186 | } 187 | 188 | fn read_secret(prompt: &str) -> String { 189 | rpassword::prompt_password(prompt).expect("Failed to read from stdin") 190 | } 191 | -------------------------------------------------------------------------------- /examples/print.rs: -------------------------------------------------------------------------------- 1 | use std::env::args; 2 | use std::fs::File; 3 | use std::io::BufReader; 4 | use std::path::{Path, PathBuf}; 5 | 6 | use dirs::home_dir; 7 | use ssh2_config::{ParseRule, SshConfig}; 8 | 9 | fn main() { 10 | // get args 11 | let args: Vec = args().collect(); 12 | // check path 13 | let config_path = match args.get(1) { 14 | Some(p) => PathBuf::from(p), 15 | None => { 16 | let mut p = home_dir().expect("Failed to get home_dir for guest OS"); 17 | p.extend(Path::new(".ssh/config")); 18 | p 19 | } 20 | }; 21 | // Open config file 22 | let config = read_config(config_path.as_path()); 23 | 24 | println!("{config}"); 25 | } 26 | 27 | fn read_config(p: &Path) -> SshConfig { 28 | let mut reader = match File::open(p) { 29 | Ok(f) => BufReader::new(f), 30 | Err(err) => panic!("Could not open file '{}': {}", p.display(), err), 31 | }; 32 | match SshConfig::default().parse(&mut reader, ParseRule::STRICT) { 33 | Ok(config) => config, 34 | Err(err) => panic!("Failed to parse configuration: {}", err), 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /examples/query.rs: -------------------------------------------------------------------------------- 1 | use std::env::args; 2 | use std::fs::File; 3 | use std::io::BufReader; 4 | use std::path::{Path, PathBuf}; 5 | use std::process::exit; 6 | 7 | use dirs::home_dir; 8 | use ssh2_config::{ParseRule, SshConfig}; 9 | 10 | fn main() { 11 | // get args 12 | let args: Vec = args().collect(); 13 | let address = match args.get(1) { 14 | Some(addr) => addr.to_string(), 15 | None => { 16 | usage(); 17 | exit(255) 18 | } 19 | }; 20 | // check path 21 | let config_path = match args.get(2) { 22 | Some(p) => PathBuf::from(p), 23 | None => { 24 | let mut p = home_dir().expect("Failed to get home_dir for guest OS"); 25 | p.extend(Path::new(".ssh/config")); 26 | p 27 | } 28 | }; 29 | // Open config file 30 | let config = read_config(config_path.as_path()); 31 | let params = config.query(address.as_str()); 32 | println!("Configuration for {}: {:?}", address, params); 33 | } 34 | 35 | fn usage() { 36 | eprintln!("Usage: cargo run --example query --
[config-path]"); 37 | } 38 | 39 | fn read_config(p: &Path) -> SshConfig { 40 | let mut reader = match File::open(p) { 41 | Ok(f) => BufReader::new(f), 42 | Err(err) => panic!("Could not open file '{}': {}", p.display(), err), 43 | }; 44 | match SshConfig::default().parse(&mut reader, ParseRule::STRICT) { 45 | Ok(config) => config, 46 | Err(err) => panic!("Failed to parse configuration: {}", err), 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | group_imports = "StdExternalCrate" 2 | imports_granularity = "Module" -------------------------------------------------------------------------------- /src/default_algorithms.rs: -------------------------------------------------------------------------------- 1 | mod openssh; 2 | 3 | /// Default algorithms for ssh. 4 | #[derive(Debug, Clone, PartialEq, Eq)] 5 | pub struct DefaultAlgorithms { 6 | pub ca_signature_algorithms: Vec, 7 | pub ciphers: Vec, 8 | pub host_key_algorithms: Vec, 9 | pub kex_algorithms: Vec, 10 | pub mac: Vec, 11 | pub pubkey_accepted_algorithms: Vec, 12 | } 13 | 14 | impl Default for DefaultAlgorithms { 15 | fn default() -> Self { 16 | self::openssh::defaults() 17 | } 18 | } 19 | 20 | impl DefaultAlgorithms { 21 | /// Create a new instance of [`DefaultAlgorithms`] with empty fields. 22 | pub fn empty() -> Self { 23 | Self { 24 | ca_signature_algorithms: vec![], 25 | ciphers: vec![], 26 | host_key_algorithms: vec![], 27 | kex_algorithms: vec![], 28 | mac: vec![], 29 | pubkey_accepted_algorithms: vec![], 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/default_algorithms/openssh.rs: -------------------------------------------------------------------------------- 1 | //! This file is autogenerated at build-time when `RELOAD_SSH_ALGO` is set to environment. 2 | 3 | use crate::DefaultAlgorithms; 4 | 5 | /// Default algorithms for ssh. 6 | pub fn defaults() -> DefaultAlgorithms { 7 | DefaultAlgorithms { 8 | ca_signature_algorithms: vec![ 9 | "ssh-ed25519".to_string(), 10 | "ecdsa-sha2-nistp256".to_string(), 11 | "ecdsa-sha2-nistp384".to_string(), 12 | "ecdsa-sha2-nistp521".to_string(), 13 | "sk-ssh-ed25519@openssh.com".to_string(), 14 | "sk-ecdsa-sha2-nistp256@openssh.com".to_string(), 15 | "rsa-sha2-512".to_string(), 16 | "rsa-sha2-256".to_string(), 17 | ], 18 | ciphers: vec![ 19 | "chacha20-poly1305@openssh.com".to_string(), 20 | "aes128-ctr,aes192-ctr,aes256-ctr".to_string(), 21 | "aes128-gcm@openssh.com,aes256-gcm@openssh.com".to_string(), 22 | ], 23 | host_key_algorithms: vec![ 24 | "ssh-ed25519-cert-v01@openssh.com".to_string(), 25 | "ecdsa-sha2-nistp256-cert-v01@openssh.com".to_string(), 26 | "ecdsa-sha2-nistp384-cert-v01@openssh.com".to_string(), 27 | "ecdsa-sha2-nistp521-cert-v01@openssh.com".to_string(), 28 | "sk-ssh-ed25519-cert-v01@openssh.com".to_string(), 29 | "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com".to_string(), 30 | "rsa-sha2-512-cert-v01@openssh.com".to_string(), 31 | "rsa-sha2-256-cert-v01@openssh.com".to_string(), 32 | "ssh-ed25519".to_string(), 33 | "ecdsa-sha2-nistp256".to_string(), 34 | "ecdsa-sha2-nistp384".to_string(), 35 | "ecdsa-sha2-nistp521".to_string(), 36 | "sk-ssh-ed25519@openssh.com".to_string(), 37 | "sk-ecdsa-sha2-nistp256@openssh.com".to_string(), 38 | "rsa-sha2-512".to_string(), 39 | "rsa-sha2-256".to_string(), 40 | ], 41 | kex_algorithms: vec![ 42 | "sntrup761x25519-sha512".to_string(), 43 | "sntrup761x25519-sha512@openssh.com".to_string(), 44 | "mlkem768x25519-sha256".to_string(), 45 | "curve25519-sha256".to_string(), 46 | "curve25519-sha256@libssh.org".to_string(), 47 | "ecdh-sha2-nistp256".to_string(), 48 | "ecdh-sha2-nistp384".to_string(), 49 | "ecdh-sha2-nistp521".to_string(), 50 | "diffie-hellman-group-exchange-sha256".to_string(), 51 | "diffie-hellman-group16-sha512".to_string(), 52 | "diffie-hellman-group18-sha512".to_string(), 53 | "diffie-hellman-group14-sha256".to_string(), 54 | "ssh-ed25519-cert-v01@openssh.com".to_string(), 55 | "ecdsa-sha2-nistp256-cert-v01@openssh.com".to_string(), 56 | "ecdsa-sha2-nistp384-cert-v01@openssh.com".to_string(), 57 | "ecdsa-sha2-nistp521-cert-v01@openssh.com".to_string(), 58 | "sk-ssh-ed25519-cert-v01@openssh.com".to_string(), 59 | "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com".to_string(), 60 | "rsa-sha2-512-cert-v01@openssh.com".to_string(), 61 | "rsa-sha2-256-cert-v01@openssh.com".to_string(), 62 | "ssh-ed25519".to_string(), 63 | "ecdsa-sha2-nistp256".to_string(), 64 | "ecdsa-sha2-nistp384".to_string(), 65 | "ecdsa-sha2-nistp521".to_string(), 66 | "sk-ssh-ed25519@openssh.com".to_string(), 67 | "sk-ecdsa-sha2-nistp256@openssh.com".to_string(), 68 | "rsa-sha2-512".to_string(), 69 | "rsa-sha2-256".to_string(), 70 | "chacha20-poly1305@openssh.com".to_string(), 71 | "aes128-ctr,aes192-ctr,aes256-ctr".to_string(), 72 | "aes128-gcm@openssh.com,aes256-gcm@openssh.com".to_string(), 73 | "chacha20-poly1305@openssh.com".to_string(), 74 | "aes128-ctr,aes192-ctr,aes256-ctr".to_string(), 75 | "aes128-gcm@openssh.com,aes256-gcm@openssh.com".to_string(), 76 | "umac-64-etm@openssh.com".to_string(), 77 | "umac-128-etm@openssh.com".to_string(), 78 | "hmac-sha2-256-etm@openssh.com".to_string(), 79 | "hmac-sha2-512-etm@openssh.com".to_string(), 80 | "hmac-sha1-etm@openssh.com".to_string(), 81 | "umac-64@openssh.com".to_string(), 82 | "umac-128@openssh.com".to_string(), 83 | "hmac-sha2-256".to_string(), 84 | "hmac-sha2-512".to_string(), 85 | "hmac-sha1".to_string(), 86 | "umac-64-etm@openssh.com".to_string(), 87 | "umac-128-etm@openssh.com".to_string(), 88 | "hmac-sha2-256-etm@openssh.com".to_string(), 89 | "hmac-sha2-512-etm@openssh.com".to_string(), 90 | "hmac-sha1-etm@openssh.com".to_string(), 91 | "umac-64@openssh.com".to_string(), 92 | "umac-128@openssh.com".to_string(), 93 | "hmac-sha2-256".to_string(), 94 | "hmac-sha2-512".to_string(), 95 | "hmac-sha1".to_string(), 96 | "none,zlib@openssh.com".to_string(), 97 | "none,zlib@openssh.com".to_string(), 98 | ], 99 | mac: vec![ 100 | "umac-64-etm@openssh.com".to_string(), 101 | "umac-128-etm@openssh.com".to_string(), 102 | "hmac-sha2-256-etm@openssh.com".to_string(), 103 | "hmac-sha2-512-etm@openssh.com".to_string(), 104 | "hmac-sha1-etm@openssh.com".to_string(), 105 | "umac-64@openssh.com".to_string(), 106 | "umac-128@openssh.com".to_string(), 107 | "hmac-sha2-256".to_string(), 108 | "hmac-sha2-512".to_string(), 109 | "hmac-sha1".to_string(), 110 | ], 111 | pubkey_accepted_algorithms: vec![ 112 | "ssh-ed25519-cert-v01@openssh.com".to_string(), 113 | "ecdsa-sha2-nistp256-cert-v01@openssh.com".to_string(), 114 | "ecdsa-sha2-nistp384-cert-v01@openssh.com".to_string(), 115 | "ecdsa-sha2-nistp521-cert-v01@openssh.com".to_string(), 116 | "sk-ssh-ed25519-cert-v01@openssh.com".to_string(), 117 | "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com".to_string(), 118 | "rsa-sha2-512-cert-v01@openssh.com".to_string(), 119 | "rsa-sha2-256-cert-v01@openssh.com".to_string(), 120 | "ssh-ed25519".to_string(), 121 | "ecdsa-sha2-nistp256".to_string(), 122 | "ecdsa-sha2-nistp384".to_string(), 123 | "ecdsa-sha2-nistp521".to_string(), 124 | "sk-ssh-ed25519@openssh.com".to_string(), 125 | "sk-ecdsa-sha2-nistp256@openssh.com".to_string(), 126 | "rsa-sha2-512".to_string(), 127 | "rsa-sha2-256".to_string(), 128 | ], 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/host.rs: -------------------------------------------------------------------------------- 1 | //! # host 2 | //! 3 | //! Ssh host type 4 | 5 | use std::fmt; 6 | 7 | use wildmatch::WildMatch; 8 | 9 | use super::HostParams; 10 | 11 | /// Describes the rules to be used for a certain host 12 | #[derive(Debug, Clone, PartialEq, Eq)] 13 | pub struct Host { 14 | /// List of hosts for which params are valid. String is string pattern, bool is whether condition is negated 15 | pub pattern: Vec, 16 | pub params: HostParams, 17 | } 18 | 19 | impl Host { 20 | pub fn new(pattern: Vec, params: HostParams) -> Self { 21 | Self { pattern, params } 22 | } 23 | 24 | /// Returns whether `host` argument intersects the host clauses 25 | pub fn intersects(&self, host: &str) -> bool { 26 | let mut has_matched = false; 27 | for entry in self.pattern.iter() { 28 | let matches = entry.intersects(host); 29 | // If the entry is negated and it matches we can stop searching 30 | if matches && entry.negated { 31 | return false; 32 | } 33 | has_matched |= matches; 34 | } 35 | has_matched 36 | } 37 | } 38 | 39 | /// Describes a single clause to match host 40 | #[derive(Debug, Clone, PartialEq, Eq)] 41 | pub struct HostClause { 42 | pub pattern: String, 43 | pub negated: bool, 44 | } 45 | 46 | impl fmt::Display for HostClause { 47 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 48 | if self.negated { 49 | write!(f, "!{}", self.pattern) 50 | } else { 51 | write!(f, "{}", self.pattern) 52 | } 53 | } 54 | } 55 | 56 | impl HostClause { 57 | /// Creates a new `HostClause` from arguments 58 | pub fn new(pattern: String, negated: bool) -> Self { 59 | Self { pattern, negated } 60 | } 61 | 62 | /// Returns whether `host` argument intersects the clause 63 | pub fn intersects(&self, host: &str) -> bool { 64 | WildMatch::new(self.pattern.as_str()).matches(host) 65 | } 66 | } 67 | 68 | #[cfg(test)] 69 | mod test { 70 | 71 | use pretty_assertions::assert_eq; 72 | 73 | use super::*; 74 | use crate::DefaultAlgorithms; 75 | 76 | #[test] 77 | fn should_build_host_clause() { 78 | let clause = HostClause::new("192.168.1.1".to_string(), false); 79 | assert_eq!(clause.pattern.as_str(), "192.168.1.1"); 80 | assert_eq!(clause.negated, false); 81 | } 82 | 83 | #[test] 84 | fn should_intersect_host_clause() { 85 | let clause = HostClause::new("192.168.*.*".to_string(), false); 86 | assert!(clause.intersects("192.168.2.30")); 87 | let clause = HostClause::new("192.168.?0.*".to_string(), false); 88 | assert!(clause.intersects("192.168.40.28")); 89 | } 90 | 91 | #[test] 92 | fn should_not_intersect_host_clause() { 93 | let clause = HostClause::new("192.168.*.*".to_string(), false); 94 | assert_eq!(clause.intersects("172.26.104.4"), false); 95 | } 96 | 97 | #[test] 98 | fn should_init_host() { 99 | let host = Host::new( 100 | vec![HostClause::new("192.168.*.*".to_string(), false)], 101 | HostParams::new(&DefaultAlgorithms::default()), 102 | ); 103 | assert_eq!(host.pattern.len(), 1); 104 | } 105 | 106 | #[test] 107 | fn should_intersect_clause() { 108 | let host = Host::new( 109 | vec![ 110 | HostClause::new("192.168.*.*".to_string(), false), 111 | HostClause::new("172.26.*.*".to_string(), false), 112 | HostClause::new("10.8.*.*".to_string(), false), 113 | HostClause::new("10.8.0.8".to_string(), true), 114 | ], 115 | HostParams::new(&DefaultAlgorithms::default()), 116 | ); 117 | assert!(host.intersects("192.168.1.32")); 118 | assert!(host.intersects("172.26.104.4")); 119 | assert!(host.intersects("10.8.0.10")); 120 | } 121 | 122 | #[test] 123 | fn should_not_intersect_clause() { 124 | let host = Host::new( 125 | vec![ 126 | HostClause::new("192.168.*.*".to_string(), false), 127 | HostClause::new("172.26.*.*".to_string(), false), 128 | HostClause::new("10.8.*.*".to_string(), false), 129 | HostClause::new("10.8.0.8".to_string(), true), 130 | ], 131 | HostParams::new(&DefaultAlgorithms::default()), 132 | ); 133 | assert_eq!(host.intersects("192.169.1.32"), false); 134 | assert_eq!(host.intersects("172.28.104.4"), false); 135 | assert_eq!(host.intersects("10.9.0.8"), false); 136 | assert_eq!(host.intersects("10.8.0.8"), false); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![crate_name = "ssh2_config"] 2 | #![crate_type = "lib"] 3 | 4 | //! # ssh2-config 5 | //! 6 | //! ssh2-config a library which provides a parser for the SSH configuration file, 7 | //! to be used in pair with the [ssh2](https://github.com/alexcrichton/ssh2-rs) crate. 8 | //! 9 | //! This library provides a method to parse the configuration file and returns the 10 | //! configuration parsed into a structure. 11 | //! The `SshConfig` structure provides all the attributes which **can** be used to configure the **ssh2 Session** 12 | //! and to resolve the host, port and username. 13 | //! 14 | //! Once the configuration has been parsed you can use the `query(&str)` 15 | //! method to query configuration for a certain host, based on the configured patterns. 16 | //! Even if many attributes are not exposed, since not supported, there is anyway a validation of the configuration, 17 | //! so invalid configuration will result in a parsing error. 18 | //! 19 | //! ## Get started 20 | //! 21 | //! First of you need to add **ssh2-config** to your project dependencies: 22 | //! 23 | //! ```toml 24 | //! ssh2-config = "^0.5" 25 | //! ``` 26 | //! 27 | //! ## Example 28 | //! 29 | //! Here is a basic example: 30 | //! 31 | //! ```rust 32 | //! 33 | //! use ssh2::Session; 34 | //! use ssh2_config::{HostParams, ParseRule, SshConfig}; 35 | //! use std::fs::File; 36 | //! use std::io::BufReader; 37 | //! use std::path::Path; 38 | //! 39 | //! let mut reader = BufReader::new( 40 | //! File::open(Path::new("./assets/ssh.config")) 41 | //! .expect("Could not open configuration file") 42 | //! ); 43 | //! 44 | //! let config = SshConfig::default().parse(&mut reader, ParseRule::STRICT).expect("Failed to parse configuration"); 45 | //! 46 | //! // Query parameters for your host 47 | //! // If there's no rule for your host, default params are returned 48 | //! let params = config.query("192.168.1.2"); 49 | //! 50 | //! // ... 51 | //! 52 | //! // serialize configuration to string 53 | //! let s = config.to_string(); 54 | //! 55 | //! ``` 56 | //! 57 | //! --- 58 | //! 59 | //! ## How host parameters are resolved 60 | //! 61 | //! This topic has been debated a lot over the years, so finally since 0.5 this has been fixed to follow the official ssh configuration file rules, as described in the MAN . 62 | //! 63 | //! > Unless noted otherwise, for each parameter, the first obtained value will be used. The configuration files contain sections separated by Host specifications, and that section is only applied for hosts that match one of the patterns given in the specification. The matched host name is usually the one given on the command line (see the CanonicalizeHostname option for exceptions). 64 | //! > 65 | //! > Since the first obtained value for each parameter is used, more host-specific declarations should be given near the beginning of the file, and general defaults at the end. 66 | //! 67 | //! This means that: 68 | //! 69 | //! 1. The first obtained value parsing the configuration top-down will be used 70 | //! 2. Host specific rules ARE not overriding default ones if they are not the first obtained value 71 | //! 3. If you want to achieve default values to be less specific than host specific ones, you should put the default values at the end of the configuration file using `Host *`. 72 | //! 4. Algorithms, so `KexAlgorithms`, `Ciphers`, `MACs` and `HostKeyAlgorithms` use a different resolvers which supports appending, excluding and heading insertions, as described in the man page at ciphers: . 73 | //! 74 | //! ### Resolvers examples 75 | //! 76 | //! ```ssh 77 | //! Compression yes 78 | //! 79 | //! Host 192.168.1.1 80 | //! Compression no 81 | //! ``` 82 | //! 83 | //! If we get rules for `192.168.1.1`, compression will be `yes`, because it's the first obtained value. 84 | //! 85 | //! ```ssh 86 | //! Host 192.168.1.1 87 | //! Compression no 88 | //! 89 | //! Host * 90 | //! Compression yes 91 | //! ``` 92 | //! 93 | //! If we get rules for `192.168.1.1`, compression will be `no`, because it's the first obtained value. 94 | //! 95 | //! If we get rules for `172.168.1.1`, compression will be `yes`, because it's the first obtained value MATCHING the host rule. 96 | //! 97 | //! ```ssh 98 | //! 99 | //! Host 192.168.1.1 100 | //! Ciphers +c 101 | //! ``` 102 | //! 103 | //! If we get rules for `192.168.1.1`, ciphers will be `c` appended to default algorithms, which can be specified in the [`SshConfig`] constructor. 104 | //! 105 | //! ## Configuring default algorithms 106 | //! 107 | //! When you invoke [`SshConfig::default`], the default algorithms are set from openssh source code, which are the following: 108 | //! 109 | //! ```txt 110 | //! ca_signature_algorithms: 111 | //! "ssh-ed25519", 112 | //! "ecdsa-sha2-nistp256", 113 | //! "ecdsa-sha2-nistp384", 114 | //! "ecdsa-sha2-nistp521", 115 | //! "sk-ssh-ed25519@openssh.com", 116 | //! "sk-ecdsa-sha2-nistp256@openssh.com", 117 | //! "rsa-sha2-512", 118 | //! "rsa-sha2-256", 119 | //! 120 | //! ciphers: 121 | //! "chacha20-poly1305@openssh.com", 122 | //! "aes128-ctr,aes192-ctr,aes256-ctr", 123 | //! "aes128-gcm@openssh.com,aes256-gcm@openssh.com", 124 | //! 125 | //! host_key_algorithms: 126 | //! "ssh-ed25519-cert-v01@openssh.com", 127 | //! "ecdsa-sha2-nistp256-cert-v01@openssh.com", 128 | //! "ecdsa-sha2-nistp384-cert-v01@openssh.com", 129 | //! "ecdsa-sha2-nistp521-cert-v01@openssh.com", 130 | //! "sk-ssh-ed25519-cert-v01@openssh.com", 131 | //! "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", 132 | //! "rsa-sha2-512-cert-v01@openssh.com", 133 | //! "rsa-sha2-256-cert-v01@openssh.com", 134 | //! "ssh-ed25519", 135 | //! "ecdsa-sha2-nistp256", 136 | //! "ecdsa-sha2-nistp384", 137 | //! "ecdsa-sha2-nistp521", 138 | //! "sk-ssh-ed25519@openssh.com", 139 | //! "sk-ecdsa-sha2-nistp256@openssh.com", 140 | //! "rsa-sha2-512", 141 | //! "rsa-sha2-256", 142 | //! 143 | //! kex_algorithms: 144 | //! "sntrup761x25519-sha512", 145 | //! "sntrup761x25519-sha512@openssh.com", 146 | //! "mlkem768x25519-sha256", 147 | //! "curve25519-sha256", 148 | //! "curve25519-sha256@libssh.org", 149 | //! "ecdh-sha2-nistp256", 150 | //! "ecdh-sha2-nistp384", 151 | //! "ecdh-sha2-nistp521", 152 | //! "diffie-hellman-group-exchange-sha256", 153 | //! "diffie-hellman-group16-sha512", 154 | //! "diffie-hellman-group18-sha512", 155 | //! "diffie-hellman-group14-sha256", 156 | //! "ssh-ed25519-cert-v01@openssh.com", 157 | //! "ecdsa-sha2-nistp256-cert-v01@openssh.com", 158 | //! "ecdsa-sha2-nistp384-cert-v01@openssh.com", 159 | //! "ecdsa-sha2-nistp521-cert-v01@openssh.com", 160 | //! "sk-ssh-ed25519-cert-v01@openssh.com", 161 | //! "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", 162 | //! "rsa-sha2-512-cert-v01@openssh.com", 163 | //! "rsa-sha2-256-cert-v01@openssh.com", 164 | //! "ssh-ed25519", 165 | //! "ecdsa-sha2-nistp256", 166 | //! "ecdsa-sha2-nistp384", 167 | //! "ecdsa-sha2-nistp521", 168 | //! "sk-ssh-ed25519@openssh.com", 169 | //! "sk-ecdsa-sha2-nistp256@openssh.com", 170 | //! "rsa-sha2-512", 171 | //! "rsa-sha2-256", 172 | //! "chacha20-poly1305@openssh.com", 173 | //! "aes128-ctr,aes192-ctr,aes256-ctr", 174 | //! "aes128-gcm@openssh.com,aes256-gcm@openssh.com", 175 | //! "chacha20-poly1305@openssh.com", 176 | //! "aes128-ctr,aes192-ctr,aes256-ctr", 177 | //! "aes128-gcm@openssh.com,aes256-gcm@openssh.com", 178 | //! "umac-64-etm@openssh.com", 179 | //! "umac-128-etm@openssh.com", 180 | //! "hmac-sha2-256-etm@openssh.com", 181 | //! "hmac-sha2-512-etm@openssh.com", 182 | //! "hmac-sha1-etm@openssh.com", 183 | //! "umac-64@openssh.com", 184 | //! "umac-128@openssh.com", 185 | //! "hmac-sha2-256", 186 | //! "hmac-sha2-512", 187 | //! "hmac-sha1", 188 | //! "umac-64-etm@openssh.com", 189 | //! "umac-128-etm@openssh.com", 190 | //! "hmac-sha2-256-etm@openssh.com", 191 | //! "hmac-sha2-512-etm@openssh.com", 192 | //! "hmac-sha1-etm@openssh.com", 193 | //! "umac-64@openssh.com", 194 | //! "umac-128@openssh.com", 195 | //! "hmac-sha2-256", 196 | //! "hmac-sha2-512", 197 | //! "hmac-sha1", 198 | //! "none,zlib@openssh.com", 199 | //! "none,zlib@openssh.com", 200 | //! 201 | //! mac: 202 | //! "umac-64-etm@openssh.com", 203 | //! "umac-128-etm@openssh.com", 204 | //! "hmac-sha2-256-etm@openssh.com", 205 | //! "hmac-sha2-512-etm@openssh.com", 206 | //! "hmac-sha1-etm@openssh.com", 207 | //! "umac-64@openssh.com", 208 | //! "umac-128@openssh.com", 209 | //! "hmac-sha2-256", 210 | //! "hmac-sha2-512", 211 | //! "hmac-sha1", 212 | //! 213 | //! pubkey_accepted_algorithms: 214 | //! "ssh-ed25519-cert-v01@openssh.com", 215 | //! "ecdsa-sha2-nistp256-cert-v01@openssh.com", 216 | //! "ecdsa-sha2-nistp384-cert-v01@openssh.com", 217 | //! "ecdsa-sha2-nistp521-cert-v01@openssh.com", 218 | //! "sk-ssh-ed25519-cert-v01@openssh.com", 219 | //! "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", 220 | //! "rsa-sha2-512-cert-v01@openssh.com", 221 | //! "rsa-sha2-256-cert-v01@openssh.com", 222 | //! "ssh-ed25519", 223 | //! "ecdsa-sha2-nistp256", 224 | //! "ecdsa-sha2-nistp384", 225 | //! "ecdsa-sha2-nistp521", 226 | //! "sk-ssh-ed25519@openssh.com", 227 | //! "sk-ecdsa-sha2-nistp256@openssh.com", 228 | //! "rsa-sha2-512", 229 | //! "rsa-sha2-256", 230 | //! ``` 231 | //! 232 | //! If you want you can use a custom constructor [`SshConfig::default_algorithms`] to set your own default algorithms. 233 | 234 | #![doc(html_playground_url = "https://play.rust-lang.org")] 235 | 236 | #[macro_use] 237 | extern crate log; 238 | 239 | use std::fmt; 240 | use std::fs::File; 241 | use std::io::{self, BufRead, BufReader}; 242 | use std::path::PathBuf; 243 | use std::time::Duration; 244 | // -- modules 245 | mod default_algorithms; 246 | mod host; 247 | mod params; 248 | mod parser; 249 | mod serializer; 250 | 251 | // -- export 252 | pub use self::default_algorithms::DefaultAlgorithms; 253 | pub use self::host::{Host, HostClause}; 254 | pub use self::params::{Algorithms, HostParams}; 255 | pub use self::parser::{ParseRule, SshParserError, SshParserResult}; 256 | 257 | /// Describes the ssh configuration. 258 | /// Configuration is described in this document: 259 | #[derive(Debug, Clone, PartialEq, Eq, Default)] 260 | pub struct SshConfig { 261 | /// Default algorithms for ssh. 262 | default_algorithms: DefaultAlgorithms, 263 | /// Rulesets for hosts. 264 | /// Default config will be stored with key `*` 265 | hosts: Vec, 266 | } 267 | 268 | impl fmt::Display for SshConfig { 269 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 270 | serializer::SshConfigSerializer::from(self).serialize(f) 271 | } 272 | } 273 | 274 | impl SshConfig { 275 | /// Query params for a certain host. Returns [`HostParams`] for the host. 276 | pub fn query>(&self, pattern: S) -> HostParams { 277 | let mut params = HostParams::new(&self.default_algorithms); 278 | // iter keys, overwrite if None top-down 279 | for host in self.hosts.iter() { 280 | if host.intersects(pattern.as_ref()) { 281 | debug!( 282 | "Merging params for host: {:?} into params {params:?}", 283 | host.pattern 284 | ); 285 | params.overwrite_if_none(&host.params); 286 | trace!("Params after merge: {params:?}"); 287 | } 288 | } 289 | // return calculated params 290 | params 291 | } 292 | 293 | /// Get an iterator over the [`Host`]s which intersect with the given host pattern 294 | pub fn intersecting_hosts(&self, pattern: &str) -> impl Iterator { 295 | self.hosts.iter().filter(|host| host.intersects(pattern)) 296 | } 297 | 298 | /// Set default algorithms for ssh. 299 | /// 300 | /// If you want to use the default algorithms from the system, you can use the `Default::default()` method. 301 | pub fn default_algorithms(mut self, algos: DefaultAlgorithms) -> Self { 302 | self.default_algorithms = algos; 303 | 304 | self 305 | } 306 | 307 | /// Parse [`SshConfig`] from stream which implements [`BufRead`] and return parsed configuration or parser error 308 | /// 309 | /// ## Example 310 | /// 311 | /// ```rust,ignore 312 | /// let mut reader = BufReader::new( 313 | /// File::open(Path::new("./assets/ssh.config")) 314 | /// .expect("Could not open configuration file") 315 | /// ); 316 | /// 317 | /// let config = SshConfig::default().parse(&mut reader, ParseRule::STRICT).expect("Failed to parse configuration"); 318 | /// ``` 319 | pub fn parse(mut self, reader: &mut impl BufRead, rules: ParseRule) -> SshParserResult { 320 | parser::SshConfigParser::parse(&mut self, reader, rules).map(|_| self) 321 | } 322 | 323 | /// Parse `~/.ssh/config`` file and return parsed configuration [`SshConfig`] or parser error 324 | pub fn parse_default_file(rules: ParseRule) -> SshParserResult { 325 | let ssh_folder = dirs::home_dir() 326 | .ok_or_else(|| { 327 | SshParserError::Io(io::Error::new( 328 | io::ErrorKind::NotFound, 329 | "Home folder not found", 330 | )) 331 | })? 332 | .join(".ssh"); 333 | 334 | let mut reader = 335 | BufReader::new(File::open(ssh_folder.join("config")).map_err(SshParserError::Io)?); 336 | 337 | Self::default().parse(&mut reader, rules) 338 | } 339 | 340 | /// Get list of [`Host`]s in the configuration 341 | pub fn get_hosts(&self) -> &Vec { 342 | &self.hosts 343 | } 344 | } 345 | 346 | #[cfg(test)] 347 | fn test_log() { 348 | use std::sync::Once; 349 | 350 | static INIT: Once = Once::new(); 351 | 352 | INIT.call_once(|| { 353 | let _ = env_logger::builder() 354 | .filter_level(log::LevelFilter::Trace) 355 | .is_test(true) 356 | .try_init(); 357 | }); 358 | } 359 | 360 | #[cfg(test)] 361 | mod test { 362 | 363 | use pretty_assertions::assert_eq; 364 | 365 | use super::*; 366 | 367 | #[test] 368 | fn should_init_ssh_config() { 369 | test_log(); 370 | 371 | let config = SshConfig::default(); 372 | assert_eq!(config.hosts.len(), 0); 373 | assert_eq!( 374 | config.query("192.168.1.2"), 375 | HostParams::new(&DefaultAlgorithms::default()) 376 | ); 377 | } 378 | 379 | #[test] 380 | fn should_parse_default_config() -> Result<(), parser::SshParserError> { 381 | test_log(); 382 | 383 | let _config = SshConfig::parse_default_file(ParseRule::ALLOW_UNKNOWN_FIELDS)?; 384 | Ok(()) 385 | } 386 | 387 | #[test] 388 | fn should_parse_config() -> Result<(), parser::SshParserError> { 389 | test_log(); 390 | 391 | use std::fs::File; 392 | use std::io::BufReader; 393 | use std::path::Path; 394 | 395 | let mut reader = BufReader::new( 396 | File::open(Path::new("./assets/ssh.config")) 397 | .expect("Could not open configuration file"), 398 | ); 399 | 400 | SshConfig::default().parse(&mut reader, ParseRule::STRICT)?; 401 | 402 | Ok(()) 403 | } 404 | 405 | #[test] 406 | fn should_query_ssh_config() { 407 | test_log(); 408 | 409 | let mut config = SshConfig::default(); 410 | // add config 411 | let mut params1 = HostParams::new(&DefaultAlgorithms::default()); 412 | params1.bind_address = Some("0.0.0.0".to_string()); 413 | config.hosts.push(Host::new( 414 | vec![HostClause::new(String::from("192.168.*.*"), false)], 415 | params1.clone(), 416 | )); 417 | let mut params2 = HostParams::new(&DefaultAlgorithms::default()); 418 | params2.bind_interface = Some(String::from("tun0")); 419 | config.hosts.push(Host::new( 420 | vec![HostClause::new(String::from("192.168.10.*"), false)], 421 | params2.clone(), 422 | )); 423 | 424 | let mut params3 = HostParams::new(&DefaultAlgorithms::default()); 425 | params3.host_name = Some("172.26.104.4".to_string()); 426 | config.hosts.push(Host::new( 427 | vec![ 428 | HostClause::new(String::from("172.26.*.*"), false), 429 | HostClause::new(String::from("172.26.104.4"), true), 430 | ], 431 | params3.clone(), 432 | )); 433 | // Query 434 | assert_eq!(config.query("192.168.1.32"), params1); 435 | // merged case 436 | params1.overwrite_if_none(¶ms2); 437 | assert_eq!(config.query("192.168.10.1"), params1); 438 | // Negated case 439 | assert_eq!(config.query("172.26.254.1"), params3); 440 | assert_eq!( 441 | config.query("172.26.104.4"), 442 | HostParams::new(&DefaultAlgorithms::default()) 443 | ); 444 | } 445 | } 446 | -------------------------------------------------------------------------------- /src/params.rs: -------------------------------------------------------------------------------- 1 | //! # params 2 | //! 3 | //! Ssh config params for host rule 4 | 5 | mod algos; 6 | 7 | use std::collections::HashMap; 8 | 9 | pub use self::algos::Algorithms; 10 | pub(crate) use self::algos::AlgorithmsRule; 11 | use super::{Duration, PathBuf}; 12 | use crate::DefaultAlgorithms; 13 | 14 | /// Describes the ssh configuration. 15 | /// Configuration is describes in this document: 16 | /// Only arguments supported by libssh2 are implemented 17 | #[derive(Debug, Clone, PartialEq, Eq)] 18 | pub struct HostParams { 19 | /// Specifies to use the specified address on the local machine as the source address of the connection 20 | pub bind_address: Option, 21 | /// Use the specified address on the local machine as the source address of the connection 22 | pub bind_interface: Option, 23 | /// Specifies which algorithms are allowed for signing of certificates by certificate authorities 24 | pub ca_signature_algorithms: Algorithms, 25 | /// Specifies a file from which the user's certificate is read 26 | pub certificate_file: Option, 27 | /// Specifies the ciphers allowed for protocol version 2 in order of preference 28 | pub ciphers: Algorithms, 29 | /// Specifies whether to use compression 30 | pub compression: Option, 31 | /// Specifies the number of attempts to make before exiting 32 | pub connection_attempts: Option, 33 | /// Specifies the timeout used when connecting to the SSH server 34 | pub connect_timeout: Option, 35 | /// Specifies the host key signature algorithms that the client wants to use in order of preference 36 | pub host_key_algorithms: Algorithms, 37 | /// Specifies the real host name to log into 38 | pub host_name: Option, 39 | /// Specifies the path of the identity file to be used when authenticating. 40 | /// More than one file can be specified. 41 | /// If more than one file is specified, they will be read in order 42 | pub identity_file: Option>, 43 | /// Specifies a pattern-list of unknown options to be ignored if they are encountered in configuration parsing 44 | pub ignore_unknown: Option>, 45 | /// Specifies the available KEX (Key Exchange) algorithms 46 | pub kex_algorithms: Algorithms, 47 | /// Specifies the MAC (message authentication code) algorithms in order of preference 48 | pub mac: Algorithms, 49 | /// Specifies the port number to connect on the remote host. 50 | pub port: Option, 51 | /// Specifies the signature algorithms that will be used for public key authentication 52 | pub pubkey_accepted_algorithms: Algorithms, 53 | /// Specifies whether to try public key authentication using SSH keys 54 | pub pubkey_authentication: Option, 55 | /// Specifies that a TCP port on the remote machine be forwarded over the secure channel 56 | pub remote_forward: Option, 57 | /// Sets a timeout interval in seconds after which if no data has been received from the server, keep alive will be sent 58 | pub server_alive_interval: Option, 59 | /// Specifies whether to send TCP keepalives to the other side 60 | pub tcp_keep_alive: Option, 61 | #[cfg(target_os = "macos")] 62 | /// specifies whether the system should search for passphrases in the user's keychain when attempting to use a particular key 63 | pub use_keychain: Option, 64 | /// Specifies the user to log in as. 65 | pub user: Option, 66 | /// fields that the parser wasn't able to parse 67 | pub ignored_fields: HashMap>, 68 | /// fields that the parser was able to parse but ignored 69 | pub unsupported_fields: HashMap>, 70 | } 71 | 72 | impl HostParams { 73 | /// Create a new [`HostParams`] object with the [`DefaultAlgorithms`] 74 | pub fn new(default_algorithms: &DefaultAlgorithms) -> Self { 75 | Self { 76 | bind_address: None, 77 | bind_interface: None, 78 | ca_signature_algorithms: Algorithms::new(&default_algorithms.ca_signature_algorithms), 79 | certificate_file: None, 80 | ciphers: Algorithms::new(&default_algorithms.ciphers), 81 | compression: None, 82 | connection_attempts: None, 83 | connect_timeout: None, 84 | host_key_algorithms: Algorithms::new(&default_algorithms.host_key_algorithms), 85 | host_name: None, 86 | identity_file: None, 87 | ignore_unknown: None, 88 | kex_algorithms: Algorithms::new(&default_algorithms.kex_algorithms), 89 | mac: Algorithms::new(&default_algorithms.mac), 90 | port: None, 91 | pubkey_accepted_algorithms: Algorithms::new( 92 | &default_algorithms.pubkey_accepted_algorithms, 93 | ), 94 | pubkey_authentication: None, 95 | remote_forward: None, 96 | server_alive_interval: None, 97 | tcp_keep_alive: None, 98 | #[cfg(target_os = "macos")] 99 | use_keychain: None, 100 | user: None, 101 | ignored_fields: HashMap::new(), 102 | unsupported_fields: HashMap::new(), 103 | } 104 | } 105 | 106 | /// Return whether a certain `param` is in the ignored list 107 | pub(crate) fn ignored(&self, param: &str) -> bool { 108 | self.ignore_unknown 109 | .as_ref() 110 | .map(|x| x.iter().any(|x| x.as_str() == param)) 111 | .unwrap_or(false) 112 | } 113 | 114 | /// Given a [`HostParams`] object `b`, it will overwrite all the params from `self` only if they are [`None`] 115 | pub fn overwrite_if_none(&mut self, b: &Self) { 116 | self.bind_address = self.bind_address.clone().or_else(|| b.bind_address.clone()); 117 | self.bind_interface = self 118 | .bind_interface 119 | .clone() 120 | .or_else(|| b.bind_interface.clone()); 121 | self.certificate_file = self 122 | .certificate_file 123 | .clone() 124 | .or_else(|| b.certificate_file.clone()); 125 | self.compression = self.compression.or(b.compression); 126 | self.connection_attempts = self.connection_attempts.or(b.connection_attempts); 127 | self.connect_timeout = self.connect_timeout.or(b.connect_timeout); 128 | self.host_name = self.host_name.clone().or_else(|| b.host_name.clone()); 129 | self.identity_file = self 130 | .identity_file 131 | .clone() 132 | .or_else(|| b.identity_file.clone()); 133 | self.ignore_unknown = self 134 | .ignore_unknown 135 | .clone() 136 | .or_else(|| b.ignore_unknown.clone()); 137 | self.port = self.port.or(b.port); 138 | self.pubkey_authentication = self.pubkey_authentication.or(b.pubkey_authentication); 139 | self.remote_forward = self.remote_forward.or(b.remote_forward); 140 | self.server_alive_interval = self.server_alive_interval.or(b.server_alive_interval); 141 | #[cfg(target_os = "macos")] 142 | { 143 | self.use_keychain = self.use_keychain.or(b.use_keychain); 144 | } 145 | self.tcp_keep_alive = self.tcp_keep_alive.or(b.tcp_keep_alive); 146 | self.user = self.user.clone().or_else(|| b.user.clone()); 147 | for (ignored_field, args) in &b.ignored_fields { 148 | if !self.ignored_fields.contains_key(ignored_field) { 149 | self.ignored_fields 150 | .insert(ignored_field.to_owned(), args.to_owned()); 151 | } 152 | } 153 | for (unsupported_field, args) in &b.unsupported_fields { 154 | if !self.unsupported_fields.contains_key(unsupported_field) { 155 | self.unsupported_fields 156 | .insert(unsupported_field.to_owned(), args.to_owned()); 157 | } 158 | } 159 | 160 | // merge algos if default and b is not default 161 | if self.ca_signature_algorithms.is_default() && !b.ca_signature_algorithms.is_default() { 162 | self.ca_signature_algorithms = b.ca_signature_algorithms.clone(); 163 | } 164 | if self.ciphers.is_default() && !b.ciphers.is_default() { 165 | self.ciphers = b.ciphers.clone(); 166 | } 167 | if self.host_key_algorithms.is_default() && !b.host_key_algorithms.is_default() { 168 | self.host_key_algorithms = b.host_key_algorithms.clone(); 169 | } 170 | if self.kex_algorithms.is_default() && !b.kex_algorithms.is_default() { 171 | self.kex_algorithms = b.kex_algorithms.clone(); 172 | } 173 | if self.mac.is_default() && !b.mac.is_default() { 174 | self.mac = b.mac.clone(); 175 | } 176 | if self.pubkey_accepted_algorithms.is_default() 177 | && !b.pubkey_accepted_algorithms.is_default() 178 | { 179 | self.pubkey_accepted_algorithms = b.pubkey_accepted_algorithms.clone(); 180 | } 181 | } 182 | } 183 | 184 | #[cfg(test)] 185 | mod test { 186 | 187 | use std::str::FromStr; 188 | 189 | use pretty_assertions::assert_eq; 190 | 191 | use super::*; 192 | use crate::params::algos::AlgorithmsRule; 193 | 194 | #[test] 195 | fn should_initialize_params() { 196 | let params = HostParams::new(&DefaultAlgorithms::default()); 197 | assert!(params.bind_address.is_none()); 198 | assert!(params.bind_interface.is_none()); 199 | assert_eq!( 200 | params.ca_signature_algorithms.algorithms(), 201 | DefaultAlgorithms::default().ca_signature_algorithms 202 | ); 203 | assert!(params.certificate_file.is_none()); 204 | assert_eq!( 205 | params.ciphers.algorithms(), 206 | DefaultAlgorithms::default().ciphers 207 | ); 208 | assert!(params.compression.is_none()); 209 | assert!(params.connection_attempts.is_none()); 210 | assert!(params.connect_timeout.is_none()); 211 | assert_eq!( 212 | params.host_key_algorithms.algorithms(), 213 | DefaultAlgorithms::default().host_key_algorithms 214 | ); 215 | assert!(params.host_name.is_none()); 216 | assert!(params.identity_file.is_none()); 217 | assert!(params.ignore_unknown.is_none()); 218 | assert_eq!( 219 | params.kex_algorithms.algorithms(), 220 | DefaultAlgorithms::default().kex_algorithms 221 | ); 222 | assert_eq!(params.mac.algorithms(), DefaultAlgorithms::default().mac); 223 | assert!(params.port.is_none()); 224 | assert_eq!( 225 | params.pubkey_accepted_algorithms.algorithms(), 226 | DefaultAlgorithms::default().pubkey_accepted_algorithms 227 | ); 228 | assert!(params.pubkey_authentication.is_none()); 229 | assert!(params.remote_forward.is_none()); 230 | assert!(params.server_alive_interval.is_none()); 231 | #[cfg(target_os = "macos")] 232 | assert!(params.use_keychain.is_none()); 233 | assert!(params.tcp_keep_alive.is_none()); 234 | } 235 | 236 | #[test] 237 | fn test_should_overwrite_if_none() { 238 | let mut params = HostParams::new(&DefaultAlgorithms::default()); 239 | params.bind_address = Some(String::from("pippo")); 240 | 241 | let mut b = HostParams::new(&DefaultAlgorithms::default()); 242 | b.bind_address = Some(String::from("pluto")); 243 | b.bind_interface = Some(String::from("tun0")); 244 | b.ciphers 245 | .apply(AlgorithmsRule::from_str("c,d").expect("parse error")); 246 | 247 | params.overwrite_if_none(&b); 248 | assert_eq!(params.bind_address.unwrap(), "pippo"); 249 | assert_eq!(params.bind_interface.unwrap(), "tun0"); 250 | 251 | // algos 252 | assert_eq!( 253 | params.ciphers.algorithms(), 254 | vec!["c".to_string(), "d".to_string()] 255 | ); 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /src/params/algos.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::str::FromStr; 3 | 4 | use crate::SshParserError; 5 | 6 | const ID_APPEND: char = '+'; 7 | const ID_HEAD: char = '^'; 8 | const ID_EXCLUDE: char = '-'; 9 | 10 | /// List of algorithms to be used. 11 | /// The algorithms can be appended to the default set, placed at the head of the list, 12 | /// excluded from the default set, or set as the default set. 13 | /// 14 | /// # Configuring SSH Algorithms 15 | /// 16 | /// In order to configure ssh you should use the `to_string()` method to get the string representation 17 | /// with the correct format for ssh2. 18 | #[derive(Debug, Clone, PartialEq, Eq)] 19 | pub struct Algorithms { 20 | /// Algorithms to be used. 21 | algos: Vec, 22 | /// whether the default algorithms have been overridden 23 | overridden: bool, 24 | /// applied rule 25 | rule: Option, 26 | } 27 | 28 | impl Algorithms { 29 | /// Create a new instance of [`Algorithms`] with the given default algorithms. 30 | /// 31 | /// ## Example 32 | /// 33 | /// ```rust 34 | /// use ssh2_config::Algorithms; 35 | /// 36 | /// let algos = Algorithms::new(&["aes128-ctr", "aes192-ctr"]); 37 | /// ``` 38 | pub fn new(default: I) -> Self 39 | where 40 | I: IntoIterator, 41 | S: AsRef, 42 | { 43 | Self { 44 | algos: default 45 | .into_iter() 46 | .map(|s| s.as_ref().to_string()) 47 | .collect(), 48 | overridden: false, 49 | rule: None, 50 | } 51 | } 52 | } 53 | 54 | /// List of algorithms to be used. 55 | /// The algorithms can be appended to the default set, placed at the head of the list, 56 | /// excluded from the default set, or set as the default set. 57 | /// 58 | /// # Configuring SSH Algorithms 59 | /// 60 | /// In order to configure ssh you should use the `to_string()` method to get the string representation 61 | /// with the correct format for ssh2. 62 | /// 63 | /// # Algorithms vector 64 | /// 65 | /// Otherwise you can access the inner [`Vec`] of algorithms with the [`Algorithms::algos`] method. 66 | /// 67 | /// Beware though, that you must **TAKE CARE of the current variant**. 68 | /// 69 | /// For instance in case the variant is [`Algorithms::Exclude`] the algos contained in the vec are the ones **to be excluded**. 70 | /// 71 | /// While in case of [`Algorithms::Append`] the algos contained in the vec are the ones to be appended to the default ones. 72 | #[derive(Clone, Debug, PartialEq, Eq)] 73 | pub enum AlgorithmsRule { 74 | /// Append the given algorithms to the default set. 75 | Append(Vec), 76 | /// Place the given algorithms at the head of the list. 77 | Head(Vec), 78 | /// Exclude the given algorithms from the default set. 79 | Exclude(Vec), 80 | /// Set the given algorithms as the default set. 81 | Set(Vec), 82 | } 83 | 84 | /// Rule applied; used to format algorithms 85 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 86 | enum AlgorithmsOp { 87 | Append, 88 | Head, 89 | Exclude, 90 | Set, 91 | } 92 | 93 | impl Algorithms { 94 | /// Returns whether the default algorithms are being used. 95 | pub fn is_default(&self) -> bool { 96 | !self.overridden 97 | } 98 | 99 | /// Returns algorithms to be used. 100 | pub fn algorithms(&self) -> &[String] { 101 | &self.algos 102 | } 103 | 104 | /// Apply an [`AlgorithmsRule`] to the [`Algorithms`] instance. 105 | /// 106 | /// If defaults haven't been overridden, apply changes from incoming rule; 107 | /// otherwise keep as-is. 108 | pub fn apply(&mut self, rule: AlgorithmsRule) { 109 | if self.overridden { 110 | // don't apply changes if defaults have been overridden 111 | return; 112 | } 113 | 114 | let mut current_algos = self.algos.clone(); 115 | 116 | match rule.clone() { 117 | AlgorithmsRule::Append(algos) => { 118 | // append but exclude duplicates 119 | for algo in algos { 120 | if !current_algos.iter().any(|s| s == &algo) { 121 | current_algos.push(algo); 122 | } 123 | } 124 | } 125 | AlgorithmsRule::Head(algos) => { 126 | current_algos = algos; 127 | current_algos.extend(self.algorithms().iter().map(|s| s.to_string())); 128 | } 129 | AlgorithmsRule::Exclude(exclude) => { 130 | current_algos = current_algos 131 | .iter() 132 | .filter(|algo| !exclude.contains(algo)) 133 | .map(|s| s.to_string()) 134 | .collect(); 135 | } 136 | AlgorithmsRule::Set(algos) => { 137 | // override default with new set 138 | current_algos = algos; 139 | } 140 | } 141 | 142 | // apply changes 143 | self.rule = Some(rule); 144 | self.algos = current_algos; 145 | self.overridden = true; 146 | } 147 | } 148 | 149 | impl AlgorithmsRule { 150 | fn op(&self) -> AlgorithmsOp { 151 | match self { 152 | Self::Append(_) => AlgorithmsOp::Append, 153 | Self::Head(_) => AlgorithmsOp::Head, 154 | Self::Exclude(_) => AlgorithmsOp::Exclude, 155 | Self::Set(_) => AlgorithmsOp::Set, 156 | } 157 | } 158 | } 159 | 160 | impl FromStr for AlgorithmsRule { 161 | type Err = SshParserError; 162 | 163 | fn from_str(s: &str) -> Result { 164 | if s.is_empty() { 165 | return Err(SshParserError::ExpectedAlgorithms); 166 | } 167 | 168 | // get first char 169 | let (op, start) = match s.chars().next().expect("can't be empty") { 170 | ID_APPEND => (AlgorithmsOp::Append, 1), 171 | ID_HEAD => (AlgorithmsOp::Head, 1), 172 | ID_EXCLUDE => (AlgorithmsOp::Exclude, 1), 173 | _ => (AlgorithmsOp::Set, 0), 174 | }; 175 | 176 | let algos = s[start..] 177 | .split(',') 178 | .map(|s| s.trim().to_string()) 179 | .collect::>(); 180 | 181 | match op { 182 | AlgorithmsOp::Append => Ok(Self::Append(algos)), 183 | AlgorithmsOp::Head => Ok(Self::Head(algos)), 184 | AlgorithmsOp::Exclude => Ok(Self::Exclude(algos)), 185 | AlgorithmsOp::Set => Ok(Self::Set(algos)), 186 | } 187 | } 188 | } 189 | 190 | impl fmt::Display for AlgorithmsRule { 191 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 192 | let op = self.op(); 193 | write!(f, "{op}") 194 | } 195 | } 196 | 197 | impl fmt::Display for AlgorithmsOp { 198 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 199 | match &self { 200 | Self::Append => write!(f, "{ID_APPEND}"), 201 | Self::Head => write!(f, "{ID_HEAD}"), 202 | Self::Exclude => write!(f, "{ID_EXCLUDE}"), 203 | Self::Set => write!(f, ""), 204 | } 205 | } 206 | } 207 | 208 | impl fmt::Display for Algorithms { 209 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 210 | if let Some(rule) = self.rule.as_ref() { 211 | write!(f, "{rule}",) 212 | } else { 213 | write!(f, "{}", self.algos.join(",")) 214 | } 215 | } 216 | } 217 | 218 | #[cfg(test)] 219 | mod test { 220 | 221 | use pretty_assertions::assert_eq; 222 | 223 | use super::*; 224 | 225 | #[test] 226 | fn test_should_parse_algos_set() { 227 | let algo = 228 | AlgorithmsRule::from_str("aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse"); 229 | assert_eq!( 230 | algo, 231 | AlgorithmsRule::Set(vec![ 232 | "aes128-ctr".to_string(), 233 | "aes192-ctr".to_string(), 234 | "aes256-ctr".to_string() 235 | ]) 236 | ); 237 | } 238 | 239 | #[test] 240 | fn test_should_parse_algos_append() { 241 | let algo = 242 | AlgorithmsRule::from_str("+aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse"); 243 | assert_eq!( 244 | algo, 245 | AlgorithmsRule::Append(vec![ 246 | "aes128-ctr".to_string(), 247 | "aes192-ctr".to_string(), 248 | "aes256-ctr".to_string() 249 | ]) 250 | ); 251 | } 252 | 253 | #[test] 254 | fn test_should_parse_algos_head() { 255 | let algo = 256 | AlgorithmsRule::from_str("^aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse"); 257 | assert_eq!( 258 | algo, 259 | AlgorithmsRule::Head(vec![ 260 | "aes128-ctr".to_string(), 261 | "aes192-ctr".to_string(), 262 | "aes256-ctr".to_string() 263 | ]) 264 | ); 265 | } 266 | 267 | #[test] 268 | fn test_should_parse_algos_exclude() { 269 | let algo = 270 | AlgorithmsRule::from_str("-aes128-ctr,aes192-ctr,aes256-ctr").expect("failed to parse"); 271 | assert_eq!( 272 | algo, 273 | AlgorithmsRule::Exclude(vec![ 274 | "aes128-ctr".to_string(), 275 | "aes192-ctr".to_string(), 276 | "aes256-ctr".to_string() 277 | ]) 278 | ); 279 | } 280 | 281 | #[test] 282 | fn test_should_apply_append() { 283 | let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]); 284 | let algo2 = AlgorithmsRule::from_str("+aes256-ctr").expect("failed to parse"); 285 | algo1.apply(algo2); 286 | assert_eq!( 287 | algo1.algorithms(), 288 | vec![ 289 | "aes128-ctr".to_string(), 290 | "aes192-ctr".to_string(), 291 | "aes256-ctr".to_string() 292 | ] 293 | ); 294 | } 295 | 296 | #[test] 297 | fn test_should_merge_append_if_undefined() { 298 | let algos: Vec = vec![]; 299 | let mut algo1 = Algorithms::new(algos); 300 | let algo2 = AlgorithmsRule::from_str("+aes256-ctr").expect("failed to parse"); 301 | algo1.apply(algo2); 302 | assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string()]); 303 | } 304 | 305 | #[test] 306 | fn test_should_merge_head() { 307 | let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]); 308 | let algo2 = AlgorithmsRule::from_str("^aes256-ctr").expect("failed to parse"); 309 | algo1.apply(algo2); 310 | assert_eq!( 311 | algo1.algorithms(), 312 | vec![ 313 | "aes256-ctr".to_string(), 314 | "aes128-ctr".to_string(), 315 | "aes192-ctr".to_string() 316 | ] 317 | ); 318 | } 319 | 320 | #[test] 321 | fn test_should_apply_head() { 322 | let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]); 323 | let algo2 = AlgorithmsRule::from_str("^aes256-ctr").expect("failed to parse"); 324 | algo1.apply(algo2); 325 | assert_eq!( 326 | algo1.algorithms(), 327 | vec![ 328 | "aes256-ctr".to_string(), 329 | "aes128-ctr".to_string(), 330 | "aes192-ctr".to_string() 331 | ] 332 | ); 333 | } 334 | 335 | #[test] 336 | fn test_should_merge_exclude() { 337 | let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr", "aes256-ctr"]); 338 | let algo2 = AlgorithmsRule::from_str("-aes192-ctr").expect("failed to parse"); 339 | algo1.apply(algo2); 340 | assert_eq!( 341 | algo1.algorithms(), 342 | vec!["aes128-ctr".to_string(), "aes256-ctr".to_string()] 343 | ); 344 | } 345 | 346 | #[test] 347 | fn test_should_merge_set() { 348 | let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]); 349 | let algo2 = AlgorithmsRule::from_str("aes256-ctr").expect("failed to parse"); 350 | algo1.apply(algo2); 351 | assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string()]); 352 | } 353 | 354 | #[test] 355 | fn test_should_not_apply_twice() { 356 | let mut algo1 = Algorithms::new(&["aes128-ctr", "aes192-ctr"]); 357 | let algo2 = AlgorithmsRule::from_str("aes256-ctr").expect("failed to parse"); 358 | algo1.apply(algo2); 359 | assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string(),]); 360 | 361 | let algo3 = AlgorithmsRule::from_str("aes128-ctr").expect("failed to parse"); 362 | algo1.apply(algo3); 363 | assert_eq!(algo1.algorithms(), vec!["aes256-ctr".to_string()]); 364 | assert_eq!(algo1.overridden, true); 365 | } 366 | } 367 | -------------------------------------------------------------------------------- /src/parser.rs: -------------------------------------------------------------------------------- 1 | //! # parser 2 | //! 3 | //! Ssh config parser 4 | 5 | use std::fs::File; 6 | use std::io::{BufRead, BufReader, Error as IoError}; 7 | use std::path::PathBuf; 8 | use std::str::FromStr; 9 | use std::time::Duration; 10 | 11 | use bitflags::bitflags; 12 | use glob::glob; 13 | use thiserror::Error; 14 | 15 | use super::{Host, HostClause, HostParams, SshConfig}; 16 | use crate::DefaultAlgorithms; 17 | use crate::params::AlgorithmsRule; 18 | 19 | // modules 20 | mod field; 21 | use field::Field; 22 | 23 | pub type SshParserResult = Result; 24 | 25 | /// Ssh config parser error 26 | #[derive(Debug, Error)] 27 | pub enum SshParserError { 28 | #[error("expected boolean value ('yes', 'no')")] 29 | ExpectedBoolean, 30 | #[error("expected port number")] 31 | ExpectedPort, 32 | #[error("expected unsigned value")] 33 | ExpectedUnsigned, 34 | #[error("expected algorithms")] 35 | ExpectedAlgorithms, 36 | #[error("expected path")] 37 | ExpectedPath, 38 | #[error("IO error: {0}")] 39 | Io(#[from] IoError), 40 | #[error("glob error: {0}")] 41 | Glob(#[from] glob::GlobError), 42 | #[error("missing argument")] 43 | MissingArgument, 44 | #[error("pattern error: {0}")] 45 | PatternError(#[from] glob::PatternError), 46 | #[error("unknown field: {0}")] 47 | UnknownField(String, Vec), 48 | #[error("unknown field: {0}")] 49 | UnsupportedField(String, Vec), 50 | } 51 | 52 | bitflags! { 53 | /// The parsing mode 54 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] 55 | pub struct ParseRule: u8 { 56 | /// Don't allow any invalid field or value 57 | const STRICT = 0b00000000; 58 | /// Allow unknown field 59 | const ALLOW_UNKNOWN_FIELDS = 0b00000001; 60 | /// Allow unsupported fields 61 | const ALLOW_UNSUPPORTED_FIELDS = 0b00000010; 62 | } 63 | } 64 | 65 | // -- parser 66 | 67 | /// Ssh config parser 68 | pub struct SshConfigParser; 69 | 70 | impl SshConfigParser { 71 | /// Parse reader lines and apply parameters to configuration 72 | pub fn parse( 73 | config: &mut SshConfig, 74 | reader: &mut impl BufRead, 75 | rules: ParseRule, 76 | ) -> SshParserResult<()> { 77 | // Options preceding the first `Host` section 78 | // are parsed as command line options; 79 | // overriding all following host-specific options. 80 | // 81 | // See https://github.com/openssh/openssh-portable/blob/master/readconf.c#L1051-L1054 82 | config.hosts.push(Host::new( 83 | vec![HostClause::new(String::from("*"), false)], 84 | HostParams::new(&config.default_algorithms), 85 | )); 86 | 87 | // Current host pointer 88 | let mut current_host = config.hosts.last_mut().unwrap(); 89 | 90 | let mut lines = reader.lines(); 91 | // iter lines 92 | loop { 93 | let line = match lines.next() { 94 | None => break, 95 | Some(Err(err)) => return Err(SshParserError::Io(err)), 96 | Some(Ok(line)) => Self::strip_comments(line.trim()), 97 | }; 98 | if line.is_empty() { 99 | continue; 100 | } 101 | // tokenize 102 | let (field, args) = match Self::tokenize_line(&line) { 103 | Ok((field, args)) => (field, args), 104 | Err(SshParserError::UnknownField(field, args)) 105 | if rules.intersects(ParseRule::ALLOW_UNKNOWN_FIELDS) 106 | || current_host.params.ignored(&field) => 107 | { 108 | current_host.params.ignored_fields.insert(field, args); 109 | continue; 110 | } 111 | Err(SshParserError::UnknownField(field, args)) => { 112 | return Err(SshParserError::UnknownField(field, args)); 113 | } 114 | Err(err) => return Err(err), 115 | }; 116 | // If field is block, init a new block 117 | if field == Field::Host { 118 | // Pass `ignore_unknown` from global overrides down into the tokenizer. 119 | let mut params = HostParams::new(&config.default_algorithms); 120 | params.ignore_unknown = config.hosts[0].params.ignore_unknown.clone(); 121 | let pattern = Self::parse_host(args)?; 122 | trace!("Adding new host: {pattern:?}",); 123 | 124 | // Add a new host 125 | config.hosts.push(Host::new(pattern, params)); 126 | // Update current host pointer 127 | current_host = config.hosts.last_mut().unwrap(); 128 | } else { 129 | // Update field 130 | match Self::update_host( 131 | field, 132 | args, 133 | current_host, 134 | rules, 135 | &config.default_algorithms, 136 | ) { 137 | Ok(()) => Ok(()), 138 | // If we're allowing unsupported fields to be parsed, add them to the map 139 | Err(SshParserError::UnsupportedField(field, args)) 140 | if rules.intersects(ParseRule::ALLOW_UNSUPPORTED_FIELDS) => 141 | { 142 | current_host.params.unsupported_fields.insert(field, args); 143 | Ok(()) 144 | } 145 | // Eat the error here to not break the API with this change 146 | // Also it'd be weird to error on correct ssh_config's just because they're 147 | // not supported by this library 148 | Err(SshParserError::UnsupportedField(_, _)) => Ok(()), 149 | e => e, 150 | }?; 151 | } 152 | } 153 | 154 | Ok(()) 155 | } 156 | 157 | /// Strip comments from line 158 | fn strip_comments(s: &str) -> String { 159 | if let Some(pos) = s.find('#') { 160 | s[..pos].to_string() 161 | } else { 162 | s.to_string() 163 | } 164 | } 165 | 166 | /// Update current given host with field argument 167 | fn update_host( 168 | field: Field, 169 | args: Vec, 170 | host: &mut Host, 171 | rules: ParseRule, 172 | default_algos: &DefaultAlgorithms, 173 | ) -> SshParserResult<()> { 174 | trace!("parsing field {field:?} with args {args:?}",); 175 | let params = &mut host.params; 176 | match field { 177 | Field::BindAddress => { 178 | let value = Self::parse_string(args)?; 179 | trace!("bind_address: {value}",); 180 | params.bind_address = Some(value); 181 | } 182 | Field::BindInterface => { 183 | let value = Self::parse_string(args)?; 184 | trace!("bind_interface: {value}",); 185 | params.bind_interface = Some(value); 186 | } 187 | Field::CaSignatureAlgorithms => { 188 | let rule = Self::parse_algos(args)?; 189 | trace!("ca_signature_algorithms: {rule:?}",); 190 | params.ca_signature_algorithms.apply(rule); 191 | } 192 | Field::CertificateFile => { 193 | let value = Self::parse_path(args)?; 194 | trace!("certificate_file: {value:?}",); 195 | params.certificate_file = Some(value); 196 | } 197 | Field::Ciphers => { 198 | let rule = Self::parse_algos(args)?; 199 | trace!("ciphers: {rule:?}",); 200 | params.ciphers.apply(rule); 201 | } 202 | Field::Compression => { 203 | let value = Self::parse_boolean(args)?; 204 | trace!("compression: {value}",); 205 | params.compression = Some(value); 206 | } 207 | Field::ConnectTimeout => { 208 | let value = Self::parse_duration(args)?; 209 | trace!("connect_timeout: {value:?}",); 210 | params.connect_timeout = Some(value); 211 | } 212 | Field::ConnectionAttempts => { 213 | let value = Self::parse_unsigned(args)?; 214 | trace!("connection_attempts: {value}",); 215 | params.connection_attempts = Some(value); 216 | } 217 | Field::Host => { /* already handled before */ } 218 | Field::HostKeyAlgorithms => { 219 | let rule = Self::parse_algos(args)?; 220 | trace!("host_key_algorithm: {rule:?}",); 221 | params.host_key_algorithms.apply(rule); 222 | } 223 | Field::HostName => { 224 | let value = Self::parse_string(args)?; 225 | trace!("host_name: {value}",); 226 | params.host_name = Some(value); 227 | } 228 | Field::Include => { 229 | Self::include_files(args, host, rules, default_algos)?; 230 | } 231 | Field::IdentityFile => { 232 | let value = Self::parse_path_list(args)?; 233 | trace!("identity_file: {value:?}",); 234 | params.identity_file = Some(value); 235 | } 236 | Field::IgnoreUnknown => { 237 | let value = Self::parse_comma_separated_list(args)?; 238 | trace!("ignore_unknown: {value:?}",); 239 | params.ignore_unknown = Some(value); 240 | } 241 | Field::KexAlgorithms => { 242 | let rule = Self::parse_algos(args)?; 243 | trace!("kex_algorithms: {rule:?}",); 244 | params.kex_algorithms.apply(rule); 245 | } 246 | Field::Mac => { 247 | let rule = Self::parse_algos(args)?; 248 | trace!("mac: {rule:?}",); 249 | params.mac.apply(rule); 250 | } 251 | Field::Port => { 252 | let value = Self::parse_port(args)?; 253 | trace!("port: {value}",); 254 | params.port = Some(value); 255 | } 256 | Field::PubkeyAcceptedAlgorithms => { 257 | let rule = Self::parse_algos(args)?; 258 | trace!("pubkey_accepted_algorithms: {rule:?}",); 259 | params.pubkey_accepted_algorithms.apply(rule); 260 | } 261 | Field::PubkeyAuthentication => { 262 | let value = Self::parse_boolean(args)?; 263 | trace!("pubkey_authentication: {value}",); 264 | params.pubkey_authentication = Some(value); 265 | } 266 | Field::RemoteForward => { 267 | let value = Self::parse_port(args)?; 268 | trace!("remote_forward: {value}",); 269 | params.remote_forward = Some(value); 270 | } 271 | Field::ServerAliveInterval => { 272 | let value = Self::parse_duration(args)?; 273 | trace!("server_alive_interval: {value:?}",); 274 | params.server_alive_interval = Some(value); 275 | } 276 | Field::TcpKeepAlive => { 277 | let value = Self::parse_boolean(args)?; 278 | trace!("tcp_keep_alive: {value}",); 279 | params.tcp_keep_alive = Some(value); 280 | } 281 | #[cfg(target_os = "macos")] 282 | Field::UseKeychain => { 283 | let value = Self::parse_boolean(args)?; 284 | trace!("use_keychain: {value}",); 285 | params.use_keychain = Some(value); 286 | } 287 | Field::User => { 288 | let value = Self::parse_string(args)?; 289 | trace!("user: {value}",); 290 | params.user = Some(value); 291 | } 292 | // -- unimplemented fields 293 | Field::AddKeysToAgent 294 | | Field::AddressFamily 295 | | Field::BatchMode 296 | | Field::CanonicalDomains 297 | | Field::CanonicalizeFallbackLock 298 | | Field::CanonicalizeHostname 299 | | Field::CanonicalizeMaxDots 300 | | Field::CanonicalizePermittedCNAMEs 301 | | Field::CheckHostIP 302 | | Field::ClearAllForwardings 303 | | Field::ControlMaster 304 | | Field::ControlPath 305 | | Field::ControlPersist 306 | | Field::DynamicForward 307 | | Field::EnableSSHKeysign 308 | | Field::EscapeChar 309 | | Field::ExitOnForwardFailure 310 | | Field::FingerprintHash 311 | | Field::ForkAfterAuthentication 312 | | Field::ForwardAgent 313 | | Field::ForwardX11 314 | | Field::ForwardX11Timeout 315 | | Field::ForwardX11Trusted 316 | | Field::GatewayPorts 317 | | Field::GlobalKnownHostsFile 318 | | Field::GSSAPIAuthentication 319 | | Field::GSSAPIDelegateCredentials 320 | | Field::HashKnownHosts 321 | | Field::HostbasedAcceptedAlgorithms 322 | | Field::HostbasedAuthentication 323 | | Field::HostKeyAlias 324 | | Field::HostbasedKeyTypes 325 | | Field::IdentitiesOnly 326 | | Field::IdentityAgent 327 | | Field::IPQoS 328 | | Field::KbdInteractiveAuthentication 329 | | Field::KbdInteractiveDevices 330 | | Field::KnownHostsCommand 331 | | Field::LocalCommand 332 | | Field::LocalForward 333 | | Field::LogLevel 334 | | Field::LogVerbose 335 | | Field::NoHostAuthenticationForLocalhost 336 | | Field::NumberOfPasswordPrompts 337 | | Field::PasswordAuthentication 338 | | Field::PermitLocalCommand 339 | | Field::PermitRemoteOpen 340 | | Field::PKCS11Provider 341 | | Field::PreferredAuthentications 342 | | Field::ProxyCommand 343 | | Field::ProxyJump 344 | | Field::ProxyUseFdpass 345 | | Field::PubkeyAcceptedKeyTypes 346 | | Field::RekeyLimit 347 | | Field::RequestTTY 348 | | Field::RevokedHostKeys 349 | | Field::SecruityKeyProvider 350 | | Field::SendEnv 351 | | Field::ServerAliveCountMax 352 | | Field::SessionType 353 | | Field::SetEnv 354 | | Field::StdinNull 355 | | Field::StreamLocalBindMask 356 | | Field::StrictHostKeyChecking 357 | | Field::SyslogFacility 358 | | Field::UpdateHostKeys 359 | | Field::UserKnownHostsFile 360 | | Field::VerifyHostKeyDNS 361 | | Field::VisualHostKey 362 | | Field::XAuthLocation => { 363 | return Err(SshParserError::UnsupportedField(field.to_string(), args)); 364 | } 365 | } 366 | Ok(()) 367 | } 368 | 369 | /// include a file by parsing it and updating host rules by merging the read config to the current one for the host 370 | fn include_files( 371 | args: Vec, 372 | host: &mut Host, 373 | rules: ParseRule, 374 | default_algos: &DefaultAlgorithms, 375 | ) -> SshParserResult<()> { 376 | let path_match = Self::parse_string(args)?; 377 | trace!("include files: {path_match}",); 378 | let files = glob(&path_match)?; 379 | 380 | for file in files { 381 | let file = file?; 382 | trace!("including file: {}", file.display()); 383 | let mut reader = BufReader::new(File::open(file)?); 384 | let mut sub_config = SshConfig::default().default_algorithms(default_algos.clone()); 385 | Self::parse(&mut sub_config, &mut reader, rules)?; 386 | 387 | // merge sub-config into host 388 | for pattern in &host.pattern { 389 | if pattern.negated { 390 | trace!("excluding sub-config for pattern: {pattern:?}",); 391 | continue; 392 | } 393 | trace!("merging sub-config for pattern: {pattern:?}",); 394 | let params = sub_config.query(&pattern.pattern); 395 | host.params.overwrite_if_none(¶ms); 396 | } 397 | } 398 | 399 | Ok(()) 400 | } 401 | 402 | /// Tokenize line if possible. Returns [`Field`] name and args as a [`Vec`] of [`String`]. 403 | /// 404 | /// All of these lines are valid for tokenization 405 | /// 406 | /// ```txt 407 | /// IgnoreUnknown=Pippo,Pluto 408 | /// ConnectTimeout = 15 409 | /// Ciphers "Pepperoni Pizza,Margherita Pizza,Hawaiian Pizza" 410 | /// Macs="Pasta Carbonara,Pasta con tonno" 411 | /// ``` 412 | /// 413 | /// So lines have syntax `field args...`, `field=args...`, `field "args"`, `field="args"` 414 | fn tokenize_line(line: &str) -> SshParserResult<(Field, Vec)> { 415 | // check what comes first, space or =? 416 | let trimmed_line = line.trim(); 417 | // first token is the field, and it may be separated either by a space or by '=' 418 | let (field, other_tokens) = if trimmed_line.find('=').unwrap_or(usize::MAX) 419 | < trimmed_line.find(char::is_whitespace).unwrap_or(usize::MAX) 420 | { 421 | trimmed_line 422 | .split_once('=') 423 | .ok_or(SshParserError::MissingArgument)? 424 | } else { 425 | trimmed_line 426 | .split_once(char::is_whitespace) 427 | .ok_or(SshParserError::MissingArgument)? 428 | }; 429 | 430 | trace!("tokenized line '{line}' - field '{field}' with args '{other_tokens}'",); 431 | 432 | // other tokens should trim = and whitespace 433 | let other_tokens = other_tokens.trim().trim_start_matches('=').trim(); 434 | trace!("other tokens trimmed: '{other_tokens}'",); 435 | 436 | // if args is quoted, don't split it 437 | let args = if other_tokens.starts_with('"') && other_tokens.ends_with('"') { 438 | trace!("quoted args: '{other_tokens}'",); 439 | vec![other_tokens[1..other_tokens.len() - 1].to_string()] 440 | } else { 441 | trace!("splitting args (non-quoted): '{other_tokens}'",); 442 | // split by whitespace 443 | let tokens = other_tokens.split_whitespace(); 444 | 445 | tokens 446 | .map(|x| x.trim().to_string()) 447 | .filter(|x| !x.is_empty()) 448 | .collect() 449 | }; 450 | 451 | match Field::from_str(field) { 452 | Ok(field) => Ok((field, args)), 453 | Err(_) => Err(SshParserError::UnknownField(field.to_string(), args)), 454 | } 455 | } 456 | 457 | // -- value parsers 458 | 459 | /// parse boolean value 460 | fn parse_boolean(args: Vec) -> SshParserResult { 461 | match args.first().map(|x| x.as_str()) { 462 | Some("yes") => Ok(true), 463 | Some("no") => Ok(false), 464 | Some(_) => Err(SshParserError::ExpectedBoolean), 465 | None => Err(SshParserError::MissingArgument), 466 | } 467 | } 468 | 469 | /// Parse algorithms argument 470 | fn parse_algos(args: Vec) -> SshParserResult { 471 | let first = args.first().ok_or(SshParserError::MissingArgument)?; 472 | 473 | AlgorithmsRule::from_str(first) 474 | } 475 | 476 | /// Parse comma separated list arguments 477 | fn parse_comma_separated_list(args: Vec) -> SshParserResult> { 478 | match args 479 | .first() 480 | .map(|x| x.split(',').map(|x| x.to_string()).collect()) 481 | { 482 | Some(args) => Ok(args), 483 | _ => Err(SshParserError::MissingArgument), 484 | } 485 | } 486 | 487 | /// Parse duration argument 488 | fn parse_duration(args: Vec) -> SshParserResult { 489 | let value = Self::parse_unsigned(args)?; 490 | Ok(Duration::from_secs(value as u64)) 491 | } 492 | 493 | /// Parse host argument 494 | fn parse_host(args: Vec) -> SshParserResult> { 495 | if args.is_empty() { 496 | return Err(SshParserError::MissingArgument); 497 | } 498 | // Collect hosts 499 | Ok(args 500 | .into_iter() 501 | .map(|x| { 502 | let tokens: Vec<&str> = x.split('!').collect(); 503 | if tokens.len() == 2 { 504 | HostClause::new(tokens[1].to_string(), true) 505 | } else { 506 | HostClause::new(tokens[0].to_string(), false) 507 | } 508 | }) 509 | .collect()) 510 | } 511 | 512 | /// Parse a list of paths 513 | fn parse_path_list(args: Vec) -> SshParserResult> { 514 | if args.is_empty() { 515 | return Err(SshParserError::MissingArgument); 516 | } 517 | args.iter() 518 | .map(|x| Self::parse_path_arg(x.as_str())) 519 | .collect() 520 | } 521 | 522 | /// Parse path argument 523 | fn parse_path(args: Vec) -> SshParserResult { 524 | if let Some(s) = args.first() { 525 | Self::parse_path_arg(s) 526 | } else { 527 | Err(SshParserError::MissingArgument) 528 | } 529 | } 530 | 531 | /// Parse path argument 532 | fn parse_path_arg(s: &str) -> SshParserResult { 533 | // Remove tilde 534 | let s = if s.starts_with('~') { 535 | let home_dir = dirs::home_dir() 536 | .unwrap_or_else(|| PathBuf::from("~")) 537 | .to_string_lossy() 538 | .to_string(); 539 | s.replacen('~', &home_dir, 1) 540 | } else { 541 | s.to_string() 542 | }; 543 | Ok(PathBuf::from(s)) 544 | } 545 | 546 | /// Parse port number argument 547 | fn parse_port(args: Vec) -> SshParserResult { 548 | match args.first().map(|x| u16::from_str(x)) { 549 | Some(Ok(val)) => Ok(val), 550 | Some(Err(_)) => Err(SshParserError::ExpectedPort), 551 | None => Err(SshParserError::MissingArgument), 552 | } 553 | } 554 | 555 | /// Parse string argument 556 | fn parse_string(args: Vec) -> SshParserResult { 557 | if let Some(s) = args.into_iter().next() { 558 | Ok(s) 559 | } else { 560 | Err(SshParserError::MissingArgument) 561 | } 562 | } 563 | 564 | /// Parse unsigned argument 565 | fn parse_unsigned(args: Vec) -> SshParserResult { 566 | match args.first().map(|x| usize::from_str(x)) { 567 | Some(Ok(val)) => Ok(val), 568 | Some(Err(_)) => Err(SshParserError::ExpectedUnsigned), 569 | None => Err(SshParserError::MissingArgument), 570 | } 571 | } 572 | } 573 | 574 | #[cfg(test)] 575 | mod test { 576 | 577 | use std::fs::File; 578 | use std::io::{BufReader, Write}; 579 | use std::path::Path; 580 | 581 | use pretty_assertions::assert_eq; 582 | use tempfile::NamedTempFile; 583 | 584 | use super::*; 585 | use crate::DefaultAlgorithms; 586 | 587 | #[test] 588 | fn should_parse_configuration() -> Result<(), SshParserError> { 589 | crate::test_log(); 590 | let temp = create_ssh_config(); 591 | let file = File::open(temp.path()).expect("Failed to open tempfile"); 592 | let mut reader = BufReader::new(file); 593 | let config = SshConfig::default() 594 | .default_algorithms(DefaultAlgorithms { 595 | ca_signature_algorithms: vec![], 596 | ciphers: vec![], 597 | host_key_algorithms: vec![], 598 | kex_algorithms: vec![], 599 | mac: vec![], 600 | pubkey_accepted_algorithms: vec!["omar-crypt".to_string()], 601 | }) 602 | .parse(&mut reader, ParseRule::STRICT)?; 603 | 604 | // Query openssh cmdline overrides (options preceding the first `Host` section, 605 | // overriding all following options) 606 | let params = config.query("*"); 607 | assert_eq!( 608 | params.ignore_unknown.as_deref().unwrap(), 609 | &["Pippo", "Pluto"] 610 | ); 611 | assert_eq!(params.compression.unwrap(), true); 612 | assert_eq!(params.connection_attempts.unwrap(), 10); 613 | assert_eq!(params.connect_timeout.unwrap(), Duration::from_secs(60)); 614 | assert_eq!( 615 | params.server_alive_interval.unwrap(), 616 | Duration::from_secs(40) 617 | ); 618 | assert_eq!(params.tcp_keep_alive.unwrap(), true); 619 | assert_eq!(params.ciphers.algorithms(), &["a-manella", "blowfish"]); 620 | assert_eq!( 621 | params.pubkey_accepted_algorithms.algorithms(), 622 | &["desu", "omar-crypt", "fast-omar-crypt"] 623 | ); 624 | 625 | // Query explicit all-hosts fallback options (`Host *`) 626 | assert_eq!(params.ca_signature_algorithms.algorithms(), &["random"]); 627 | assert_eq!( 628 | params.host_key_algorithms.algorithms(), 629 | &["luigi", "mario",] 630 | ); 631 | assert_eq!(params.kex_algorithms.algorithms(), &["desu", "gigi",]); 632 | assert_eq!(params.mac.algorithms(), &["concorde"]); 633 | assert!(params.bind_address.is_none()); 634 | 635 | // Query 172.26.104.4, yielding cmdline overrides, 636 | // explicit `Host 192.168.*.* 172.26.*.* !192.168.1.30` options, 637 | // and all-hosts fallback options. 638 | let params_172_26_104_4 = config.query("172.26.104.4"); 639 | 640 | // cmdline overrides 641 | assert_eq!(params_172_26_104_4.compression.unwrap(), true); 642 | assert_eq!(params_172_26_104_4.connection_attempts.unwrap(), 10); 643 | assert_eq!( 644 | params_172_26_104_4.connect_timeout.unwrap(), 645 | Duration::from_secs(60) 646 | ); 647 | assert_eq!(params_172_26_104_4.tcp_keep_alive.unwrap(), true); 648 | 649 | // all-hosts fallback options, merged with host-specific options 650 | assert_eq!( 651 | params_172_26_104_4.ca_signature_algorithms.algorithms(), 652 | &["random"] 653 | ); 654 | assert_eq!( 655 | params_172_26_104_4.ciphers.algorithms(), 656 | &["a-manella", "blowfish",] 657 | ); 658 | assert_eq!(params_172_26_104_4.mac.algorithms(), &["spyro", "deoxys"]); // use subconfig; defined before * macs 659 | assert_eq!( 660 | params_172_26_104_4 661 | .pubkey_accepted_algorithms 662 | .algorithms() 663 | .is_empty(), // should have removed omar-crypt 664 | true 665 | ); 666 | assert_eq!( 667 | params_172_26_104_4.bind_address.as_deref().unwrap(), 668 | "10.8.0.10" 669 | ); 670 | assert_eq!( 671 | params_172_26_104_4.bind_interface.as_deref().unwrap(), 672 | "tun0" 673 | ); 674 | assert_eq!(params_172_26_104_4.port.unwrap(), 2222); 675 | assert_eq!( 676 | params_172_26_104_4.identity_file.as_deref().unwrap(), 677 | vec![ 678 | Path::new("/home/root/.ssh/pippo.key"), 679 | Path::new("/home/root/.ssh/pluto.key") 680 | ] 681 | ); 682 | assert_eq!(params_172_26_104_4.user.as_deref().unwrap(), "omar"); 683 | 684 | // Query tostapane 685 | let params_tostapane = config.query("tostapane"); 686 | assert_eq!(params_tostapane.compression.unwrap(), true); // it takes the first value defined, which is `yes` 687 | assert_eq!(params_tostapane.connection_attempts.unwrap(), 10); 688 | assert_eq!( 689 | params_tostapane.connect_timeout.unwrap(), 690 | Duration::from_secs(60) 691 | ); 692 | assert_eq!(params_tostapane.tcp_keep_alive.unwrap(), true); 693 | assert_eq!(params_tostapane.remote_forward.unwrap(), 88); 694 | assert_eq!(params_tostapane.user.as_deref().unwrap(), "ciro-esposito"); 695 | 696 | // all-hosts fallback options 697 | assert_eq!( 698 | params_tostapane.ca_signature_algorithms.algorithms(), 699 | &["random"] 700 | ); 701 | assert_eq!( 702 | params_tostapane.ciphers.algorithms(), 703 | &["a-manella", "blowfish",] 704 | ); 705 | assert_eq!( 706 | params_tostapane.mac.algorithms(), 707 | vec!["spyro".to_string(), "deoxys".to_string(),] 708 | ); 709 | assert_eq!( 710 | params_tostapane.pubkey_accepted_algorithms.algorithms(), 711 | &["desu", "omar-crypt", "fast-omar-crypt"] 712 | ); 713 | 714 | // query 192.168.1.30 715 | let params_192_168_1_30 = config.query("192.168.1.30"); 716 | 717 | // host-specific options 718 | assert_eq!(params_192_168_1_30.user.as_deref().unwrap(), "nutellaro"); 719 | assert_eq!(params_192_168_1_30.remote_forward.unwrap(), 123); 720 | 721 | // cmdline overrides 722 | assert_eq!(params_192_168_1_30.compression.unwrap(), true); 723 | assert_eq!(params_192_168_1_30.connection_attempts.unwrap(), 10); 724 | assert_eq!( 725 | params_192_168_1_30.connect_timeout.unwrap(), 726 | Duration::from_secs(60) 727 | ); 728 | assert_eq!(params_192_168_1_30.tcp_keep_alive.unwrap(), true); 729 | 730 | // all-hosts fallback options 731 | assert_eq!( 732 | params_192_168_1_30.ca_signature_algorithms.algorithms(), 733 | &["random"] 734 | ); 735 | assert_eq!( 736 | params_192_168_1_30.ciphers.algorithms(), 737 | &["a-manella", "blowfish"] 738 | ); 739 | assert_eq!(params_192_168_1_30.mac.algorithms(), &["concorde"]); 740 | assert_eq!( 741 | params_192_168_1_30.pubkey_accepted_algorithms.algorithms(), 742 | &["desu", "omar-crypt", "fast-omar-crypt"] 743 | ); 744 | 745 | Ok(()) 746 | } 747 | 748 | #[test] 749 | fn should_allow_unknown_field() -> Result<(), SshParserError> { 750 | crate::test_log(); 751 | let temp = create_ssh_config_with_unknown_fields(); 752 | let file = File::open(temp.path()).expect("Failed to open tempfile"); 753 | let mut reader = BufReader::new(file); 754 | let _config = SshConfig::default() 755 | .default_algorithms(DefaultAlgorithms::empty()) 756 | .parse(&mut reader, ParseRule::ALLOW_UNKNOWN_FIELDS)?; 757 | 758 | Ok(()) 759 | } 760 | 761 | #[test] 762 | fn should_not_allow_unknown_field() { 763 | crate::test_log(); 764 | let temp = create_ssh_config_with_unknown_fields(); 765 | let file = File::open(temp.path()).expect("Failed to open tempfile"); 766 | let mut reader = BufReader::new(file); 767 | assert!(matches!( 768 | SshConfig::default() 769 | .default_algorithms(DefaultAlgorithms::empty()) 770 | .parse(&mut reader, ParseRule::STRICT) 771 | .unwrap_err(), 772 | SshParserError::UnknownField(..) 773 | )); 774 | } 775 | 776 | #[test] 777 | fn should_store_unknown_fields() { 778 | crate::test_log(); 779 | let temp = create_ssh_config_with_unknown_fields(); 780 | let file = File::open(temp.path()).expect("Failed to open tempfile"); 781 | let mut reader = BufReader::new(file); 782 | let config = SshConfig::default() 783 | .default_algorithms(DefaultAlgorithms::empty()) 784 | .parse(&mut reader, ParseRule::ALLOW_UNKNOWN_FIELDS) 785 | .unwrap(); 786 | 787 | let host = config.query("cross-platform"); 788 | assert_eq!( 789 | host.ignored_fields.get("Piropero").unwrap(), 790 | &vec![String::from("yes")] 791 | ); 792 | } 793 | 794 | #[test] 795 | fn should_parse_inversed_ssh_config() { 796 | crate::test_log(); 797 | let temp = create_inverted_ssh_config(); 798 | let file = File::open(temp.path()).expect("Failed to open tempfile"); 799 | let mut reader = BufReader::new(file); 800 | let config = SshConfig::default() 801 | .default_algorithms(DefaultAlgorithms::empty()) 802 | .parse(&mut reader, ParseRule::STRICT) 803 | .unwrap(); 804 | 805 | let home_dir = dirs::home_dir() 806 | .unwrap_or_else(|| PathBuf::from("~")) 807 | .to_string_lossy() 808 | .to_string(); 809 | 810 | let remote_host = config.query("remote-host"); 811 | 812 | // From `*-host` 813 | assert_eq!( 814 | remote_host.identity_file.unwrap()[0].as_path(), 815 | Path::new(format!("{home_dir}/.ssh/id_rsa_good").as_str()) // because it's the first in the file 816 | ); 817 | 818 | // From `remote-*` 819 | assert_eq!(remote_host.host_name.unwrap(), "hostname.com"); 820 | assert_eq!(remote_host.user.unwrap(), "user"); 821 | 822 | // From `*` 823 | assert_eq!( 824 | remote_host.connect_timeout.unwrap(), 825 | Duration::from_secs(15) 826 | ); 827 | } 828 | 829 | #[test] 830 | fn should_parse_configuration_with_hosts() { 831 | crate::test_log(); 832 | let temp = create_ssh_config_with_comments(); 833 | 834 | let file = File::open(temp.path()).expect("Failed to open tempfile"); 835 | let mut reader = BufReader::new(file); 836 | let config = SshConfig::default() 837 | .default_algorithms(DefaultAlgorithms::empty()) 838 | .parse(&mut reader, ParseRule::STRICT) 839 | .unwrap(); 840 | 841 | let hostname = config.query("cross-platform").host_name.unwrap(); 842 | assert_eq!(&hostname, "hostname.com"); 843 | 844 | assert!(config.query("this").host_name.is_none()); 845 | } 846 | 847 | #[test] 848 | fn should_update_host_bind_address() -> Result<(), SshParserError> { 849 | crate::test_log(); 850 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 851 | SshConfigParser::update_host( 852 | Field::BindAddress, 853 | vec![String::from("127.0.0.1")], 854 | &mut host, 855 | ParseRule::ALLOW_UNKNOWN_FIELDS, 856 | &DefaultAlgorithms::empty(), 857 | )?; 858 | assert_eq!(host.params.bind_address.as_deref().unwrap(), "127.0.0.1"); 859 | Ok(()) 860 | } 861 | 862 | #[test] 863 | fn should_update_host_bind_interface() -> Result<(), SshParserError> { 864 | crate::test_log(); 865 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 866 | SshConfigParser::update_host( 867 | Field::BindInterface, 868 | vec![String::from("aaa")], 869 | &mut host, 870 | ParseRule::ALLOW_UNKNOWN_FIELDS, 871 | &DefaultAlgorithms::empty(), 872 | )?; 873 | assert_eq!(host.params.bind_interface.as_deref().unwrap(), "aaa"); 874 | Ok(()) 875 | } 876 | 877 | #[test] 878 | fn should_update_host_ca_signature_algos() -> Result<(), SshParserError> { 879 | crate::test_log(); 880 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 881 | SshConfigParser::update_host( 882 | Field::CaSignatureAlgorithms, 883 | vec![String::from("a,b,c")], 884 | &mut host, 885 | ParseRule::ALLOW_UNKNOWN_FIELDS, 886 | &DefaultAlgorithms::empty(), 887 | )?; 888 | assert_eq!( 889 | host.params.ca_signature_algorithms.algorithms(), 890 | &["a", "b", "c"] 891 | ); 892 | Ok(()) 893 | } 894 | 895 | #[test] 896 | fn should_update_host_certificate_file() -> Result<(), SshParserError> { 897 | crate::test_log(); 898 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 899 | SshConfigParser::update_host( 900 | Field::CertificateFile, 901 | vec![String::from("/tmp/a.crt")], 902 | &mut host, 903 | ParseRule::ALLOW_UNKNOWN_FIELDS, 904 | &DefaultAlgorithms::empty(), 905 | )?; 906 | assert_eq!( 907 | host.params.certificate_file.as_deref().unwrap(), 908 | Path::new("/tmp/a.crt") 909 | ); 910 | Ok(()) 911 | } 912 | 913 | #[test] 914 | fn should_update_host_ciphers() -> Result<(), SshParserError> { 915 | crate::test_log(); 916 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 917 | SshConfigParser::update_host( 918 | Field::Ciphers, 919 | vec![String::from("a,b,c")], 920 | &mut host, 921 | ParseRule::ALLOW_UNKNOWN_FIELDS, 922 | &DefaultAlgorithms::empty(), 923 | )?; 924 | assert_eq!(host.params.ciphers.algorithms(), &["a", "b", "c"]); 925 | Ok(()) 926 | } 927 | 928 | #[test] 929 | fn should_update_host_compression() -> Result<(), SshParserError> { 930 | crate::test_log(); 931 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 932 | SshConfigParser::update_host( 933 | Field::Compression, 934 | vec![String::from("yes")], 935 | &mut host, 936 | ParseRule::ALLOW_UNKNOWN_FIELDS, 937 | &DefaultAlgorithms::empty(), 938 | )?; 939 | assert_eq!(host.params.compression.unwrap(), true); 940 | Ok(()) 941 | } 942 | 943 | #[test] 944 | fn should_update_host_connection_attempts() -> Result<(), SshParserError> { 945 | crate::test_log(); 946 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 947 | SshConfigParser::update_host( 948 | Field::ConnectionAttempts, 949 | vec![String::from("4")], 950 | &mut host, 951 | ParseRule::ALLOW_UNKNOWN_FIELDS, 952 | &DefaultAlgorithms::empty(), 953 | )?; 954 | assert_eq!(host.params.connection_attempts.unwrap(), 4); 955 | Ok(()) 956 | } 957 | 958 | #[test] 959 | fn should_update_host_connection_timeout() -> Result<(), SshParserError> { 960 | crate::test_log(); 961 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 962 | SshConfigParser::update_host( 963 | Field::ConnectTimeout, 964 | vec![String::from("10")], 965 | &mut host, 966 | ParseRule::ALLOW_UNKNOWN_FIELDS, 967 | &DefaultAlgorithms::empty(), 968 | )?; 969 | assert_eq!( 970 | host.params.connect_timeout.unwrap(), 971 | Duration::from_secs(10) 972 | ); 973 | Ok(()) 974 | } 975 | 976 | #[test] 977 | fn should_update_host_key_algorithms() -> Result<(), SshParserError> { 978 | crate::test_log(); 979 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 980 | SshConfigParser::update_host( 981 | Field::HostKeyAlgorithms, 982 | vec![String::from("a,b,c")], 983 | &mut host, 984 | ParseRule::ALLOW_UNKNOWN_FIELDS, 985 | &DefaultAlgorithms::empty(), 986 | )?; 987 | assert_eq!( 988 | host.params.host_key_algorithms.algorithms(), 989 | &["a", "b", "c"] 990 | ); 991 | Ok(()) 992 | } 993 | 994 | #[test] 995 | fn should_update_host_host_name() -> Result<(), SshParserError> { 996 | crate::test_log(); 997 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 998 | SshConfigParser::update_host( 999 | Field::HostName, 1000 | vec![String::from("192.168.1.1")], 1001 | &mut host, 1002 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1003 | &DefaultAlgorithms::empty(), 1004 | )?; 1005 | assert_eq!(host.params.host_name.as_deref().unwrap(), "192.168.1.1"); 1006 | Ok(()) 1007 | } 1008 | 1009 | #[test] 1010 | fn should_update_host_ignore_unknown() -> Result<(), SshParserError> { 1011 | crate::test_log(); 1012 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1013 | SshConfigParser::update_host( 1014 | Field::IgnoreUnknown, 1015 | vec![String::from("a,b,c")], 1016 | &mut host, 1017 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1018 | &DefaultAlgorithms::empty(), 1019 | )?; 1020 | assert_eq!( 1021 | host.params.ignore_unknown.as_deref().unwrap(), 1022 | &["a", "b", "c"] 1023 | ); 1024 | Ok(()) 1025 | } 1026 | 1027 | #[test] 1028 | fn should_update_kex_algorithms() -> Result<(), SshParserError> { 1029 | crate::test_log(); 1030 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1031 | SshConfigParser::update_host( 1032 | Field::KexAlgorithms, 1033 | vec![String::from("a,b,c")], 1034 | &mut host, 1035 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1036 | &DefaultAlgorithms::empty(), 1037 | )?; 1038 | assert_eq!(host.params.kex_algorithms.algorithms(), &["a", "b", "c"]); 1039 | Ok(()) 1040 | } 1041 | 1042 | #[test] 1043 | fn should_update_host_mac() -> Result<(), SshParserError> { 1044 | crate::test_log(); 1045 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1046 | SshConfigParser::update_host( 1047 | Field::Mac, 1048 | vec![String::from("a,b,c")], 1049 | &mut host, 1050 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1051 | &DefaultAlgorithms::empty(), 1052 | )?; 1053 | assert_eq!(host.params.mac.algorithms(), &["a", "b", "c"]); 1054 | Ok(()) 1055 | } 1056 | 1057 | #[test] 1058 | fn should_update_host_port() -> Result<(), SshParserError> { 1059 | crate::test_log(); 1060 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1061 | SshConfigParser::update_host( 1062 | Field::Port, 1063 | vec![String::from("2222")], 1064 | &mut host, 1065 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1066 | &DefaultAlgorithms::empty(), 1067 | )?; 1068 | assert_eq!(host.params.port.unwrap(), 2222); 1069 | Ok(()) 1070 | } 1071 | 1072 | #[test] 1073 | fn should_update_host_pubkey_accepted_algos() -> Result<(), SshParserError> { 1074 | crate::test_log(); 1075 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1076 | SshConfigParser::update_host( 1077 | Field::PubkeyAcceptedAlgorithms, 1078 | vec![String::from("a,b,c")], 1079 | &mut host, 1080 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1081 | &DefaultAlgorithms::empty(), 1082 | )?; 1083 | assert_eq!( 1084 | host.params.pubkey_accepted_algorithms.algorithms(), 1085 | &["a", "b", "c"] 1086 | ); 1087 | Ok(()) 1088 | } 1089 | 1090 | #[test] 1091 | fn should_update_host_pubkey_authentication() -> Result<(), SshParserError> { 1092 | crate::test_log(); 1093 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1094 | SshConfigParser::update_host( 1095 | Field::PubkeyAuthentication, 1096 | vec![String::from("yes")], 1097 | &mut host, 1098 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1099 | &DefaultAlgorithms::empty(), 1100 | )?; 1101 | assert_eq!(host.params.pubkey_authentication.unwrap(), true); 1102 | Ok(()) 1103 | } 1104 | 1105 | #[test] 1106 | fn should_update_host_remote_forward() -> Result<(), SshParserError> { 1107 | crate::test_log(); 1108 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1109 | SshConfigParser::update_host( 1110 | Field::RemoteForward, 1111 | vec![String::from("3005")], 1112 | &mut host, 1113 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1114 | &DefaultAlgorithms::empty(), 1115 | )?; 1116 | assert_eq!(host.params.remote_forward.unwrap(), 3005); 1117 | Ok(()) 1118 | } 1119 | 1120 | #[test] 1121 | fn should_update_host_server_alive_interval() -> Result<(), SshParserError> { 1122 | crate::test_log(); 1123 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1124 | SshConfigParser::update_host( 1125 | Field::ServerAliveInterval, 1126 | vec![String::from("40")], 1127 | &mut host, 1128 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1129 | &DefaultAlgorithms::empty(), 1130 | )?; 1131 | assert_eq!( 1132 | host.params.server_alive_interval.unwrap(), 1133 | Duration::from_secs(40) 1134 | ); 1135 | Ok(()) 1136 | } 1137 | 1138 | #[test] 1139 | fn should_update_host_tcp_keep_alive() -> Result<(), SshParserError> { 1140 | crate::test_log(); 1141 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1142 | SshConfigParser::update_host( 1143 | Field::TcpKeepAlive, 1144 | vec![String::from("no")], 1145 | &mut host, 1146 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1147 | &DefaultAlgorithms::empty(), 1148 | )?; 1149 | assert_eq!(host.params.tcp_keep_alive.unwrap(), false); 1150 | Ok(()) 1151 | } 1152 | 1153 | #[test] 1154 | fn should_update_host_user() -> Result<(), SshParserError> { 1155 | crate::test_log(); 1156 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1157 | SshConfigParser::update_host( 1158 | Field::User, 1159 | vec![String::from("pippo")], 1160 | &mut host, 1161 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1162 | &DefaultAlgorithms::empty(), 1163 | )?; 1164 | assert_eq!(host.params.user.as_deref().unwrap(), "pippo"); 1165 | Ok(()) 1166 | } 1167 | 1168 | #[test] 1169 | fn should_not_update_host_if_unknown() -> Result<(), SshParserError> { 1170 | crate::test_log(); 1171 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1172 | let result = SshConfigParser::update_host( 1173 | Field::AddKeysToAgent, 1174 | vec![String::from("yes")], 1175 | &mut host, 1176 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1177 | &DefaultAlgorithms::empty(), 1178 | ); 1179 | 1180 | match result { 1181 | Ok(()) | Err(SshParserError::UnsupportedField(_, _)) => Ok(()), 1182 | e => e, 1183 | }?; 1184 | 1185 | assert_eq!(host.params, HostParams::new(&DefaultAlgorithms::empty())); 1186 | Ok(()) 1187 | } 1188 | 1189 | #[test] 1190 | fn should_update_host_if_unsupported() -> Result<(), SshParserError> { 1191 | crate::test_log(); 1192 | let mut host = Host::new(vec![], HostParams::new(&DefaultAlgorithms::empty())); 1193 | let result = SshConfigParser::update_host( 1194 | Field::AddKeysToAgent, 1195 | vec![String::from("yes")], 1196 | &mut host, 1197 | ParseRule::ALLOW_UNKNOWN_FIELDS, 1198 | &DefaultAlgorithms::empty(), 1199 | ); 1200 | 1201 | match result { 1202 | Err(SshParserError::UnsupportedField(field, _)) => { 1203 | assert_eq!(field, "addkeystoagent"); 1204 | Ok(()) 1205 | } 1206 | e => e, 1207 | }?; 1208 | 1209 | assert_eq!(host.params, HostParams::new(&DefaultAlgorithms::empty())); 1210 | Ok(()) 1211 | } 1212 | 1213 | #[test] 1214 | fn should_tokenize_line() -> Result<(), SshParserError> { 1215 | crate::test_log(); 1216 | assert_eq!( 1217 | SshConfigParser::tokenize_line("HostName 192.168.*.* 172.26.*.*")?, 1218 | ( 1219 | Field::HostName, 1220 | vec![String::from("192.168.*.*"), String::from("172.26.*.*")] 1221 | ) 1222 | ); 1223 | // Tokenize line with spaces 1224 | assert_eq!( 1225 | SshConfigParser::tokenize_line( 1226 | " HostName 192.168.*.* 172.26.*.* " 1227 | )?, 1228 | ( 1229 | Field::HostName, 1230 | vec![String::from("192.168.*.*"), String::from("172.26.*.*")] 1231 | ) 1232 | ); 1233 | Ok(()) 1234 | } 1235 | 1236 | #[test] 1237 | fn should_not_tokenize_line() { 1238 | crate::test_log(); 1239 | assert!(matches!( 1240 | SshConfigParser::tokenize_line("Omar yes").unwrap_err(), 1241 | SshParserError::UnknownField(..) 1242 | )); 1243 | } 1244 | 1245 | #[test] 1246 | fn should_fail_parsing_field() { 1247 | crate::test_log(); 1248 | 1249 | assert!(matches!( 1250 | SshConfigParser::tokenize_line(" ").unwrap_err(), 1251 | SshParserError::MissingArgument 1252 | )); 1253 | } 1254 | 1255 | #[test] 1256 | fn should_parse_boolean() -> Result<(), SshParserError> { 1257 | crate::test_log(); 1258 | assert_eq!( 1259 | SshConfigParser::parse_boolean(vec![String::from("yes")])?, 1260 | true 1261 | ); 1262 | assert_eq!( 1263 | SshConfigParser::parse_boolean(vec![String::from("no")])?, 1264 | false 1265 | ); 1266 | Ok(()) 1267 | } 1268 | 1269 | #[test] 1270 | fn should_fail_parsing_boolean() { 1271 | crate::test_log(); 1272 | assert!(matches!( 1273 | SshConfigParser::parse_boolean(vec!["boh".to_string()]).unwrap_err(), 1274 | SshParserError::ExpectedBoolean 1275 | )); 1276 | assert!(matches!( 1277 | SshConfigParser::parse_boolean(vec![]).unwrap_err(), 1278 | SshParserError::MissingArgument 1279 | )); 1280 | } 1281 | 1282 | #[test] 1283 | fn should_parse_algos() -> Result<(), SshParserError> { 1284 | crate::test_log(); 1285 | assert_eq!( 1286 | SshConfigParser::parse_algos(vec![String::from("a,b,c,d")])?, 1287 | AlgorithmsRule::Set(vec![ 1288 | "a".to_string(), 1289 | "b".to_string(), 1290 | "c".to_string(), 1291 | "d".to_string(), 1292 | ]) 1293 | ); 1294 | 1295 | assert_eq!( 1296 | SshConfigParser::parse_algos(vec![String::from("a")])?, 1297 | AlgorithmsRule::Set(vec!["a".to_string()]) 1298 | ); 1299 | 1300 | assert_eq!( 1301 | SshConfigParser::parse_algos(vec![String::from("+a,b")])?, 1302 | AlgorithmsRule::Append(vec!["a".to_string(), "b".to_string()]) 1303 | ); 1304 | 1305 | Ok(()) 1306 | } 1307 | 1308 | #[test] 1309 | fn should_parse_comma_separated_list() -> Result<(), SshParserError> { 1310 | crate::test_log(); 1311 | assert_eq!( 1312 | SshConfigParser::parse_comma_separated_list(vec![String::from("a,b,c,d")])?, 1313 | vec![ 1314 | "a".to_string(), 1315 | "b".to_string(), 1316 | "c".to_string(), 1317 | "d".to_string(), 1318 | ] 1319 | ); 1320 | assert_eq!( 1321 | SshConfigParser::parse_comma_separated_list(vec![String::from("a")])?, 1322 | vec!["a".to_string()] 1323 | ); 1324 | Ok(()) 1325 | } 1326 | 1327 | #[test] 1328 | fn should_fail_parsing_comma_separated_list() { 1329 | crate::test_log(); 1330 | assert!(matches!( 1331 | SshConfigParser::parse_comma_separated_list(vec![]).unwrap_err(), 1332 | SshParserError::MissingArgument 1333 | )); 1334 | } 1335 | 1336 | #[test] 1337 | fn should_parse_duration() -> Result<(), SshParserError> { 1338 | crate::test_log(); 1339 | assert_eq!( 1340 | SshConfigParser::parse_duration(vec![String::from("60")])?, 1341 | Duration::from_secs(60) 1342 | ); 1343 | Ok(()) 1344 | } 1345 | 1346 | #[test] 1347 | fn should_fail_parsing_duration() { 1348 | crate::test_log(); 1349 | assert!(matches!( 1350 | SshConfigParser::parse_duration(vec![String::from("AAA")]).unwrap_err(), 1351 | SshParserError::ExpectedUnsigned 1352 | )); 1353 | assert!(matches!( 1354 | SshConfigParser::parse_duration(vec![]).unwrap_err(), 1355 | SshParserError::MissingArgument 1356 | )); 1357 | } 1358 | 1359 | #[test] 1360 | fn should_parse_host() -> Result<(), SshParserError> { 1361 | crate::test_log(); 1362 | assert_eq!( 1363 | SshConfigParser::parse_host(vec![ 1364 | String::from("192.168.*.*"), 1365 | String::from("!192.168.1.1"), 1366 | String::from("172.26.104.*"), 1367 | String::from("!172.26.104.10"), 1368 | ])?, 1369 | vec![ 1370 | HostClause::new(String::from("192.168.*.*"), false), 1371 | HostClause::new(String::from("192.168.1.1"), true), 1372 | HostClause::new(String::from("172.26.104.*"), false), 1373 | HostClause::new(String::from("172.26.104.10"), true), 1374 | ] 1375 | ); 1376 | Ok(()) 1377 | } 1378 | 1379 | #[test] 1380 | fn should_fail_parsing_host() { 1381 | crate::test_log(); 1382 | assert!(matches!( 1383 | SshConfigParser::parse_host(vec![]).unwrap_err(), 1384 | SshParserError::MissingArgument 1385 | )); 1386 | } 1387 | 1388 | #[test] 1389 | fn should_parse_path() -> Result<(), SshParserError> { 1390 | crate::test_log(); 1391 | assert_eq!( 1392 | SshConfigParser::parse_path(vec![String::from("/tmp/a.txt")])?, 1393 | PathBuf::from("/tmp/a.txt") 1394 | ); 1395 | Ok(()) 1396 | } 1397 | 1398 | #[test] 1399 | fn should_parse_path_and_resolve_tilde() -> Result<(), SshParserError> { 1400 | crate::test_log(); 1401 | let mut expected = dirs::home_dir().unwrap(); 1402 | expected.push(".ssh/id_dsa"); 1403 | assert_eq!( 1404 | SshConfigParser::parse_path(vec![String::from("~/.ssh/id_dsa")])?, 1405 | expected 1406 | ); 1407 | Ok(()) 1408 | } 1409 | 1410 | #[test] 1411 | fn should_parse_path_list() -> Result<(), SshParserError> { 1412 | crate::test_log(); 1413 | assert_eq!( 1414 | SshConfigParser::parse_path_list(vec![ 1415 | String::from("/tmp/a.txt"), 1416 | String::from("/tmp/b.txt") 1417 | ])?, 1418 | vec![PathBuf::from("/tmp/a.txt"), PathBuf::from("/tmp/b.txt")] 1419 | ); 1420 | Ok(()) 1421 | } 1422 | 1423 | #[test] 1424 | fn should_fail_parse_path_list() { 1425 | crate::test_log(); 1426 | assert!(matches!( 1427 | SshConfigParser::parse_path_list(vec![]).unwrap_err(), 1428 | SshParserError::MissingArgument 1429 | )); 1430 | } 1431 | 1432 | #[test] 1433 | fn should_fail_parsing_path() { 1434 | crate::test_log(); 1435 | assert!(matches!( 1436 | SshConfigParser::parse_path(vec![]).unwrap_err(), 1437 | SshParserError::MissingArgument 1438 | )); 1439 | } 1440 | 1441 | #[test] 1442 | fn should_parse_port() -> Result<(), SshParserError> { 1443 | crate::test_log(); 1444 | assert_eq!(SshConfigParser::parse_port(vec![String::from("22")])?, 22); 1445 | Ok(()) 1446 | } 1447 | 1448 | #[test] 1449 | fn should_fail_parsing_port() { 1450 | crate::test_log(); 1451 | assert!(matches!( 1452 | SshConfigParser::parse_port(vec![String::from("1234567")]).unwrap_err(), 1453 | SshParserError::ExpectedPort 1454 | )); 1455 | assert!(matches!( 1456 | SshConfigParser::parse_port(vec![]).unwrap_err(), 1457 | SshParserError::MissingArgument 1458 | )); 1459 | } 1460 | 1461 | #[test] 1462 | fn should_parse_string() -> Result<(), SshParserError> { 1463 | crate::test_log(); 1464 | assert_eq!( 1465 | SshConfigParser::parse_string(vec![String::from("foobar")])?, 1466 | String::from("foobar") 1467 | ); 1468 | Ok(()) 1469 | } 1470 | 1471 | #[test] 1472 | fn should_fail_parsing_string() { 1473 | crate::test_log(); 1474 | assert!(matches!( 1475 | SshConfigParser::parse_string(vec![]).unwrap_err(), 1476 | SshParserError::MissingArgument 1477 | )); 1478 | } 1479 | 1480 | #[test] 1481 | fn should_parse_unsigned() -> Result<(), SshParserError> { 1482 | crate::test_log(); 1483 | assert_eq!( 1484 | SshConfigParser::parse_unsigned(vec![String::from("43")])?, 1485 | 43 1486 | ); 1487 | Ok(()) 1488 | } 1489 | 1490 | #[test] 1491 | fn should_fail_parsing_unsigned() { 1492 | crate::test_log(); 1493 | assert!(matches!( 1494 | SshConfigParser::parse_unsigned(vec![String::from("abc")]).unwrap_err(), 1495 | SshParserError::ExpectedUnsigned 1496 | )); 1497 | assert!(matches!( 1498 | SshConfigParser::parse_unsigned(vec![]).unwrap_err(), 1499 | SshParserError::MissingArgument 1500 | )); 1501 | } 1502 | 1503 | #[test] 1504 | fn should_strip_comments() { 1505 | crate::test_log(); 1506 | 1507 | assert_eq!( 1508 | SshConfigParser::strip_comments("host my_host # this is my fav host").as_str(), 1509 | "host my_host " 1510 | ); 1511 | assert_eq!( 1512 | SshConfigParser::strip_comments("# this is a comment").as_str(), 1513 | "" 1514 | ); 1515 | } 1516 | 1517 | #[test] 1518 | fn test_should_parse_config_with_quotes_and_eq() { 1519 | crate::test_log(); 1520 | 1521 | let config = create_ssh_config_with_quotes_and_eq(); 1522 | let file = File::open(config.path()).expect("Failed to open tempfile"); 1523 | let mut reader = BufReader::new(file); 1524 | 1525 | let config = SshConfig::default() 1526 | .default_algorithms(DefaultAlgorithms::empty()) 1527 | .parse(&mut reader, ParseRule::STRICT) 1528 | .expect("Failed to parse config"); 1529 | 1530 | let params = config.query("foo"); 1531 | 1532 | // connect timeout is 15 1533 | assert_eq!( 1534 | params.connect_timeout.expect("unspec connect timeout"), 1535 | Duration::from_secs(15) 1536 | ); 1537 | assert_eq!( 1538 | params 1539 | .ignore_unknown 1540 | .as_deref() 1541 | .expect("unspec ignore unknown"), 1542 | &["Pippo", "Pluto"] 1543 | ); 1544 | assert_eq!( 1545 | params 1546 | .ciphers 1547 | .algorithms() 1548 | .iter() 1549 | .map(|x| x.as_str()) 1550 | .collect::>(), 1551 | &["Pepperoni Pizza", "Margherita Pizza", "Hawaiian Pizza"] 1552 | ); 1553 | assert_eq!( 1554 | params 1555 | .mac 1556 | .algorithms() 1557 | .iter() 1558 | .map(|x| x.as_str()) 1559 | .collect::>(), 1560 | &["Pasta Carbonara", "Pasta con tonno"] 1561 | ); 1562 | } 1563 | 1564 | fn create_ssh_config_with_quotes_and_eq() -> NamedTempFile { 1565 | let mut tmpfile: tempfile::NamedTempFile = 1566 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1567 | let config = r##" 1568 | # ssh config 1569 | # written by veeso 1570 | 1571 | 1572 | # I put a comment here just to annoy 1573 | 1574 | IgnoreUnknown=Pippo,Pluto 1575 | ConnectTimeout = 15 1576 | Ciphers "Pepperoni Pizza,Margherita Pizza,Hawaiian Pizza" 1577 | Macs="Pasta Carbonara,Pasta con tonno" 1578 | "##; 1579 | tmpfile.write_all(config.as_bytes()).unwrap(); 1580 | tmpfile 1581 | } 1582 | 1583 | fn create_ssh_config() -> NamedTempFile { 1584 | let mut tmpfile: tempfile::NamedTempFile = 1585 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1586 | let config = r##" 1587 | # ssh config 1588 | # written by veeso 1589 | 1590 | 1591 | # I put a comment here just to annoy 1592 | 1593 | IgnoreUnknown Pippo,Pluto 1594 | 1595 | Compression yes 1596 | ConnectionAttempts 10 1597 | ConnectTimeout 60 1598 | ServerAliveInterval 40 1599 | TcpKeepAlive yes 1600 | Ciphers +a-manella,blowfish 1601 | 1602 | # Let's start defining some hosts 1603 | 1604 | Host 192.168.*.* 172.26.*.* !192.168.1.30 1605 | User omar 1606 | # Forward agent is actually not supported; I just want to see that it wont' fail parsing 1607 | ForwardAgent yes 1608 | BindAddress 10.8.0.10 1609 | BindInterface tun0 1610 | Ciphers +coi-piedi,cazdecan,triestin-stretto 1611 | IdentityFile /home/root/.ssh/pippo.key /home/root/.ssh/pluto.key 1612 | Macs spyro,deoxys 1613 | Port 2222 1614 | PubkeyAcceptedAlgorithms -omar-crypt 1615 | 1616 | Host tostapane 1617 | User ciro-esposito 1618 | HostName 192.168.24.32 1619 | RemoteForward 88 1620 | Compression no 1621 | Pippo yes 1622 | Pluto 56 1623 | Macs +spyro,deoxys 1624 | 1625 | Host 192.168.1.30 1626 | User nutellaro 1627 | RemoteForward 123 1628 | 1629 | Host * 1630 | CaSignatureAlgorithms random 1631 | HostKeyAlgorithms luigi,mario 1632 | KexAlgorithms desu,gigi 1633 | Macs concorde 1634 | PubkeyAcceptedAlgorithms desu,omar-crypt,fast-omar-crypt 1635 | "##; 1636 | tmpfile.write_all(config.as_bytes()).unwrap(); 1637 | tmpfile 1638 | } 1639 | 1640 | fn create_inverted_ssh_config() -> NamedTempFile { 1641 | let mut tmpfile: tempfile::NamedTempFile = 1642 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1643 | let config = r##" 1644 | Host *-host 1645 | IdentityFile ~/.ssh/id_rsa_good 1646 | 1647 | Host remote-* 1648 | HostName hostname.com 1649 | User user 1650 | IdentityFile ~/.ssh/id_rsa_bad 1651 | 1652 | Host * 1653 | ConnectTimeout 15 1654 | IdentityFile ~/.ssh/id_rsa_ugly 1655 | "##; 1656 | tmpfile.write_all(config.as_bytes()).unwrap(); 1657 | tmpfile 1658 | } 1659 | 1660 | fn create_ssh_config_with_comments() -> NamedTempFile { 1661 | let mut tmpfile: tempfile::NamedTempFile = 1662 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1663 | let config = r##" 1664 | Host cross-platform # this is my fav host 1665 | HostName hostname.com 1666 | User user 1667 | IdentityFile ~/.ssh/id_rsa_good 1668 | 1669 | Host * 1670 | AddKeysToAgent yes 1671 | IdentityFile ~/.ssh/id_rsa_bad 1672 | "##; 1673 | tmpfile.write_all(config.as_bytes()).unwrap(); 1674 | tmpfile 1675 | } 1676 | 1677 | fn create_ssh_config_with_unknown_fields() -> NamedTempFile { 1678 | let mut tmpfile: tempfile::NamedTempFile = 1679 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1680 | let config = r##" 1681 | Host cross-platform # this is my fav host 1682 | HostName hostname.com 1683 | User user 1684 | IdentityFile ~/.ssh/id_rsa_good 1685 | Piropero yes 1686 | 1687 | Host * 1688 | AddKeysToAgent yes 1689 | IdentityFile ~/.ssh/id_rsa_bad 1690 | "##; 1691 | tmpfile.write_all(config.as_bytes()).unwrap(); 1692 | tmpfile 1693 | } 1694 | 1695 | #[test] 1696 | fn test_should_parse_config_with_include() { 1697 | crate::test_log(); 1698 | 1699 | let config = create_include_config(); 1700 | let file = File::open(config.config.path()).expect("Failed to open tempfile"); 1701 | let mut reader = BufReader::new(file); 1702 | 1703 | let config = SshConfig::default() 1704 | .default_algorithms(DefaultAlgorithms::empty()) 1705 | .parse(&mut reader, ParseRule::STRICT) 1706 | .expect("Failed to parse config"); 1707 | 1708 | // verify include 1 overwrites the default value 1709 | let glob_params = config.query("192.168.1.1"); 1710 | assert_eq!( 1711 | glob_params.connect_timeout.unwrap(), 1712 | Duration::from_secs(60) 1713 | ); 1714 | assert_eq!( 1715 | glob_params.server_alive_interval.unwrap(), 1716 | Duration::from_secs(40) // first read 1717 | ); 1718 | assert_eq!(glob_params.tcp_keep_alive.unwrap(), true); 1719 | assert_eq!(glob_params.ciphers.algorithms().is_empty(), true); 1720 | 1721 | // verify tostapane 1722 | let tostapane_params = config.query("tostapane"); 1723 | assert_eq!( 1724 | tostapane_params.connect_timeout.unwrap(), 1725 | Duration::from_secs(60) // first read 1726 | ); 1727 | assert_eq!( 1728 | tostapane_params.server_alive_interval.unwrap(), 1729 | Duration::from_secs(40) // first read 1730 | ); 1731 | assert_eq!(tostapane_params.tcp_keep_alive.unwrap(), true); 1732 | // verify ciphers 1733 | assert_eq!( 1734 | tostapane_params.ciphers.algorithms(), 1735 | &[ 1736 | "a-manella", 1737 | "blowfish", 1738 | "coi-piedi", 1739 | "cazdecan", 1740 | "triestin-stretto" 1741 | ] 1742 | ); 1743 | } 1744 | 1745 | #[allow(dead_code)] 1746 | struct ConfigWithInclude { 1747 | config: NamedTempFile, 1748 | inc1: NamedTempFile, 1749 | inc2: NamedTempFile, 1750 | } 1751 | 1752 | fn create_include_config() -> ConfigWithInclude { 1753 | let mut config_file: tempfile::NamedTempFile = 1754 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1755 | let mut inc1_file: tempfile::NamedTempFile = 1756 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1757 | let mut inc2_file: tempfile::NamedTempFile = 1758 | tempfile::NamedTempFile::new().expect("Failed to create tempfile"); 1759 | 1760 | let config = format!( 1761 | r##" 1762 | # ssh config 1763 | # written by veeso 1764 | 1765 | 1766 | # I put a comment here just to annoy 1767 | 1768 | IgnoreUnknown Pippo,Pluto 1769 | 1770 | Compression yes 1771 | ConnectionAttempts 10 1772 | ConnectTimeout 60 1773 | ServerAliveInterval 40 1774 | Include {inc1} 1775 | 1776 | # Let's start defining some hosts 1777 | 1778 | Host tostapane 1779 | User ciro-esposito 1780 | HostName 192.168.24.32 1781 | RemoteForward 88 1782 | Compression no 1783 | Pippo yes 1784 | Pluto 56 1785 | Include {inc2} 1786 | "##, 1787 | inc1 = inc1_file.path().display(), 1788 | inc2 = inc2_file.path().display() 1789 | ); 1790 | config_file.write_all(config.as_bytes()).unwrap(); 1791 | 1792 | // write include 1 1793 | let inc1 = r##" 1794 | ConnectTimeout 60 1795 | ServerAliveInterval 60 1796 | TcpKeepAlive yes 1797 | "##; 1798 | inc1_file.write_all(inc1.as_bytes()).unwrap(); 1799 | 1800 | // write include 2 1801 | let inc2 = r##" 1802 | ConnectTimeout 180 1803 | ServerAliveInterval 180 1804 | Ciphers +a-manella,blowfish,coi-piedi,cazdecan,triestin-stretto 1805 | "##; 1806 | inc2_file.write_all(inc2.as_bytes()).unwrap(); 1807 | 1808 | ConfigWithInclude { 1809 | config: config_file, 1810 | inc1: inc1_file, 1811 | inc2: inc2_file, 1812 | } 1813 | } 1814 | } 1815 | -------------------------------------------------------------------------------- /src/parser/field.rs: -------------------------------------------------------------------------------- 1 | //! # field 2 | //! 3 | //! Ssh config fields 4 | 5 | use std::fmt; 6 | use std::str::FromStr; 7 | 8 | /// Configuration field. 9 | /// This enum defines ALL THE SUPPORTED fields in ssh config, 10 | /// as described at . 11 | /// Only a few of them are implemented, as described in `HostParams` struct. 12 | #[derive(Debug, Eq, PartialEq)] 13 | pub enum Field { 14 | Host, 15 | BindAddress, 16 | BindInterface, 17 | CaSignatureAlgorithms, 18 | CertificateFile, 19 | Ciphers, 20 | Compression, 21 | ConnectionAttempts, 22 | ConnectTimeout, 23 | HostKeyAlgorithms, 24 | HostName, 25 | IdentityFile, 26 | IgnoreUnknown, 27 | KexAlgorithms, 28 | Mac, 29 | Port, 30 | PubkeyAcceptedAlgorithms, 31 | PubkeyAuthentication, 32 | RemoteForward, 33 | ServerAliveInterval, 34 | TcpKeepAlive, 35 | #[cfg(target_os = "macos")] 36 | UseKeychain, 37 | User, 38 | // -- not implemented 39 | AddKeysToAgent, 40 | AddressFamily, 41 | BatchMode, 42 | CanonicalDomains, 43 | CanonicalizeFallbackLock, 44 | CanonicalizeHostname, 45 | CanonicalizeMaxDots, 46 | CanonicalizePermittedCNAMEs, 47 | CheckHostIP, 48 | ClearAllForwardings, 49 | ControlMaster, 50 | ControlPath, 51 | ControlPersist, 52 | DynamicForward, 53 | EnableSSHKeysign, 54 | EscapeChar, 55 | ExitOnForwardFailure, 56 | FingerprintHash, 57 | ForkAfterAuthentication, 58 | ForwardAgent, 59 | ForwardX11, 60 | ForwardX11Timeout, 61 | ForwardX11Trusted, 62 | GatewayPorts, 63 | GlobalKnownHostsFile, 64 | GSSAPIAuthentication, 65 | GSSAPIDelegateCredentials, 66 | HashKnownHosts, 67 | HostbasedAcceptedAlgorithms, 68 | HostbasedAuthentication, 69 | HostbasedKeyTypes, 70 | HostKeyAlias, 71 | IdentitiesOnly, 72 | IdentityAgent, 73 | Include, 74 | IPQoS, 75 | KbdInteractiveAuthentication, 76 | KbdInteractiveDevices, 77 | KnownHostsCommand, 78 | LocalCommand, 79 | LocalForward, 80 | LogLevel, 81 | LogVerbose, 82 | NoHostAuthenticationForLocalhost, 83 | NumberOfPasswordPrompts, 84 | PasswordAuthentication, 85 | PermitLocalCommand, 86 | PermitRemoteOpen, 87 | PKCS11Provider, 88 | PreferredAuthentications, 89 | ProxyCommand, 90 | ProxyJump, 91 | ProxyUseFdpass, 92 | PubkeyAcceptedKeyTypes, 93 | RekeyLimit, 94 | RequestTTY, 95 | RevokedHostKeys, 96 | SecruityKeyProvider, 97 | SendEnv, 98 | ServerAliveCountMax, 99 | SessionType, 100 | SetEnv, 101 | StdinNull, 102 | StreamLocalBindMask, 103 | StrictHostKeyChecking, 104 | SyslogFacility, 105 | UpdateHostKeys, 106 | UserKnownHostsFile, 107 | VerifyHostKeyDNS, 108 | VisualHostKey, 109 | XAuthLocation, 110 | } 111 | 112 | impl FromStr for Field { 113 | type Err = String; 114 | 115 | fn from_str(s: &str) -> Result { 116 | match s.to_lowercase().as_str() { 117 | "host" => Ok(Self::Host), 118 | "bindaddress" => Ok(Self::BindAddress), 119 | "bindinterface" => Ok(Self::BindInterface), 120 | "casignaturealgorithms" => Ok(Self::CaSignatureAlgorithms), 121 | "certificatefile" => Ok(Self::CertificateFile), 122 | "ciphers" => Ok(Self::Ciphers), 123 | "compression" => Ok(Self::Compression), 124 | "connectionattempts" => Ok(Self::ConnectionAttempts), 125 | "connecttimeout" => Ok(Self::ConnectTimeout), 126 | "hostkeyalgorithms" => Ok(Self::HostKeyAlgorithms), 127 | "hostname" => Ok(Self::HostName), 128 | "identityfile" => Ok(Self::IdentityFile), 129 | "ignoreunknown" => Ok(Self::IgnoreUnknown), 130 | "kexalgorithms" => Ok(Self::KexAlgorithms), 131 | "macs" => Ok(Self::Mac), 132 | "port" => Ok(Self::Port), 133 | "pubkeyacceptedalgorithms" => Ok(Self::PubkeyAcceptedAlgorithms), 134 | "pubkeyauthentication" => Ok(Self::PubkeyAuthentication), 135 | "remoteforward" => Ok(Self::RemoteForward), 136 | "serveraliveinterval" => Ok(Self::ServerAliveInterval), 137 | "tcpkeepalive" => Ok(Self::TcpKeepAlive), 138 | #[cfg(target_os = "macos")] 139 | "usekeychain" => Ok(Self::UseKeychain), 140 | "user" => Ok(Self::User), 141 | // -- not implemented fields 142 | "addkeystoagent" => Ok(Self::AddKeysToAgent), 143 | "addressfamily" => Ok(Self::AddressFamily), 144 | "batchmode" => Ok(Self::BatchMode), 145 | "canonicaldomains" => Ok(Self::CanonicalDomains), 146 | "canonicalizefallbacklock" => Ok(Self::CanonicalizeFallbackLock), 147 | "canonicalizehostname" => Ok(Self::CanonicalizeHostname), 148 | "canonicalizemaxdots" => Ok(Self::CanonicalizeMaxDots), 149 | "canonicalizepermittedcnames" => Ok(Self::CanonicalizePermittedCNAMEs), 150 | "checkhostip" => Ok(Self::CheckHostIP), 151 | "clearallforwardings" => Ok(Self::ClearAllForwardings), 152 | "controlmaster" => Ok(Self::ControlMaster), 153 | "controlpath" => Ok(Self::ControlPath), 154 | "controlpersist" => Ok(Self::ControlPersist), 155 | "dynamicforward" => Ok(Self::DynamicForward), 156 | "enablesshkeysign" => Ok(Self::EnableSSHKeysign), 157 | "escapechar" => Ok(Self::EscapeChar), 158 | "exitonforwardfailure" => Ok(Self::ExitOnForwardFailure), 159 | "fingerprinthash" => Ok(Self::FingerprintHash), 160 | "forkafterauthentication" => Ok(Self::ForkAfterAuthentication), 161 | "forwardagent" => Ok(Self::ForwardAgent), 162 | "forwardx11" => Ok(Self::ForwardX11), 163 | "forwardx11timeout" => Ok(Self::ForwardX11Timeout), 164 | "forwardx11trusted" => Ok(Self::ForwardX11Trusted), 165 | "gatewayports" => Ok(Self::GatewayPorts), 166 | "globalknownhostsfile" => Ok(Self::GlobalKnownHostsFile), 167 | "gssapiauthentication" => Ok(Self::GSSAPIAuthentication), 168 | "gssapidelegatecredentials" => Ok(Self::GSSAPIDelegateCredentials), 169 | "hashknownhosts" => Ok(Self::HashKnownHosts), 170 | "hostbasedacceptedalgorithms" => Ok(Self::HostbasedAcceptedAlgorithms), 171 | "hostbasedauthentication" => Ok(Self::HostbasedAuthentication), 172 | "hostkeyalias" => Ok(Self::HostKeyAlias), 173 | "hostbasedkeytypes" => Ok(Self::HostbasedKeyTypes), 174 | "identitiesonly" => Ok(Self::IdentitiesOnly), 175 | "identityagent" => Ok(Self::IdentityAgent), 176 | "include" => Ok(Self::Include), 177 | "ipqos" => Ok(Self::IPQoS), 178 | "kbdinteractiveauthentication" => Ok(Self::KbdInteractiveAuthentication), 179 | "kbdinteractivedevices" => Ok(Self::KbdInteractiveDevices), 180 | "knownhostscommand" => Ok(Self::KnownHostsCommand), 181 | "localcommand" => Ok(Self::LocalCommand), 182 | "localforward" => Ok(Self::LocalForward), 183 | "loglevel" => Ok(Self::LogLevel), 184 | "logverbose" => Ok(Self::LogVerbose), 185 | "nohostauthenticationforlocalhost" => Ok(Self::NoHostAuthenticationForLocalhost), 186 | "numberofpasswordprompts" => Ok(Self::NumberOfPasswordPrompts), 187 | "passwordauthentication" => Ok(Self::PasswordAuthentication), 188 | "permitlocalcommand" => Ok(Self::PermitLocalCommand), 189 | "permitremoteopen" => Ok(Self::PermitRemoteOpen), 190 | "pkcs11provider" => Ok(Self::PKCS11Provider), 191 | "preferredauthentications" => Ok(Self::PreferredAuthentications), 192 | "proxycommand" => Ok(Self::ProxyCommand), 193 | "proxyjump" => Ok(Self::ProxyJump), 194 | "proxyusefdpass" => Ok(Self::ProxyUseFdpass), 195 | "pubkeyacceptedkeytypes" => Ok(Self::PubkeyAcceptedKeyTypes), 196 | "rekeylimit" => Ok(Self::RekeyLimit), 197 | "requesttty" => Ok(Self::RequestTTY), 198 | "revokedhostkeys" => Ok(Self::RevokedHostKeys), 199 | "secruitykeyprovider" => Ok(Self::SecruityKeyProvider), 200 | "sendenv" => Ok(Self::SendEnv), 201 | "serveralivecountmax" => Ok(Self::ServerAliveCountMax), 202 | "sessiontype" => Ok(Self::SessionType), 203 | "setenv" => Ok(Self::SetEnv), 204 | "stdinnull" => Ok(Self::StdinNull), 205 | "streamlocalbindmask" => Ok(Self::StreamLocalBindMask), 206 | "stricthostkeychecking" => Ok(Self::StrictHostKeyChecking), 207 | "syslogfacility" => Ok(Self::SyslogFacility), 208 | "updatehostkeys" => Ok(Self::UpdateHostKeys), 209 | "userknownhostsfile" => Ok(Self::UserKnownHostsFile), 210 | "verifyhostkeydns" => Ok(Self::VerifyHostKeyDNS), 211 | "visualhostkey" => Ok(Self::VisualHostKey), 212 | "xauthlocation" => Ok(Self::XAuthLocation), 213 | // -- unknwon field 214 | _ => Err(s.to_string()), 215 | } 216 | } 217 | } 218 | 219 | impl fmt::Display for Field { 220 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 221 | let s = match self { 222 | Self::Host => "host", 223 | Self::BindAddress => "bindaddress", 224 | Self::BindInterface => "bindinterface", 225 | Self::CaSignatureAlgorithms => "casignaturealgorithms", 226 | Self::CertificateFile => "certificatefile", 227 | Self::Ciphers => "ciphers", 228 | Self::Compression => "compression", 229 | Self::ConnectionAttempts => "connectionattempts", 230 | Self::ConnectTimeout => "connecttimeout", 231 | Self::HostKeyAlgorithms => "hostkeyalgorithms", 232 | Self::HostName => "hostname", 233 | Self::IdentityFile => "identityfile", 234 | Self::IgnoreUnknown => "ignoreunknown", 235 | Self::KexAlgorithms => "kexalgorithms", 236 | Self::Mac => "macs", 237 | Self::Port => "port", 238 | Self::PubkeyAcceptedAlgorithms => "pubkeyacceptedalgorithms", 239 | Self::PubkeyAuthentication => "pubkeyauthentication", 240 | Self::RemoteForward => "remoteforward", 241 | Self::ServerAliveInterval => "serveraliveinterval", 242 | Self::TcpKeepAlive => "tcpkeepalive", 243 | #[cfg(target_os = "macos")] 244 | Self::UseKeychain => "usekeychain", 245 | Self::User => "user", 246 | // Continuation of the rest of the enum variants 247 | Self::AddKeysToAgent => "addkeystoagent", 248 | Self::AddressFamily => "addressfamily", 249 | Self::BatchMode => "batchmode", 250 | Self::CanonicalDomains => "canonicaldomains", 251 | Self::CanonicalizeFallbackLock => "canonicalizefallbacklock", 252 | Self::CanonicalizeHostname => "canonicalizehostname", 253 | Self::CanonicalizeMaxDots => "canonicalizemaxdots", 254 | Self::CanonicalizePermittedCNAMEs => "canonicalizepermittedcnames", 255 | Self::CheckHostIP => "checkhostip", 256 | Self::ClearAllForwardings => "clearallforwardings", 257 | Self::ControlMaster => "controlmaster", 258 | Self::ControlPath => "controlpath", 259 | Self::ControlPersist => "controlpersist", 260 | Self::DynamicForward => "dynamicforward", 261 | Self::EnableSSHKeysign => "enablesshkeysign", 262 | Self::EscapeChar => "escapechar", 263 | Self::ExitOnForwardFailure => "exitonforwardfailure", 264 | Self::FingerprintHash => "fingerprinthash", 265 | Self::ForkAfterAuthentication => "forkafterauthentication", 266 | Self::ForwardAgent => "forwardagent", 267 | Self::ForwardX11 => "forwardx11", 268 | Self::ForwardX11Timeout => "forwardx11timeout", 269 | Self::ForwardX11Trusted => "forwardx11trusted", 270 | Self::GatewayPorts => "gatewayports", 271 | Self::GlobalKnownHostsFile => "globalknownhostsfile", 272 | Self::GSSAPIAuthentication => "gssapiauthentication", 273 | Self::GSSAPIDelegateCredentials => "gssapidelegatecredentials", 274 | Self::HashKnownHosts => "hashknownhosts", 275 | Self::HostbasedAcceptedAlgorithms => "hostbasedacceptedalgorithms", 276 | Self::HostbasedAuthentication => "hostbasedauthentication", 277 | Self::HostKeyAlias => "hostkeyalias", 278 | Self::HostbasedKeyTypes => "hostbasedkeytypes", 279 | Self::IdentitiesOnly => "identitiesonly", 280 | Self::IdentityAgent => "identityagent", 281 | Self::Include => "include", 282 | Self::IPQoS => "ipqos", 283 | Self::KbdInteractiveAuthentication => "kbdinteractiveauthentication", 284 | Self::KbdInteractiveDevices => "kbdinteractivedevices", 285 | Self::KnownHostsCommand => "knownhostscommand", 286 | Self::LocalCommand => "localcommand", 287 | Self::LocalForward => "localforward", 288 | Self::LogLevel => "loglevel", 289 | Self::LogVerbose => "logverbose", 290 | Self::NoHostAuthenticationForLocalhost => "nohostauthenticationforlocalhost", 291 | Self::NumberOfPasswordPrompts => "numberofpasswordprompts", 292 | Self::PasswordAuthentication => "passwordauthentication", 293 | Self::PermitLocalCommand => "permitlocalcommand", 294 | Self::PermitRemoteOpen => "permitremoteopen", 295 | Self::PKCS11Provider => "pkcs11provider", 296 | Self::PreferredAuthentications => "preferredauthentications", 297 | Self::ProxyCommand => "proxycommand", 298 | Self::ProxyJump => "proxyjump", 299 | Self::ProxyUseFdpass => "proxyusefdpass", 300 | Self::PubkeyAcceptedKeyTypes => "pubkeyacceptedkeytypes", 301 | Self::RekeyLimit => "rekeylimit", 302 | Self::RequestTTY => "requesttty", 303 | Self::RevokedHostKeys => "revokedhostkeys", 304 | Self::SecruityKeyProvider => "secruitykeyprovider", 305 | Self::SendEnv => "sendenv", 306 | Self::ServerAliveCountMax => "serveralivecountmax", 307 | Self::SessionType => "sessiontype", 308 | Self::SetEnv => "setenv", 309 | Self::StdinNull => "stdinnull", 310 | Self::StreamLocalBindMask => "streamlocalbindmask", 311 | Self::StrictHostKeyChecking => "stricthostkeychecking", 312 | Self::SyslogFacility => "syslogfacility", 313 | Self::UpdateHostKeys => "updatehostkeys", 314 | Self::UserKnownHostsFile => "userknownhostsfile", 315 | Self::VerifyHostKeyDNS => "verifyhostkeydns", 316 | Self::VisualHostKey => "visualhostkey", 317 | Self::XAuthLocation => "xauthlocation", 318 | }; 319 | write!(f, "{}", s) 320 | } 321 | } 322 | 323 | #[cfg(test)] 324 | mod test { 325 | 326 | use pretty_assertions::assert_eq; 327 | 328 | use super::*; 329 | 330 | #[test] 331 | fn should_parse_field_from_string() { 332 | assert_eq!(Field::from_str("Host").ok().unwrap(), Field::Host); 333 | assert_eq!( 334 | Field::from_str("BindAddress").ok().unwrap(), 335 | Field::BindAddress 336 | ); 337 | assert_eq!( 338 | Field::from_str("BindInterface").ok().unwrap(), 339 | Field::BindInterface 340 | ); 341 | assert_eq!( 342 | Field::from_str("CaSignatureAlgorithms").ok().unwrap(), 343 | Field::CaSignatureAlgorithms 344 | ); 345 | assert_eq!( 346 | Field::from_str("CertificateFile").ok().unwrap(), 347 | Field::CertificateFile 348 | ); 349 | assert_eq!(Field::from_str("Ciphers").ok().unwrap(), Field::Ciphers); 350 | assert_eq!( 351 | Field::from_str("Compression").ok().unwrap(), 352 | Field::Compression 353 | ); 354 | assert_eq!( 355 | Field::from_str("ConnectionAttempts").ok().unwrap(), 356 | Field::ConnectionAttempts 357 | ); 358 | assert_eq!( 359 | Field::from_str("ConnectTimeout").ok().unwrap(), 360 | Field::ConnectTimeout 361 | ); 362 | assert_eq!(Field::from_str("HostName").ok().unwrap(), Field::HostName); 363 | assert_eq!( 364 | Field::from_str("IdentityFile").ok().unwrap(), 365 | Field::IdentityFile 366 | ); 367 | assert_eq!( 368 | Field::from_str("IgnoreUnknown").ok().unwrap(), 369 | Field::IgnoreUnknown 370 | ); 371 | assert_eq!(Field::from_str("Macs").ok().unwrap(), Field::Mac); 372 | assert_eq!( 373 | Field::from_str("PubkeyAcceptedAlgorithms").ok().unwrap(), 374 | Field::PubkeyAcceptedAlgorithms 375 | ); 376 | assert_eq!( 377 | Field::from_str("PubkeyAuthentication").ok().unwrap(), 378 | Field::PubkeyAuthentication 379 | ); 380 | assert_eq!( 381 | Field::from_str("RemoteForward").ok().unwrap(), 382 | Field::RemoteForward 383 | ); 384 | assert_eq!( 385 | Field::from_str("TcpKeepAlive").ok().unwrap(), 386 | Field::TcpKeepAlive 387 | ); 388 | #[cfg(target_os = "macos")] 389 | assert_eq!( 390 | Field::from_str("UseKeychain").ok().unwrap(), 391 | Field::UseKeychain 392 | ); 393 | assert_eq!(Field::from_str("User").ok().unwrap(), Field::User); 394 | assert_eq!( 395 | Field::from_str("AddKeysToAgent").ok().unwrap(), 396 | Field::AddKeysToAgent 397 | ); 398 | assert_eq!( 399 | Field::from_str("AddressFamily").ok().unwrap(), 400 | Field::AddressFamily 401 | ); 402 | assert_eq!(Field::from_str("BatchMode").ok().unwrap(), Field::BatchMode); 403 | assert_eq!( 404 | Field::from_str("CanonicalDomains").ok().unwrap(), 405 | Field::CanonicalDomains 406 | ); 407 | assert_eq!( 408 | Field::from_str("CanonicalizeFallbackLock").ok().unwrap(), 409 | Field::CanonicalizeFallbackLock 410 | ); 411 | assert_eq!( 412 | Field::from_str("CanonicalizeHostname").ok().unwrap(), 413 | Field::CanonicalizeHostname 414 | ); 415 | assert_eq!( 416 | Field::from_str("CanonicalizeMaxDots").ok().unwrap(), 417 | Field::CanonicalizeMaxDots 418 | ); 419 | assert_eq!( 420 | Field::from_str("CanonicalizePermittedCNAMEs").ok().unwrap(), 421 | Field::CanonicalizePermittedCNAMEs 422 | ); 423 | assert_eq!( 424 | Field::from_str("CheckHostIP").ok().unwrap(), 425 | Field::CheckHostIP 426 | ); 427 | assert_eq!( 428 | Field::from_str("ClearAllForwardings").ok().unwrap(), 429 | Field::ClearAllForwardings 430 | ); 431 | assert_eq!( 432 | Field::from_str("ControlMaster").ok().unwrap(), 433 | Field::ControlMaster 434 | ); 435 | assert_eq!( 436 | Field::from_str("ControlPath").ok().unwrap(), 437 | Field::ControlPath 438 | ); 439 | assert_eq!( 440 | Field::from_str("ControlPersist").ok().unwrap(), 441 | Field::ControlPersist 442 | ); 443 | assert_eq!( 444 | Field::from_str("DynamicForward").ok().unwrap(), 445 | Field::DynamicForward 446 | ); 447 | assert_eq!( 448 | Field::from_str("EnableSSHKeysign").ok().unwrap(), 449 | Field::EnableSSHKeysign 450 | ); 451 | assert_eq!( 452 | Field::from_str("EscapeChar").ok().unwrap(), 453 | Field::EscapeChar 454 | ); 455 | assert_eq!( 456 | Field::from_str("ExitOnForwardFailure").ok().unwrap(), 457 | Field::ExitOnForwardFailure 458 | ); 459 | assert_eq!( 460 | Field::from_str("FingerprintHash").ok().unwrap(), 461 | Field::FingerprintHash 462 | ); 463 | assert_eq!( 464 | Field::from_str("ForkAfterAuthentication").ok().unwrap(), 465 | Field::ForkAfterAuthentication 466 | ); 467 | assert_eq!( 468 | Field::from_str("ForwardAgent").ok().unwrap(), 469 | Field::ForwardAgent 470 | ); 471 | assert_eq!( 472 | Field::from_str("ForwardX11").ok().unwrap(), 473 | Field::ForwardX11 474 | ); 475 | assert_eq!( 476 | Field::from_str("ForwardX11Timeout").ok().unwrap(), 477 | Field::ForwardX11Timeout 478 | ); 479 | assert_eq!( 480 | Field::from_str("ForwardX11Trusted").ok().unwrap(), 481 | Field::ForwardX11Trusted, 482 | ); 483 | assert_eq!( 484 | Field::from_str("GatewayPorts").ok().unwrap(), 485 | Field::GatewayPorts 486 | ); 487 | assert_eq!( 488 | Field::from_str("GlobalKnownHostsFile").ok().unwrap(), 489 | Field::GlobalKnownHostsFile 490 | ); 491 | assert_eq!( 492 | Field::from_str("GSSAPIAuthentication").ok().unwrap(), 493 | Field::GSSAPIAuthentication 494 | ); 495 | assert_eq!( 496 | Field::from_str("GSSAPIDelegateCredentials").ok().unwrap(), 497 | Field::GSSAPIDelegateCredentials 498 | ); 499 | assert_eq!( 500 | Field::from_str("HashKnownHosts").ok().unwrap(), 501 | Field::HashKnownHosts 502 | ); 503 | assert_eq!( 504 | Field::from_str("HostbasedAcceptedAlgorithms").ok().unwrap(), 505 | Field::HostbasedAcceptedAlgorithms 506 | ); 507 | assert_eq!( 508 | Field::from_str("HostbasedAuthentication").ok().unwrap(), 509 | Field::HostbasedAuthentication 510 | ); 511 | assert_eq!( 512 | Field::from_str("HostKeyAlgorithms").ok().unwrap(), 513 | Field::HostKeyAlgorithms 514 | ); 515 | assert_eq!( 516 | Field::from_str("HostKeyAlias").ok().unwrap(), 517 | Field::HostKeyAlias 518 | ); 519 | assert_eq!( 520 | Field::from_str("HostbasedKeyTypes").ok().unwrap(), 521 | Field::HostbasedKeyTypes 522 | ); 523 | assert_eq!( 524 | Field::from_str("IdentitiesOnly").ok().unwrap(), 525 | Field::IdentitiesOnly 526 | ); 527 | assert_eq!( 528 | Field::from_str("IdentityAgent").ok().unwrap(), 529 | Field::IdentityAgent 530 | ); 531 | assert_eq!(Field::from_str("Include").ok().unwrap(), Field::Include); 532 | assert_eq!(Field::from_str("IPQoS").ok().unwrap(), Field::IPQoS); 533 | assert_eq!( 534 | Field::from_str("KbdInteractiveAuthentication") 535 | .ok() 536 | .unwrap(), 537 | Field::KbdInteractiveAuthentication 538 | ); 539 | assert_eq!( 540 | Field::from_str("KbdInteractiveDevices").ok().unwrap(), 541 | Field::KbdInteractiveDevices 542 | ); 543 | assert_eq!( 544 | Field::from_str("KnownHostsCommand").ok().unwrap(), 545 | Field::KnownHostsCommand 546 | ); 547 | assert_eq!( 548 | Field::from_str("LocalCommand").ok().unwrap(), 549 | Field::LocalCommand 550 | ); 551 | assert_eq!( 552 | Field::from_str("LocalForward").ok().unwrap(), 553 | Field::LocalForward 554 | ); 555 | assert_eq!(Field::from_str("LogLevel").ok().unwrap(), Field::LogLevel); 556 | assert_eq!( 557 | Field::from_str("LogVerbose").ok().unwrap(), 558 | Field::LogVerbose 559 | ); 560 | assert_eq!( 561 | Field::from_str("NoHostAuthenticationForLocalhost") 562 | .ok() 563 | .unwrap(), 564 | Field::NoHostAuthenticationForLocalhost 565 | ); 566 | assert_eq!( 567 | Field::from_str("NumberOfPasswordPrompts").ok().unwrap(), 568 | Field::NumberOfPasswordPrompts 569 | ); 570 | assert_eq!( 571 | Field::from_str("PasswordAuthentication").ok().unwrap(), 572 | Field::PasswordAuthentication 573 | ); 574 | assert_eq!( 575 | Field::from_str("PermitLocalCommand").ok().unwrap(), 576 | Field::PermitLocalCommand 577 | ); 578 | assert_eq!( 579 | Field::from_str("PermitRemoteOpen").ok().unwrap(), 580 | Field::PermitRemoteOpen 581 | ); 582 | assert_eq!( 583 | Field::from_str("PKCS11Provider").ok().unwrap(), 584 | Field::PKCS11Provider 585 | ); 586 | assert_eq!(Field::from_str("Port").ok().unwrap(), Field::Port); 587 | assert_eq!( 588 | Field::from_str("PreferredAuthentications").ok().unwrap(), 589 | Field::PreferredAuthentications 590 | ); 591 | assert_eq!( 592 | Field::from_str("ProxyCommand").ok().unwrap(), 593 | Field::ProxyCommand 594 | ); 595 | assert_eq!(Field::from_str("ProxyJump").ok().unwrap(), Field::ProxyJump); 596 | assert_eq!( 597 | Field::from_str("ProxyUseFdpass").ok().unwrap(), 598 | Field::ProxyUseFdpass 599 | ); 600 | assert_eq!( 601 | Field::from_str("PubkeyAcceptedKeyTypes").ok().unwrap(), 602 | Field::PubkeyAcceptedKeyTypes 603 | ); 604 | assert_eq!( 605 | Field::from_str("RekeyLimit").ok().unwrap(), 606 | Field::RekeyLimit 607 | ); 608 | assert_eq!( 609 | Field::from_str("RequestTTY").ok().unwrap(), 610 | Field::RequestTTY 611 | ); 612 | assert_eq!( 613 | Field::from_str("RevokedHostKeys").ok().unwrap(), 614 | Field::RevokedHostKeys 615 | ); 616 | assert_eq!( 617 | Field::from_str("SecruityKeyProvider").ok().unwrap(), 618 | Field::SecruityKeyProvider 619 | ); 620 | assert_eq!(Field::from_str("SendEnv").ok().unwrap(), Field::SendEnv); 621 | assert_eq!( 622 | Field::from_str("ServerAliveCountMax").ok().unwrap(), 623 | Field::ServerAliveCountMax 624 | ); 625 | assert_eq!( 626 | Field::from_str("ServerAliveInterval").ok().unwrap(), 627 | Field::ServerAliveInterval 628 | ); 629 | assert_eq!( 630 | Field::from_str("SessionType").ok().unwrap(), 631 | Field::SessionType 632 | ); 633 | assert_eq!(Field::from_str("SetEnv").ok().unwrap(), Field::SetEnv); 634 | assert_eq!(Field::from_str("StdinNull").ok().unwrap(), Field::StdinNull); 635 | assert_eq!( 636 | Field::from_str("StreamLocalBindMask").ok().unwrap(), 637 | Field::StreamLocalBindMask 638 | ); 639 | assert_eq!( 640 | Field::from_str("StrictHostKeyChecking").ok().unwrap(), 641 | Field::StrictHostKeyChecking 642 | ); 643 | assert_eq!( 644 | Field::from_str("SyslogFacility").ok().unwrap(), 645 | Field::SyslogFacility 646 | ); 647 | assert_eq!( 648 | Field::from_str("UpdateHostKeys").ok().unwrap(), 649 | Field::UpdateHostKeys 650 | ); 651 | assert_eq!( 652 | Field::from_str("UserKnownHostsFile").ok().unwrap(), 653 | Field::UserKnownHostsFile 654 | ); 655 | assert_eq!( 656 | Field::from_str("VerifyHostKeyDNS").ok().unwrap(), 657 | Field::VerifyHostKeyDNS 658 | ); 659 | assert_eq!( 660 | Field::from_str("VisualHostKey").ok().unwrap(), 661 | Field::VisualHostKey 662 | ); 663 | assert_eq!( 664 | Field::from_str("XAuthLocation").ok().unwrap(), 665 | Field::XAuthLocation 666 | ); 667 | } 668 | 669 | #[test] 670 | fn should_fail_parsing_field() { 671 | assert!(Field::from_str("CristinaDavena").is_err()); 672 | } 673 | } 674 | -------------------------------------------------------------------------------- /src/serializer.rs: -------------------------------------------------------------------------------- 1 | //! SSH Config serializer 2 | 3 | use std::fmt; 4 | 5 | use crate::{Host, HostParams, SshConfig}; 6 | 7 | pub struct SshConfigSerializer<'a>(&'a SshConfig); 8 | 9 | impl SshConfigSerializer<'_> { 10 | pub fn serialize(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 11 | if self.0.hosts.is_empty() { 12 | return Ok(()); 13 | } 14 | 15 | // serialize default host 16 | let root = self.0.hosts.first().unwrap(); 17 | Self::serialize_host_params(f, &root.params, false)?; 18 | 19 | // serialize other hosts 20 | for host in self.0.hosts.iter().skip(1) { 21 | Self::serialize_host(f, host)?; 22 | } 23 | 24 | Ok(()) 25 | } 26 | 27 | fn serialize_host(f: &mut fmt::Formatter<'_>, host: &Host) -> fmt::Result { 28 | for pattern in &host.pattern { 29 | writeln!(f, "Host {pattern}",)?; 30 | 31 | Self::serialize_host_params(f, &host.params, true)?; 32 | writeln!(f,)?; 33 | } 34 | 35 | Ok(()) 36 | } 37 | 38 | fn serialize_host_params( 39 | f: &mut fmt::Formatter<'_>, 40 | params: &HostParams, 41 | nested: bool, 42 | ) -> fmt::Result { 43 | let padding = if nested { " " } else { "" }; 44 | 45 | if let Some(value) = params.bind_address.as_ref() { 46 | writeln!(f, "{padding}Hostname {value}",)?; 47 | } 48 | if let Some(value) = params.bind_interface.as_ref() { 49 | writeln!(f, "{padding}BindAddress {value}",)?; 50 | } 51 | if !params.ca_signature_algorithms.is_default() { 52 | writeln!( 53 | f, 54 | "{padding}CASignatureAlgorithms {ca_signature_algorithms}", 55 | padding = padding, 56 | ca_signature_algorithms = params.ca_signature_algorithms 57 | )?; 58 | } 59 | if let Some(certificate_file) = params.certificate_file.as_ref() { 60 | writeln!(f, "{padding}CertificateFile {}", certificate_file.display())?; 61 | } 62 | if !params.ciphers.is_default() { 63 | writeln!( 64 | f, 65 | "{padding}Ciphers {ciphers}", 66 | padding = padding, 67 | ciphers = params.ciphers 68 | )?; 69 | } 70 | if let Some(value) = params.compression.as_ref() { 71 | writeln!( 72 | f, 73 | "{padding}Compression {}", 74 | if *value { "yes" } else { "no" } 75 | )?; 76 | } 77 | if let Some(connection_attempts) = params.connection_attempts { 78 | writeln!(f, "{padding}ConnectionAttempts {connection_attempts}",)?; 79 | } 80 | if let Some(connect_timeout) = params.connect_timeout { 81 | writeln!(f, "{padding}ConnectTimeout {}", connect_timeout.as_secs())?; 82 | } 83 | if !params.host_key_algorithms.is_default() { 84 | writeln!( 85 | f, 86 | "{padding}HostKeyAlgorithms {host_key_algorithms}", 87 | padding = padding, 88 | host_key_algorithms = params.host_key_algorithms 89 | )?; 90 | } 91 | if let Some(host_name) = params.host_name.as_ref() { 92 | writeln!(f, "{padding}HostName {host_name}",)?; 93 | } 94 | if let Some(identity_file) = params.identity_file.as_ref() { 95 | writeln!( 96 | f, 97 | "{padding}IdentityFile {}", 98 | identity_file 99 | .iter() 100 | .map(|p| p.display().to_string()) 101 | .collect::>() 102 | .join(",") 103 | )?; 104 | } 105 | if let Some(ignore_unknown) = params.ignore_unknown.as_ref() { 106 | writeln!( 107 | f, 108 | "{padding}IgnoreUnknown {}", 109 | ignore_unknown 110 | .iter() 111 | .map(|p| p.to_string()) 112 | .collect::>() 113 | .join(",") 114 | )?; 115 | } 116 | if !params.kex_algorithms.is_default() { 117 | writeln!( 118 | f, 119 | "{padding}KexAlgorithms {kex_algorithms}", 120 | padding = padding, 121 | kex_algorithms = params.kex_algorithms 122 | )?; 123 | } 124 | if !params.mac.is_default() { 125 | writeln!( 126 | f, 127 | "{padding}MACs {mac}", 128 | padding = padding, 129 | mac = params.mac 130 | )?; 131 | } 132 | if let Some(port) = params.port { 133 | writeln!(f, "{padding}Port {port}", port = port)?; 134 | } 135 | if !params.pubkey_accepted_algorithms.is_default() { 136 | writeln!( 137 | f, 138 | "{padding}PubkeyAcceptedAlgorithms {pubkey_accepted_algorithms}", 139 | padding = padding, 140 | pubkey_accepted_algorithms = params.pubkey_accepted_algorithms 141 | )?; 142 | } 143 | if let Some(pubkey_authentication) = params.pubkey_authentication.as_ref() { 144 | writeln!( 145 | f, 146 | "{padding}PubkeyAuthentication {}", 147 | if *pubkey_authentication { "yes" } else { "no" } 148 | )?; 149 | } 150 | if let Some(remote_forward) = params.remote_forward.as_ref() { 151 | writeln!(f, "{padding}RemoteForward {remote_forward}",)?; 152 | } 153 | if let Some(server_alive_interval) = params.server_alive_interval { 154 | writeln!( 155 | f, 156 | "{padding}ServerAliveInterval {}", 157 | server_alive_interval.as_secs() 158 | )?; 159 | } 160 | if let Some(tcp_keep_alive) = params.tcp_keep_alive.as_ref() { 161 | writeln!( 162 | f, 163 | "{padding}TCPKeepAlive {}", 164 | if *tcp_keep_alive { "yes" } else { "no" } 165 | )?; 166 | } 167 | #[cfg(target_os = "macos")] 168 | if let Some(use_keychain) = params.use_keychain.as_ref() { 169 | writeln!( 170 | f, 171 | "{padding}UseKeychain {}", 172 | if *use_keychain { "yes" } else { "no" } 173 | )?; 174 | } 175 | if let Some(user) = params.user.as_ref() { 176 | writeln!(f, "{padding}User {user}",)?; 177 | } 178 | for (field, value) in ¶ms.ignored_fields { 179 | writeln!( 180 | f, 181 | "{padding}{field} {value}", 182 | field = field, 183 | value = value 184 | .iter() 185 | .map(|v| v.to_string()) 186 | .collect::>() 187 | .join(" ") 188 | )?; 189 | } 190 | for (field, value) in ¶ms.unsupported_fields { 191 | writeln!( 192 | f, 193 | "{padding}{field} {value}", 194 | field = field, 195 | value = value 196 | .iter() 197 | .map(|v| v.to_string()) 198 | .collect::>() 199 | .join(" ") 200 | )?; 201 | } 202 | 203 | Ok(()) 204 | } 205 | } 206 | 207 | impl<'a> From<&'a SshConfig> for SshConfigSerializer<'a> { 208 | fn from(config: &'a SshConfig) -> Self { 209 | SshConfigSerializer(config) 210 | } 211 | } 212 | --------------------------------------------------------------------------------