├── .githooks ├── pre-commit └── pre-commit.d │ └── rust-checks ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── msnmp ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src │ ├── client.rs │ ├── format_var_bind.rs │ ├── lib.rs │ ├── main.rs │ ├── msg_factory.rs │ ├── params.rs │ ├── request.rs │ └── session.rs ├── snmp_mp ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src │ ├── error.rs │ ├── lib.rs │ ├── object_ident.rs │ ├── pdu_error_status.rs │ ├── pdu_type.rs │ ├── scoped_pdu.rs │ ├── scoped_pdu_data.rs │ ├── snmp_msg.rs │ └── var_bind.rs └── tests │ ├── scoped_pdu.rs │ └── snmp_msg.rs └── snmp_usm ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── auth_key.rs ├── error.rs ├── lib.rs ├── localized_key.rs ├── pos_finder.rs ├── priv_key.rs ├── priv_key │ ├── aes_priv_key.rs │ └── des_priv_key.rs └── security_params.rs └── tests ├── aes128_priv_key.rs ├── auth_key.rs ├── des_priv_key.rs └── security_params.rs /.githooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # This script should be saved in a git repo as a hook file, e.g. .git/hooks/pre-commit. 4 | # It looks for scripts in the .git/hooks/pre-commit.d directory and executes them in order, 5 | # passing along stdin. If any script exits with a non-zero status, this script exits. 6 | 7 | script_dir=$(dirname $0) 8 | hook_name=$(basename $0) 9 | hook_dir="$script_dir/$hook_name.d" 10 | 11 | exit_code=0 12 | 13 | if [[ -d $hook_dir ]]; then 14 | stdin=$(cat /dev/stdin) 15 | 16 | for hook in $hook_dir/*; do 17 | echo "$stdin" | $hook "$@" 18 | 19 | exit_status=$? 20 | if [ $exit_status != 0 ]; then 21 | exit_code=$exit_status 22 | fi 23 | done 24 | fi 25 | 26 | if [ $exit_code != 0 ]; then 27 | echo "(use -n option \"git commit -n\" to avoid call pre-commit hook)" 28 | echo "" 29 | fi 30 | 31 | exit $exit_code 32 | -------------------------------------------------------------------------------- /.githooks/pre-commit.d/rust-checks: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Run `cargo fmt` validation before commit. 4 | 5 | GREEN='\033[0;32m' 6 | NOCOLOR='\033[0m' 7 | 8 | echo "${GREEN}Running cargo fmt...${NOCOLOR}" 9 | echo 10 | 11 | cargo fmt -- --check 12 | exit_code=$? 13 | if [ "$exit_code" != 0 ]; then 14 | echo 15 | exit "$exit_code" 16 | fi 17 | 18 | echo "${GREEN}Running cargo clippy...${NOCOLOR}" 19 | echo 20 | 21 | cargo clippy --all-targets --all-features -- -D warnings 22 | exit_code=$? 23 | if [ "$exit_code" != 0 ]; then 24 | echo 25 | exit "$exit_code" 26 | fi 27 | 28 | echo "${GREEN}Running cargo test...${NOCOLOR}" 29 | echo 30 | 31 | cargo test 32 | exit_code=$? 33 | if [ "$exit_code" != 0 ]; then 34 | echo 35 | exit "$exit_code" 36 | fi 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /target 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | os: linux 3 | dist: bionic 4 | cache: cargo 5 | before_script: 6 | - rustup component add rustfmt 7 | - rustup component add clippy 8 | rust: 9 | - stable 10 | - beta 11 | - nightly 12 | jobs: 13 | include: 14 | - os: linux 15 | - os: osx 16 | allow_failures: 17 | - rust: nightly 18 | fast_finish: true 19 | script: 20 | - cargo fmt -- --check 21 | - cargo clippy --all-targets --all-features -- -D warnings 22 | - cargo build 23 | - cargo test 24 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Modern SNMP 2 | 3 | ## Setup 4 | 5 | To add pre-commit checks and tests: `git config core.hooksPath ".githooks"`. 6 | 7 | ## Git Commit 8 | 9 | Some wise advice gathered from multiple sources on submitting patches. 10 | 11 | ### Describe your changes 12 | 13 | Describe your problem. Whether your patch is a one-line bug fix or 5000 lines of a new feature, there must be an underlying problem that motivated you to do this work. 14 | 15 | Describe user-visible impact. Straight up crashes and lockups are pretty convincing, but not all bugs are that blatant. Even if the problem was spotted during code review, describe the impact you think it can have on users. 16 | 17 | Quantify optimizations and trade-offs. If you claim improvements in performance, memory consumption, stack footprint, or binary size, include numbers that back them up. But also describe non-obvious costs. Optimizations usually aren't free but trade-offs between CPU, memory, and readability; or, when it comes to heuristics, between different workloads. Describe the expected downsides of your optimization so that the reviewer can weigh costs against benefits. 18 | 19 | Once the problem is established, describe what you are actually doing about it in technical detail. It's important to describe the change in plain English for the reviewer to verify that the code is behaving as you intend it to. 20 | 21 | The maintainer will thank you if you write your patch description in a form which can be easily pulled into git, as a "commit log”. Here’s a model Git commit message: 22 | 23 | > Capitalized, short (about 50 chars) summary 24 | > 25 | > More detailed explanatory text, if necessary. Wrap it to about 72 26 | > characters or so. In some contexts, the first line is treated as the 27 | > subject of an email and the rest of the text as the body. The blank 28 | > line separating the summary from the body is critical (unless you omit 29 | > the body entirely); tools like rebase can get confused if you run the 30 | > two together. 31 | 32 | Write your commit message in the imperative: "Fix bug" and not "Fixed bug" 33 | or "Fixes bug." This convention matches up with commit messages generated 34 | by commands like git merge and git revert. 35 | 36 | Further paragraphs come after blank lines. 37 | 38 | - Bullet points are okay, too 39 | 40 | - Typically a hyphen or asterisk is used for the bullet, followed by a 41 | single space, with blank lines in between, but conventions vary here 42 | 43 | - Use a hanging indent 44 | 45 | Solve only one problem per patch. If your description starts to get long, that's a sign that you probably need to split up your patch. 46 | 47 | Describe your changes in imperative mood, e.g. "make xyzzy do frotz” instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behavior. 48 | 49 | If the patch fixes a logged bug entry, refer to that bug entry by number and URL. If the patch follows from a mailing list discussion, give a URL to the mailing list archive. 50 | 51 | However, try to make your explanation understandable without external resources. In addition to giving a URL to a mailing list archive or bug, summarize the relevant points of the discussion that led to the patch as submitted. 52 | 53 | If you want to refer to a specific commit, don't just refer to the SHA-1 ID of the commit. Please also include the one-line summary of the commit, to make it easier for reviewers to know what it is about. Example: 54 | 55 | > Commit e21d2170f36602ae2708 ("video: remove unnecessary 56 | > platform_set_drvdata()") removed the unnecessary 57 | > platform_set_drvdata(), but left the variable "dev" unused, 58 | > delete it. 59 | 60 | If your patch fixes a bug in a specific commit, e.g. you found an issue using git-bisect, please use the 'Fixes:' tag with the first 12 characters of the SHA-1 ID, and the one line summary. For example: 61 | 62 | > Fixes: e21d2170f366 ("video: remove unnecessary platform_set_drvdata()”) 63 | 64 | ### Separate your changes 65 | 66 | Separate each **logical change** into a separate patch. 67 | 68 | For example, if your changes include both bug fixes and performance enhancements for a single entity, separate those changes into two or more patches. If your changes include an API update, and a addition which uses that new API, separate those into two patches. 69 | 70 | On the other hand, if you make a single change to numerous files, group those changes into a single patch. Thus a single logical change is contained within a single patch. 71 | 72 | The point to remember is that each patch should make an easily understood change that can be verified by reviewers. Each patch should be justifiable on its own merits. 73 | 74 | If one patch depends on another patch in order for a change to be complete, that is OK. Simply note "this patch depends on patch X” in your patch description. 75 | 76 | When dividing your change into a series of patches, take special care to ensure that the program builds and runs properly after each patch in the series. Developers using "git bisect" to track down a problem can end up splitting your patch series at any point; they will not thank you if you introduce bugs in the middle. 77 | 78 | Sources: 79 | 80 | - 81 | - 82 | - 83 | - 84 | 85 | ## Pull Requests 86 | 87 | Pull requests are the primary mechanism to change the code. Use the "fork and pull" where contributors push changes to their personal fork and create pull requests to bring those changes into the source repository. Please make pull requests against the master branch. 88 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "src/msnmp", 4 | "src/snmp_mp", 5 | "src/snmp_usm", 6 | ] 7 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 David Dufresne 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2020 David Dufresne 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 4 | associated documentation files (the "Software"), to deal in the Software without restriction, 5 | including without limitation the rights to use, copy, modify, merge, publish, distribute, 6 | sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 7 | furnished to do so, subject to the following conditions: 8 | 9 | The above copyright notice and this permission notice shall be included in all copies or 10 | substantial portions of the Software. 11 | 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 13 | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 14 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 15 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 16 | OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Implementation of the Simple Network Management Protocol (SNMP) version 3 2 | 3 | Modern SNMP is a pure-Rust library for SNMPv3. 4 | 5 | SNMP is an Internet Standard protocol for collecting and organizing information about managed devices on IP networks and for modifying that information to change device behavior. Devices that typically support SNMP include cable modems, routers, switches, servers, workstations, printers, and more. 6 | 7 | ## Implemented Modules 8 | 9 | | Name | Crate Name | crates.io | Docs | Build Status | 10 | |------|------------|-----------|------|--------------| 11 | |SNMP MP|snmp_mp|[![crates.io](https://img.shields.io/crates/v/snmp_mp.svg)](https://crates.io/crates/snmp_mp)|[![Documentation](https://docs.rs/snmp_mp/badge.svg)](https://docs.rs/snmp_mp)|[![Build Status](https://travis-ci.org/davedufresne/modern_snmp.svg?branch=master)](https://travis-ci.org/davedufresne/modern_snmp)| 12 | |SNMP USM|snmp_usm|[![crates.io](https://img.shields.io/crates/v/snmp_usm.svg)](https://crates.io/crates/snmp_usm)|[![Documentation](https://docs.rs/snmp_usm/badge.svg)](https://docs.rs/snmp_usm)|[![Build Status](https://travis-ci.org/davedufresne/modern_snmp.svg?branch=master)](https://travis-ci.org/davedufresne/modern_snmp)| 13 | 14 | ## Demo Application 15 | 16 | | Name | Crate Name | crates.io | Build Status | 17 | |------|------------|-----------|--------------| 18 | |Modern SNMP|msnmp|[![crates.io](https://img.shields.io/crates/v/msnmp.svg)](https://crates.io/crates/msnmp)|[![Build Status](https://travis-ci.org/davedufresne/modern_snmp.svg?branch=master)](https://travis-ci.org/davedufresne/modern_snmp)| 19 | 20 | ## License 21 | 22 | Licensed under either of 23 | 24 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) 25 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 26 | 27 | at your option. 28 | 29 | ## Contribution 30 | 31 | To contribute to Modern SNMP, please see [CONTRIBUTING](CONTRIBUTING.md). 32 | 33 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 34 | -------------------------------------------------------------------------------- /src/msnmp/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.1.1 (2023-03-15) 4 | 5 | Bump 'snmp_usm' version. 6 | 7 | ## 0.1.0 (2020-08-28) 8 | 9 | Initial release. 10 | -------------------------------------------------------------------------------- /src/msnmp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "msnmp" 3 | description = "SNMP command line utility" 4 | version = "0.1.1" 5 | authors = ["David Dufresne "] 6 | license = "MIT OR Apache-2.0" 7 | edition = "2018" 8 | readme = "README.md" 9 | repository = "https://github.com/davedufresne/modern_snmp" 10 | keywords = ["snmp", "snmpv3" ] 11 | categories = ["command-line-utilities"] 12 | 13 | [dependencies] 14 | exitfailure = "0.5.1" 15 | failure = "0.1.8" 16 | rand = "0.7.3" 17 | snmp_mp = "0.1.0" 18 | snmp_usm = "0.2.1" 19 | structopt = "0.3.17" 20 | -------------------------------------------------------------------------------- /src/msnmp/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 David Dufresne 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/msnmp/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2020 David Dufresne 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 4 | associated documentation files (the "Software"), to deal in the Software without restriction, 5 | including without limitation the rights to use, copy, modify, merge, publish, distribute, 6 | sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 7 | furnished to do so, subject to the following conditions: 8 | 9 | The above copyright notice and this permission notice shall be included in all copies or 10 | substantial portions of the Software. 11 | 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 13 | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 14 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 15 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 16 | OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/msnmp/README.md: -------------------------------------------------------------------------------- 1 | # Modern SNMP Command Line Utility 2 | 3 | This command line utility is a demo application showing how to integrate [SNMP MP](../snmp_mp) and 4 | [SNMP USM](../snmp_usm). 5 | 6 | Supported command types: 7 | 8 | * Get request 9 | * Get next request 10 | * SNMP walk 11 | 12 | ## License 13 | 14 | Licensed under either of 15 | 16 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) 17 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 18 | 19 | at your option. 20 | 21 | ## Contribution 22 | 23 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 24 | -------------------------------------------------------------------------------- /src/msnmp/src/client.rs: -------------------------------------------------------------------------------- 1 | use crate::session::{Session, Step}; 2 | use snmp_mp::{self, SnmpMsg}; 3 | use snmp_usm::{Digest, PrivKey, SecurityParams}; 4 | use std::{ 5 | io::{Error, ErrorKind, Result}, 6 | net::{ToSocketAddrs, UdpSocket}, 7 | time::Duration, 8 | }; 9 | 10 | const MAX_RETRIES: u32 = 2; 11 | // Timeout in seconds. 12 | const TIMEOUT: u64 = 3; 13 | 14 | // Client to send and receive SNMP messages. Only supports IPv4. 15 | pub struct Client { 16 | socket: UdpSocket, 17 | buf: [u8; SnmpMsg::MAX_UDP_PACKET_SIZE], 18 | } 19 | 20 | impl Client { 21 | // Constructs a new `Client` and connect it to the remote address using UDP. 22 | pub fn new(remote_addr: A) -> Result { 23 | let socket = UdpSocket::bind("0.0.0.0:0")?; 24 | 25 | let timeout = Some(Duration::from_secs(TIMEOUT)); 26 | socket.set_read_timeout(timeout)?; 27 | socket.set_write_timeout(timeout)?; 28 | socket.connect(remote_addr)?; 29 | 30 | let buf = [0; SnmpMsg::MAX_UDP_PACKET_SIZE]; 31 | 32 | Ok(Self { socket, buf }) 33 | } 34 | 35 | // Sends a request and returns the response on success. 36 | pub fn send_request( 37 | &mut self, 38 | msg: &mut SnmpMsg, 39 | session: &mut Session, 40 | ) -> Result 41 | where 42 | D: Digest, 43 | P: PrivKey, 44 | S: Step + Copy, 45 | { 46 | self.send_msg(msg, session)?; 47 | let response_msg = self.recv_msg(msg.id(), session)?; 48 | Ok(response_msg) 49 | } 50 | 51 | fn send_msg(&self, msg: &mut SnmpMsg, session: &mut Session) -> Result 52 | where 53 | D: Digest, 54 | P: PrivKey, 55 | S: Step + Copy, 56 | { 57 | let mut security_params = SecurityParams::new(); 58 | security_params 59 | .set_auth_params_placeholder() 60 | .set_username(session.username()) 61 | .set_engine_id(session.engine_id()) 62 | .set_engine_boots(session.engine_boots()) 63 | .set_engine_time(session.engine_time()); 64 | 65 | if let Some((priv_key, salt)) = session.priv_key_and_salt() { 66 | msg.encrypt_scoped_pdu(|encoded_scoped_pdu| { 67 | let (encrypted_scoped_pdu, priv_params) = 68 | priv_key.encrypt(encoded_scoped_pdu, &security_params, salt); 69 | security_params.set_priv_params(&priv_params); 70 | 71 | encrypted_scoped_pdu 72 | }); 73 | } 74 | 75 | msg.set_security_params(&security_params.encode()); 76 | 77 | if session.auth_key().is_some() { 78 | msg.set_auth_flag(); 79 | } 80 | 81 | let mut encoded_msg = msg.encode(); 82 | 83 | if let Some(auth_key) = session.auth_key() { 84 | auth_key.auth_out_msg(&mut encoded_msg)?; 85 | } 86 | 87 | for _ in 0..MAX_RETRIES { 88 | let result = self.socket.send(&encoded_msg); 89 | if let Err(ref error) = result { 90 | if error.kind() == ErrorKind::WouldBlock { 91 | continue; 92 | } 93 | } 94 | 95 | return result; 96 | } 97 | 98 | Err(Error::new(ErrorKind::TimedOut, "unable to send message")) 99 | } 100 | 101 | fn recv_msg( 102 | &mut self, 103 | sent_msg_id: u32, 104 | session: &mut Session, 105 | ) -> Result 106 | where 107 | D: Digest, 108 | P: PrivKey, 109 | { 110 | for _ in 0..MAX_RETRIES { 111 | let result = self.socket.recv(&mut self.buf); 112 | 113 | match result { 114 | Err(error) => { 115 | if error.kind() == ErrorKind::WouldBlock { 116 | continue; 117 | } 118 | 119 | return Err(error); 120 | } 121 | Ok(len) => { 122 | let encoded_msg = &mut self.buf[..len]; 123 | if let Some(auth_key) = session.auth_key() { 124 | auth_key.auth_in_msg( 125 | encoded_msg, 126 | session.engine_id(), 127 | session.engine_boots(), 128 | session.engine_time(), 129 | )?; 130 | } 131 | 132 | let mut msg = SnmpMsg::decode(encoded_msg)?; 133 | 134 | if msg.id() != sent_msg_id { 135 | continue; 136 | } 137 | 138 | let security_params = SecurityParams::decode(msg.security_params())?; 139 | if let Some(priv_key) = session.priv_key() { 140 | msg.decrypt_scoped_pdu(|encrypted_scoped_pdu| { 141 | priv_key 142 | .decrypt(encrypted_scoped_pdu, &security_params) 143 | .ok() 144 | })?; 145 | } 146 | 147 | session 148 | .set_engine_boots(security_params.engine_boots()) 149 | .set_engine_time(security_params.engine_time()); 150 | 151 | return Ok(msg); 152 | } 153 | } 154 | } 155 | 156 | Err(Error::new(ErrorKind::TimedOut, "unable to receive message")) 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/msnmp/src/format_var_bind.rs: -------------------------------------------------------------------------------- 1 | use snmp_mp::{VarBind, VarValue}; 2 | 3 | const SECONDS_IN_MINUTE: u32 = 60; 4 | const SECONDS_IN_HOUR: u32 = 60 * SECONDS_IN_MINUTE; 5 | const SECONDS_IN_DAY: u32 = SECONDS_IN_HOUR * 24; 6 | 7 | pub fn format_var_bind(var_bind: &VarBind) -> String { 8 | format!( 9 | "{} = {}", 10 | var_bind.name(), 11 | format_var_value(var_bind.value()) 12 | ) 13 | } 14 | 15 | fn format_var_value(var_value: &VarValue) -> String { 16 | match var_value { 17 | VarValue::Int(i) => format!("INTEGER: {}", i), 18 | VarValue::String(s) => format!("STRING: {:?}", String::from_utf8_lossy(s)), 19 | VarValue::ObjectId(oid) => format!("OID: {}", oid), 20 | VarValue::IpAddress(ip) => format!("IP ADDRESS: {}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3]), 21 | VarValue::Counter(c) => format!("COUNTER: {}", c), 22 | VarValue::UnsignedInt(ui) => format!("UNSIGNED INTEGER: {}", ui), 23 | VarValue::TimeTicks(time_ticks) => { 24 | let hundredth = time_ticks % 100; 25 | let remaining_seconds = time_ticks / 100; 26 | let days = remaining_seconds / SECONDS_IN_DAY; 27 | let remaining_seconds = remaining_seconds % SECONDS_IN_DAY; 28 | 29 | let hours = remaining_seconds / SECONDS_IN_HOUR; 30 | let remaining_seconds = remaining_seconds % SECONDS_IN_HOUR; 31 | 32 | let minutes = remaining_seconds / SECONDS_IN_MINUTE; 33 | let seconds = remaining_seconds % SECONDS_IN_MINUTE; 34 | 35 | format!( 36 | "TIME TICKS: ({}) {} day(s) {}:{:0>2}:{:0>2}.{:0>2}", 37 | time_ticks, days, hours, minutes, seconds, hundredth 38 | ) 39 | } 40 | VarValue::Opaque(o) => format!("OPAQUE: {:X?}", o), 41 | VarValue::BigCounter(bc) => format!("BIG COUNTER: {}", bc), 42 | VarValue::Unspecified => "Unspecified".to_string(), 43 | VarValue::NoSuchObject => "No such object".to_string(), 44 | VarValue::NoSuchInstance => "No such instance".to_string(), 45 | VarValue::EndOfMibView => "End of MIB view".to_string(), 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/msnmp/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod client; 2 | mod format_var_bind; 3 | mod msg_factory; 4 | mod params; 5 | mod request; 6 | mod session; 7 | 8 | use client::Client; 9 | use failure::Error; 10 | pub use params::{Command, Params}; 11 | use session::{Session, Step}; 12 | use snmp_mp::PduType; 13 | use snmp_usm::{ 14 | Aes128PrivKey, AuthKey, DesPrivKey, Digest, LocalizedKey, Md5, PrivKey, Sha1, WithLocalizedKey, 15 | }; 16 | 17 | #[macro_use] 18 | extern crate failure; 19 | 20 | const SNMP_PORT_NUM: u32 = 161; 21 | 22 | macro_rules! execute_request { 23 | ($digest:ty, $params:expr) => {{ 24 | if Some(Params::AES128_ENCRYPTION) == $params.privacy_protocol.as_deref() { 25 | let salt = rand::random(); 26 | execute_request::< 27 | $digest, 28 | Aes128PrivKey<$digest>, 29 | as PrivKey>::Salt, 30 | >($params, salt) 31 | } else { 32 | let salt = rand::random(); 33 | execute_request::<$digest, DesPrivKey<$digest>, as PrivKey>::Salt>( 34 | $params, salt, 35 | ) 36 | } 37 | }}; 38 | } 39 | 40 | pub fn run(params: Params) -> Result<(), Error> { 41 | if Some(Params::SHA1_DIGEST) == params.auth_protocol.as_deref() { 42 | execute_request!(Sha1, params) 43 | } else { 44 | execute_request!(Md5, params) 45 | } 46 | } 47 | 48 | fn execute_request<'a, D, P, S>(params: Params, salt: P::Salt) -> Result<(), Error> 49 | where 50 | D: Digest + 'a, 51 | P: PrivKey + WithLocalizedKey<'a, D>, 52 | S: Step + Copy, 53 | { 54 | let host = if params.host.find(':').is_none() { 55 | format!("{}:{}", params.host, SNMP_PORT_NUM) 56 | } else { 57 | params.host 58 | }; 59 | 60 | let mut client = Client::new(host)?; 61 | let mut session = Session::new(&mut client, params.user.as_bytes())?; 62 | 63 | if let Some(auth_passwd) = params.auth { 64 | let localized_key = LocalizedKey::::new(auth_passwd.as_bytes(), session.engine_id()); 65 | let auth_key = AuthKey::new(localized_key); 66 | session.set_auth_key(auth_key); 67 | 68 | if let Some(priv_passwd) = params.privacy { 69 | let localized_key = LocalizedKey::::new(priv_passwd.as_bytes(), session.engine_id()); 70 | let priv_key = P::with_localized_key(localized_key); 71 | session.set_priv_key_and_salt(priv_key, salt); 72 | } 73 | } 74 | 75 | match params.cmd { 76 | Command::Get { oids } => { 77 | request::snmp_get(PduType::GetRequest, oids, &mut client, &mut session)?; 78 | } 79 | Command::GetNext { oids } => { 80 | request::snmp_get(PduType::GetRequest, oids, &mut client, &mut session)?; 81 | } 82 | Command::Walk { oid } => { 83 | request::snmp_walk(oid, &mut client, &mut session)?; 84 | } 85 | } 86 | 87 | Ok(()) 88 | } 89 | -------------------------------------------------------------------------------- /src/msnmp/src/main.rs: -------------------------------------------------------------------------------- 1 | //! Main doc. 2 | use exitfailure::ExitFailure; 3 | use msnmp::{self, Params}; 4 | use structopt::StructOpt; 5 | 6 | fn main() -> Result<(), ExitFailure> { 7 | let args = Params::from_args(); 8 | msnmp::run(args)?; 9 | 10 | Ok(()) 11 | } 12 | -------------------------------------------------------------------------------- /src/msnmp/src/msg_factory.rs: -------------------------------------------------------------------------------- 1 | use crate::Session; 2 | use snmp_mp::{self, PduType, SnmpMsg, VarBind}; 3 | 4 | pub fn create_reportable_msg(session: &mut Session) -> SnmpMsg { 5 | let mut reportable_msg = SnmpMsg::new(session.msg_id()); 6 | reportable_msg.set_reportable_flag(); 7 | 8 | if let Some(scoped_pdu) = reportable_msg.scoped_pdu_data.plaintext_mut() { 9 | scoped_pdu 10 | .set_request_id(session.request_id()) 11 | .set_engine_id(session.engine_id()); 12 | } 13 | 14 | reportable_msg 15 | } 16 | 17 | pub fn create_request_msg( 18 | pdu_type: PduType, 19 | var_binds_iter: I, 20 | session: &mut Session, 21 | ) -> SnmpMsg 22 | where 23 | I: IntoIterator, 24 | { 25 | let mut get_request = create_reportable_msg(session); 26 | if let Some(scoped_pdu) = get_request.scoped_pdu_data.plaintext_mut() { 27 | scoped_pdu 28 | .set_pdu_type(pdu_type) 29 | .set_var_binds(var_binds_iter); 30 | } 31 | 32 | get_request 33 | } 34 | -------------------------------------------------------------------------------- /src/msnmp/src/params.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | #[derive(StructOpt, Debug)] 4 | pub struct Params { 5 | #[structopt(short, long, required = true)] 6 | pub user: String, 7 | #[structopt(short, long, required = true)] 8 | pub host: String, 9 | #[structopt(short, long)] 10 | pub auth: Option, 11 | #[structopt(short = "A", long, possible_values = &[Self::MD5_DIGEST, Self::SHA1_DIGEST])] 12 | pub auth_protocol: Option, 13 | #[structopt(short, long)] 14 | pub privacy: Option, 15 | #[structopt(short = "P", long, possible_values = &[Self::DES_ENCRYPTION, Self::AES128_ENCRYPTION])] 16 | pub privacy_protocol: Option, 17 | #[structopt(subcommand)] 18 | pub cmd: Command, 19 | } 20 | 21 | impl Params { 22 | pub const MD5_DIGEST: &'static str = "MD5"; 23 | pub const SHA1_DIGEST: &'static str = "SHA1"; 24 | pub const DES_ENCRYPTION: &'static str = "DES"; 25 | pub const AES128_ENCRYPTION: &'static str = "AES128"; 26 | } 27 | 28 | #[derive(StructOpt, Debug)] 29 | pub enum Command { 30 | #[structopt(about = "Performs an SNMP GET operation")] 31 | Get { 32 | #[structopt( 33 | name = "OID", 34 | help = "One or more object identifiers separated by spaces", 35 | required = true 36 | )] 37 | oids: Vec, 38 | }, 39 | #[structopt(about = "Performs an SNMP GET NEXT operation")] 40 | GetNext { 41 | #[structopt( 42 | name = "OID", 43 | help = "One or more object identifiers separated by spaces", 44 | required = true 45 | )] 46 | oids: Vec, 47 | }, 48 | #[structopt(about = "Retrieves a subtree of management values")] 49 | Walk { 50 | #[structopt(name = "OID", help = "Optional object identifier")] 51 | oid: Option, 52 | }, 53 | } 54 | -------------------------------------------------------------------------------- /src/msnmp/src/request.rs: -------------------------------------------------------------------------------- 1 | use crate::{format_var_bind, msg_factory, Client, Session, Step}; 2 | use failure::Error; 3 | use snmp_mp::{ObjectIdent, PduType, SnmpMsg, VarBind, VarValue}; 4 | use snmp_usm::{Digest, PrivKey}; 5 | use std::str::FromStr; 6 | 7 | const MIB2_BASE_OID: [u64; 6] = [1, 3, 6, 1, 2, 1]; 8 | 9 | pub fn snmp_get( 10 | pdu_type: PduType, 11 | oids: Vec, 12 | client: &mut Client, 13 | session: &mut Session, 14 | ) -> Result<(), Error> 15 | where 16 | D: Digest, 17 | P: PrivKey, 18 | S: Step + Copy, 19 | { 20 | let var_binds = strings_to_var_binds(oids.iter()); 21 | if var_binds.is_empty() { 22 | return Err(format_err!("invalid OID(s) supplied")); 23 | } 24 | 25 | let mut get_request = msg_factory::create_request_msg(pdu_type, var_binds, session); 26 | 27 | let response = client.send_request(&mut get_request, session)?; 28 | if let Some(var_binds) = get_var_binds(&response) { 29 | for var_bind in var_binds { 30 | println!("{}", format_var_bind::format_var_bind(var_bind)); 31 | } 32 | } 33 | 34 | Ok(()) 35 | } 36 | 37 | pub fn snmp_walk( 38 | oid: Option, 39 | client: &mut Client, 40 | session: &mut Session, 41 | ) -> Result<(), Error> 42 | where 43 | D: Digest, 44 | P: PrivKey, 45 | S: Step + Copy, 46 | { 47 | let mut var_bind = strings_to_var_binds(oid.iter()); 48 | if oid.is_some() && var_bind.is_empty() { 49 | eprintln!("invalid OID supplied, using default OID\n"); 50 | } 51 | 52 | if var_bind.is_empty() { 53 | let base_oid = ObjectIdent::from_slice(&MIB2_BASE_OID); 54 | var_bind = vec![VarBind::new(base_oid)]; 55 | } 56 | 57 | let end_oid = &next_sibling(var_bind[0].name()); 58 | loop { 59 | let mut get_next_request = 60 | msg_factory::create_request_msg(PduType::GetNextRequest, var_bind, session); 61 | 62 | let get_next_response = client.send_request(&mut get_next_request, session)?; 63 | match get_first_var_bind(&get_next_response) { 64 | Some(var) => { 65 | if var.name() >= end_oid || var.value() == &VarValue::EndOfMibView { 66 | return Ok(()); 67 | } 68 | 69 | println!("{}", format_var_bind::format_var_bind(var)); 70 | var_bind = vec![VarBind::new(var.name().clone())]; 71 | } 72 | None => return Ok(()), 73 | } 74 | } 75 | } 76 | 77 | fn strings_to_var_binds<'a, I>(strings: I) -> Vec 78 | where 79 | I: Iterator, 80 | { 81 | strings 82 | .map(|oid_str| ObjectIdent::from_str(oid_str)) 83 | .filter_map(Result::ok) 84 | .map(VarBind::new) 85 | .collect() 86 | } 87 | 88 | fn get_var_binds(msg: &SnmpMsg) -> Option<&[VarBind]> { 89 | Some(msg.scoped_pdu_data.plaintext()?.var_binds()) 90 | } 91 | 92 | fn get_first_var_bind(msg: &SnmpMsg) -> Option<&VarBind> { 93 | get_var_binds(msg)?.first() 94 | } 95 | 96 | fn next_sibling(oid: &ObjectIdent) -> ObjectIdent { 97 | let mut components = oid.components().to_vec(); 98 | let len = components.len(); 99 | components[len - 1] = components[len - 1].wrapping_add(1); 100 | 101 | ObjectIdent::new(components) 102 | } 103 | -------------------------------------------------------------------------------- /src/msnmp/src/session.rs: -------------------------------------------------------------------------------- 1 | use crate::client::Client; 2 | use crate::msg_factory; 3 | use rand::prelude::*; 4 | use snmp_mp::{ScopedPdu, SnmpMsg}; 5 | use snmp_usm::{AuthKey, Digest, PrivKey, SecurityParams}; 6 | use std::io::Result; 7 | use std::time::Instant; 8 | 9 | // Trait implemented by types representing a cryptographic salt. It allows those 'salt' types to be 10 | // used generically. 11 | pub trait Step { 12 | fn next(&self) -> Self; 13 | } 14 | 15 | impl Step for u32 { 16 | fn next(&self) -> Self { 17 | self.wrapping_add(1) 18 | } 19 | } 20 | 21 | impl Step for u64 { 22 | fn next(&self) -> Self { 23 | self.wrapping_add(1) 24 | } 25 | } 26 | 27 | // Contains the information of a session with an SNMP engine. 28 | // 29 | // Before requests can be sent to an SNMP engine a discovery process has to take place. If 30 | // authentication is requested time synchronization has also to be performed. `Session` 31 | // contains the information gathered from these processes. 32 | #[derive(Debug, Clone)] 33 | pub struct Session<'a, D, P, S> { 34 | username: Vec, 35 | engine_id: Vec, 36 | engine_boots: u32, 37 | engine_time: u32, 38 | msg_id: u32, 39 | request_id: i32, 40 | sync_time: Instant, 41 | auth_key: Option>, 42 | priv_key: Option<(P, S)>, 43 | } 44 | 45 | impl<'a, D, P, S> Session<'a, D, P, S> { 46 | pub fn username(&self) -> &[u8] { 47 | &self.username 48 | } 49 | 50 | pub fn set_username(&mut self, username: &[u8]) -> &mut Self { 51 | self.username.clear(); 52 | self.username.extend_from_slice(username); 53 | self 54 | } 55 | 56 | pub fn engine_id(&self) -> &[u8] { 57 | &self.engine_id 58 | } 59 | 60 | pub fn set_engine_id(&mut self, engine_id: &[u8]) -> &mut Self { 61 | self.engine_id.clear(); 62 | self.engine_id.extend_from_slice(engine_id); 63 | self 64 | } 65 | 66 | pub fn engine_boots(&self) -> u32 { 67 | self.engine_boots 68 | } 69 | 70 | pub fn set_engine_boots(&mut self, engine_boots: u32) -> &mut Self { 71 | self.engine_boots = engine_boots; 72 | self 73 | } 74 | 75 | pub fn engine_time(&self) -> u32 { 76 | self.engine_time + self.sync_time.elapsed().as_secs() as u32 77 | } 78 | 79 | pub fn set_engine_time(&mut self, engine_time: u32) -> &mut Self { 80 | self.engine_time = engine_time; 81 | self.sync_time = Instant::now(); 82 | self 83 | } 84 | 85 | pub fn msg_id(&mut self) -> u32 { 86 | let msg_id = self.msg_id; 87 | let next_id = self.msg_id.wrapping_add(1); 88 | self.msg_id = if next_id > SnmpMsg::MSG_ID_MAX { 89 | SnmpMsg::MSG_ID_MIN 90 | } else { 91 | next_id 92 | }; 93 | 94 | msg_id 95 | } 96 | 97 | pub fn request_id(&mut self) -> i32 { 98 | let request_id = self.request_id; 99 | let next_id = self.request_id.wrapping_add(1); 100 | self.request_id = if next_id > ScopedPdu::REQUEST_ID_MAX { 101 | ScopedPdu::REQUEST_ID_MIN 102 | } else { 103 | next_id 104 | }; 105 | 106 | request_id 107 | } 108 | 109 | pub fn auth_key(&self) -> &Option> { 110 | &self.auth_key 111 | } 112 | 113 | pub fn set_auth_key(&mut self, auth_key: AuthKey<'a, D>) -> &mut Self { 114 | self.auth_key = Some(auth_key); 115 | self 116 | } 117 | 118 | pub fn priv_key(&self) -> Option<&P> { 119 | if let Some((ref priv_key, _)) = self.priv_key { 120 | return Some(priv_key); 121 | } 122 | 123 | None 124 | } 125 | } 126 | 127 | impl<'a, D, P, S> Session<'a, D, P, S> 128 | where 129 | D: Digest, 130 | P: PrivKey, 131 | S: Step + Copy, 132 | { 133 | pub fn new(client: &mut Client, username: &[u8]) -> Result { 134 | let mut rng = thread_rng(); 135 | 136 | let mut session = Self { 137 | username: Default::default(), 138 | engine_id: Default::default(), 139 | engine_boots: Default::default(), 140 | engine_time: Default::default(), 141 | msg_id: rng.gen_range(SnmpMsg::MSG_ID_MIN, SnmpMsg::MSG_ID_MAX), 142 | request_id: rng.gen_range(ScopedPdu::REQUEST_ID_MIN, ScopedPdu::REQUEST_ID_MAX), 143 | sync_time: Instant::now(), 144 | auth_key: None, 145 | priv_key: None, 146 | }; 147 | 148 | let mut discovery_msg = msg_factory::create_reportable_msg(&mut session); 149 | let discovery_response = client.send_request(&mut discovery_msg, &mut session)?; 150 | 151 | let security_params = SecurityParams::decode(discovery_response.security_params())?; 152 | session 153 | .set_username(username) 154 | .set_engine_id(security_params.engine_id()) 155 | .set_engine_boots(security_params.engine_boots()) 156 | .set_engine_time(security_params.engine_time()); 157 | 158 | Ok(session) 159 | } 160 | 161 | pub fn priv_key_and_salt(&mut self) -> Option<(&P, P::Salt)> { 162 | if let Some((ref priv_key, ref mut salt)) = self.priv_key { 163 | let prev_salt = *salt; 164 | *salt = prev_salt.next(); 165 | 166 | return Some((priv_key, prev_salt)); 167 | } 168 | 169 | None 170 | } 171 | 172 | pub fn set_priv_key_and_salt(&mut self, priv_key: P, salt: P::Salt) -> &mut Self { 173 | self.priv_key = Some((priv_key, salt)); 174 | self 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/snmp_mp/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.1.0 (2020-08-28) 4 | 5 | Initial release. 6 | -------------------------------------------------------------------------------- /src/snmp_mp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "snmp_mp" 3 | description = "SNMPv3 Message Processing" 4 | version = "0.1.0" # remember to update html_root_url 5 | authors = ["David Dufresne "] 6 | license = "MIT OR Apache-2.0" 7 | edition = "2018" 8 | readme = "README.md" 9 | repository = "https://github.com/davedufresne/modern_snmp" 10 | keywords = ["snmp", "snmpv3", "message", "processing", "pdu"] 11 | categories = ["network-programming"] 12 | 13 | [dependencies] 14 | bitflags = "1.2.1" 15 | yasna = "0.3.2" 16 | -------------------------------------------------------------------------------- /src/snmp_mp/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 David Dufresne 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/snmp_mp/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2020 David Dufresne 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 4 | associated documentation files (the "Software"), to deal in the Software without restriction, 5 | including without limitation the rights to use, copy, modify, merge, publish, distribute, 6 | sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 7 | furnished to do so, subject to the following conditions: 8 | 9 | The above copyright notice and this permission notice shall be included in all copies or 10 | substantial portions of the Software. 11 | 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 13 | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 14 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 15 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 16 | OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/snmp_mp/README.md: -------------------------------------------------------------------------------- 1 | # SNMPv3 Message Processing 2 | 3 | **SNMP Message Processing** implements the primitives for preparing messages for sending, and extracting data from received messages. 4 | 5 | Supported PDU types: 6 | 7 | * GetRequest 8 | * GetNextRequest 9 | * GetBulkRequest 10 | * Response 11 | * SetRequest 12 | * SNMPv2-Trap 13 | * InformRequest 14 | 15 | ## License 16 | 17 | Licensed under either of 18 | 19 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) 20 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 21 | 22 | at your option. 23 | 24 | ## Contribution 25 | 26 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 27 | -------------------------------------------------------------------------------- /src/snmp_mp/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::fmt::{Display, Formatter, Result}; 3 | use std::io; 4 | 5 | /// The error type for message processing related operations. 6 | #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] 7 | pub enum MsgProcessingError { 8 | /// The contents of the value field in a variable binding does not, according to the ASN.1 9 | /// language, manifest a type, length, and value that is consistent with that required for the 10 | /// variable. 11 | BadValue, 12 | /// Bad SNMP version. 13 | BadVersion, 14 | /// Decryption error occurred. 15 | DecryptError, 16 | /// The outgoing SNMP message is too big. 17 | TooBig, 18 | /// The SNMP message was malformed. 19 | MalformedMsg, 20 | } 21 | 22 | impl Display for MsgProcessingError { 23 | fn fmt(&self, formatter: &mut Formatter) -> Result { 24 | match self { 25 | Self::BadValue => "bad variable binding value".fmt(formatter), 26 | Self::BadVersion => "bad SNMP version".fmt(formatter), 27 | Self::DecryptError => "decryption error".fmt(formatter), 28 | Self::TooBig => "outgoing message too big".fmt(formatter), 29 | Self::MalformedMsg => "malformed incoming message".fmt(formatter), 30 | } 31 | } 32 | } 33 | 34 | impl Error for MsgProcessingError {} 35 | 36 | #[doc(hidden)] 37 | impl From for io::Error { 38 | fn from(parse_error: MsgProcessingError) -> Self { 39 | Self::new(io::ErrorKind::InvalidData, parse_error) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/snmp_mp/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc(html_root_url = "https://docs.rs/snmp_mp/0.1.0")] 2 | 3 | //! # Primitives to send and receive SNMP messages. 4 | //! 5 | //! Supported PDU types: 6 | //! 7 | //! * GetRequest 8 | //! * GetNextRequest 9 | //! * GetBulkRequest 10 | //! * Response 11 | //! * SetRequest 12 | //! * SNMPv2-Trap 13 | //! * InformRequest 14 | //! 15 | //! ## Examples 16 | //! 17 | //! ``` 18 | //! use snmp_mp::{ObjectIdent, SnmpMsg, VarBind}; 19 | //! 20 | //! let mut msg = SnmpMsg::new(1); 21 | //! msg.set_reportable_flag(); 22 | //! 23 | //! if let Some(scoped_pdu) = msg.scoped_pdu_data.plaintext_mut() { 24 | //! let sys_desc = ObjectIdent::from_slice(&[0x01, 0x03, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00]); 25 | //! let var_bind = VarBind::new(sys_desc); 26 | //! 27 | //! scoped_pdu 28 | //! .set_request_id(1) 29 | //! .set_engine_id(b"context_engine_id") 30 | //! .push_var_bind(var_bind); 31 | //! } 32 | //! 33 | //! let encoded_msg = msg.encode(); 34 | //! // Send the encoded message over the network. 35 | //! ``` 36 | //! 37 | //! [encrypt_scoped_pdu](struct.SnmpMsg.html#method.encrypt_scoped_pdu) and 38 | //! [decrypt_scoped_pdu](struct.SnmpMsg.html#method.decrypt_scoped_pdu) are provided to make it 39 | //! easy to use a security model: 40 | //! 41 | //! ``` 42 | //! # use snmp_mp::SnmpMsg; 43 | //! # let mut msg = SnmpMsg::new(1); 44 | //! msg.encrypt_scoped_pdu(|encoded_scoped_pdu| { 45 | //! // A security model encrypts and returns the scoped PDU. 46 | //! // let (encrypted_scoped_pdu, priv_params) = 47 | //! // priv_key.encrypt(encoded_scoped_pdu, &security_params, salt); 48 | //! // security_params.set_priv_params(&priv_params); 49 | //! 50 | //! # let encrypted_scoped_pdu = encoded_scoped_pdu; 51 | //! encrypted_scoped_pdu 52 | //! }); 53 | //! 54 | //! msg.decrypt_scoped_pdu(|encrypted_scoped_pdu| { 55 | //! // A security model returns the decrypted scoped PDU wrapped in an `Option`. 56 | //! // priv_key 57 | //! // .decrypt(encrypted_scoped_pdu, &security_params) 58 | //! // .ok() 59 | //! # None 60 | //! }); 61 | //! ``` 62 | #[macro_use] 63 | extern crate bitflags; 64 | 65 | mod error; 66 | mod object_ident; 67 | mod pdu_error_status; 68 | mod pdu_type; 69 | mod scoped_pdu; 70 | mod scoped_pdu_data; 71 | mod snmp_msg; 72 | mod var_bind; 73 | 74 | pub use error::MsgProcessingError; 75 | pub use object_ident::ObjectIdent; 76 | pub use pdu_error_status::PduErrorStatus; 77 | pub use pdu_type::PduType; 78 | pub use scoped_pdu::ScopedPdu; 79 | pub use scoped_pdu_data::ScopedPduData; 80 | pub use snmp_msg::SnmpMsg; 81 | pub use var_bind::{VarBind, VarValue}; 82 | 83 | /// Type alias for the result of a message processing operation. 84 | pub type MsgProcessingResult = Result; 85 | 86 | const SNMP_V3: u32 = 3; 87 | -------------------------------------------------------------------------------- /src/snmp_mp/src/object_ident.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | error::Error, 3 | fmt::{self, Display, Formatter}, 4 | str::FromStr, 5 | }; 6 | use yasna::models::ObjectIdentifier; 7 | 8 | /// Represents an object identifier. 9 | /// 10 | /// For SNMP the expectation is that there are at most 128 sub-identifiers in a value, and each 11 | /// sub-identifier has a maximum value of `4_294_967_295`. These limits are not enforced by 12 | /// `ObjectIdent`. 13 | /// 14 | /// # Examples 15 | /// 16 | /// ``` 17 | /// use snmp_mp::ObjectIdent; 18 | /// 19 | /// let sys_descr_oid = [1, 3, 6, 1, 2, 1, 1, 1]; 20 | /// let sys_descr = ObjectIdent::from_slice(&sys_descr_oid); 21 | /// assert_eq!(sys_descr.components(), &sys_descr_oid); 22 | /// ``` 23 | #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] 24 | pub struct ObjectIdent(pub(crate) ObjectIdentifier); 25 | 26 | impl ObjectIdent { 27 | /// Constructs a new `ObjectIdent` from a `Vec`. 28 | /// 29 | /// # Examples 30 | /// 31 | /// ``` 32 | /// # use snmp_mp::ObjectIdent; 33 | /// let sys_descr_oid = vec![1, 3, 6, 1, 2, 1, 1, 1]; 34 | /// let sys_descr = ObjectIdent::new(sys_descr_oid.clone()); 35 | /// assert_eq!(sys_descr.components(), &sys_descr_oid[..]); 36 | pub fn new(components: Vec) -> Self { 37 | Self(ObjectIdentifier::new(components)) 38 | } 39 | 40 | /// Constructs a new `ObjectIdent` from a slice. 41 | /// 42 | /// # Examples 43 | /// 44 | /// ``` 45 | /// # use snmp_mp::ObjectIdent; 46 | /// let sys_descr_oid = [1, 3, 6, 1, 2, 1, 1, 1]; 47 | /// let sys_descr = ObjectIdent::from_slice(&sys_descr_oid); 48 | /// assert_eq!(sys_descr.components(), &sys_descr_oid); 49 | /// ``` 50 | pub fn from_slice(components: &[u64]) -> Self { 51 | Self(ObjectIdentifier::from_slice(components)) 52 | } 53 | 54 | /// Returns the components of this `ObjectIdent`. 55 | /// 56 | /// # Examples 57 | /// 58 | /// ``` 59 | /// # use snmp_mp::ObjectIdent; 60 | /// let sys_descr_oid = [1, 3, 6, 1, 2, 1, 1, 1]; 61 | /// let sys_descr = ObjectIdent::from_slice(&sys_descr_oid); 62 | /// assert_eq!(sys_descr.components(), &sys_descr_oid); 63 | /// ``` 64 | pub fn components(&self) -> &[u64] { 65 | self.0.components() 66 | } 67 | } 68 | 69 | impl Display for ObjectIdent { 70 | fn fmt(&self, formatter: &mut Formatter) -> fmt::Result { 71 | self.0.fmt(formatter) 72 | } 73 | } 74 | 75 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 76 | /// An error indicating failure to parse an Object identifier. 77 | pub struct ParseOidError; 78 | 79 | impl Error for ParseOidError {} 80 | 81 | impl Display for ParseOidError { 82 | fn fmt(&self, formatter: &mut Formatter) -> fmt::Result { 83 | "failed to parse OID".fmt(formatter) 84 | } 85 | } 86 | 87 | impl FromStr for ObjectIdent { 88 | type Err = ParseOidError; 89 | 90 | fn from_str(s: &str) -> Result { 91 | // The BER parsing library panics when trying to write an OID with only one component. 92 | let result = ObjectIdentifier::from_str(s); 93 | match result { 94 | Ok(oid) => { 95 | if oid.components().len() < 2 { 96 | Err(ParseOidError) 97 | } else { 98 | Ok(Self(oid)) 99 | } 100 | } 101 | Err(_) => Err(ParseOidError), 102 | } 103 | } 104 | } 105 | 106 | impl From> for ObjectIdent { 107 | fn from(components: Vec) -> Self { 108 | Self::new(components) 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/snmp_mp/src/pdu_error_status.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryFrom; 2 | use std::error::Error; 3 | use std::fmt; 4 | 5 | const NO_ERROR: isize = 0; 6 | const TOO_BIG: isize = 1; 7 | const NO_SUCH_NAME: isize = 2; 8 | const BAD_VALUE: isize = 3; 9 | const READ_ONLY: isize = 4; 10 | const GEN_ERR: isize = 5; 11 | const NO_ACCESS: isize = 6; 12 | const WRONG_TYPE: isize = 7; 13 | const WRONG_LENGTH: isize = 8; 14 | const WRONG_ENCODING: isize = 9; 15 | const WRONG_VALUE: isize = 10; 16 | const NO_CREATION: isize = 11; 17 | const INCONSISTENT_VALUE: isize = 12; 18 | const RESOURCE_UNAVAILABLE: isize = 13; 19 | const COMMIT_FAILED: isize = 14; 20 | const UNDO_FAILED: isize = 15; 21 | const AUTHORIZATION_ERROR: isize = 16; 22 | const NOT_WRITABLE: isize = 17; 23 | const INCONSISTENT_NAME: isize = 18; 24 | 25 | /// Response PDU error status. 26 | /// 27 | /// A non-zero value of the error-status field in a Response-PDU is used to indicate that an error 28 | /// occurred to prevent the processing of the request. 29 | #[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Hash)] 30 | pub enum PduErrorStatus { 31 | #[default] 32 | NoError = NO_ERROR, 33 | TooBig = TOO_BIG, 34 | NoSuchName = NO_SUCH_NAME, 35 | BadValue = BAD_VALUE, 36 | ReadOnly = READ_ONLY, 37 | GenErr = GEN_ERR, 38 | NoAccess = NO_ACCESS, 39 | WrongType = WRONG_TYPE, 40 | WrongLength = WRONG_LENGTH, 41 | WrongEncoding = WRONG_ENCODING, 42 | WrongValue = WRONG_VALUE, 43 | NoCreation = NO_CREATION, 44 | InconsistentValue = INCONSISTENT_VALUE, 45 | ResourceUnavailable = RESOURCE_UNAVAILABLE, 46 | CommitFailed = COMMIT_FAILED, 47 | UndoFailed = UNDO_FAILED, 48 | AuthorizationError = AUTHORIZATION_ERROR, 49 | NotWritable = NOT_WRITABLE, 50 | InconsistentName = INCONSISTENT_NAME, 51 | } 52 | 53 | /// Error returned when the conversion from `u8` to `PduErrorStatus` fails. 54 | #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] 55 | pub struct IntToPduErrorStatusError; 56 | 57 | impl IntToPduErrorStatusError { 58 | fn description(&self) -> &str { 59 | "not a valid PDU error status" 60 | } 61 | } 62 | 63 | impl Error for IntToPduErrorStatusError {} 64 | 65 | impl fmt::Display for IntToPduErrorStatusError { 66 | fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 67 | self.description().fmt(formatter) 68 | } 69 | } 70 | 71 | impl TryFrom for PduErrorStatus { 72 | type Error = IntToPduErrorStatusError; 73 | 74 | /// Tries to create a `PduErrorStatus` from a `u8`. 75 | /// 76 | /// # Errors 77 | /// 78 | /// This returns an error if the `u8` doesn't match a PDU type. 79 | fn try_from(integer: u8) -> Result { 80 | let result = match integer as isize { 81 | NO_ERROR => PduErrorStatus::NoError, 82 | TOO_BIG => PduErrorStatus::TooBig, 83 | NO_SUCH_NAME => PduErrorStatus::NoSuchName, 84 | BAD_VALUE => PduErrorStatus::BadValue, 85 | READ_ONLY => PduErrorStatus::ReadOnly, 86 | GEN_ERR => PduErrorStatus::GenErr, 87 | NO_ACCESS => PduErrorStatus::NoAccess, 88 | WRONG_TYPE => PduErrorStatus::WrongType, 89 | WRONG_LENGTH => PduErrorStatus::WrongLength, 90 | WRONG_ENCODING => PduErrorStatus::WrongEncoding, 91 | WRONG_VALUE => PduErrorStatus::WrongValue, 92 | NO_CREATION => PduErrorStatus::NoCreation, 93 | INCONSISTENT_VALUE => PduErrorStatus::InconsistentValue, 94 | RESOURCE_UNAVAILABLE => PduErrorStatus::ResourceUnavailable, 95 | COMMIT_FAILED => PduErrorStatus::CommitFailed, 96 | UNDO_FAILED => PduErrorStatus::UndoFailed, 97 | AUTHORIZATION_ERROR => PduErrorStatus::AuthorizationError, 98 | NOT_WRITABLE => PduErrorStatus::NotWritable, 99 | INCONSISTENT_NAME => PduErrorStatus::InconsistentName, 100 | _ => return Err(IntToPduErrorStatusError), 101 | }; 102 | 103 | Ok(result) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/snmp_mp/src/pdu_type.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryFrom; 2 | use std::error::Error; 3 | use std::fmt; 4 | 5 | // `u64` is used because the BER encoding library uses this type for tag numbers. 6 | const GET_REQUEST_TAG_NUM: u64 = 0; 7 | const GET_NEXT_REQUEST_TAG_NUM: u64 = 1; 8 | const RESPONSE_TAG_NUM: u64 = 2; 9 | const SET_REQUEST_TAG_NUM: u64 = 3; 10 | const GET_BULK_REQUEST_TAG_NUM: u64 = 5; 11 | const INFORM_REQUEST_TAG_NUM: u64 = 6; 12 | const SNMP_TRAP_TAG_NUM: u64 = 7; 13 | const REPORT_TAG_NUM: u64 = 8; 14 | 15 | /// Represents a PDU type. 16 | /// 17 | /// PDU types are encoded as implicit tags. 18 | #[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Hash)] 19 | pub enum PduType { 20 | #[default] 21 | GetRequest = GET_REQUEST_TAG_NUM as isize, 22 | GetNextRequest = GET_NEXT_REQUEST_TAG_NUM as isize, 23 | Response = RESPONSE_TAG_NUM as isize, 24 | SetRequest = SET_REQUEST_TAG_NUM as isize, 25 | GetBulkRequest = GET_BULK_REQUEST_TAG_NUM as isize, 26 | InformRequest = INFORM_REQUEST_TAG_NUM as isize, 27 | SnmpTrap = SNMP_TRAP_TAG_NUM as isize, 28 | Report = REPORT_TAG_NUM as isize, 29 | } 30 | 31 | /// Error returned when the conversion from `u64` to `PduType` fails. 32 | #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] 33 | pub struct IntToPduTypeError; 34 | 35 | impl IntToPduTypeError { 36 | fn description(&self) -> &str { 37 | "not a valid PDU type" 38 | } 39 | } 40 | 41 | impl Error for IntToPduTypeError {} 42 | 43 | impl fmt::Display for IntToPduTypeError { 44 | fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 45 | self.description().fmt(formatter) 46 | } 47 | } 48 | 49 | impl TryFrom for PduType { 50 | type Error = IntToPduTypeError; 51 | 52 | /// Tries to create a `PduType` from a `u64`. 53 | /// 54 | /// # Errors 55 | /// 56 | /// This returns an error if the `u64` doesn't match a PDU type. 57 | fn try_from(integer: u64) -> Result { 58 | let result = match integer { 59 | GET_REQUEST_TAG_NUM => Self::GetRequest, 60 | GET_NEXT_REQUEST_TAG_NUM => Self::GetNextRequest, 61 | RESPONSE_TAG_NUM => Self::Response, 62 | SET_REQUEST_TAG_NUM => Self::SetRequest, 63 | GET_BULK_REQUEST_TAG_NUM => Self::GetBulkRequest, 64 | INFORM_REQUEST_TAG_NUM => Self::InformRequest, 65 | SNMP_TRAP_TAG_NUM => Self::SnmpTrap, 66 | REPORT_TAG_NUM => Self::Report, 67 | _ => return Err(IntToPduTypeError), 68 | }; 69 | 70 | Ok(result) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/snmp_mp/src/scoped_pdu.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryFrom; 2 | use yasna::{self, ASN1Error, ASN1ErrorKind, ASN1Result, BERReader, DERWriter, Tag, TagClass}; 3 | 4 | use crate::{MsgProcessingError, MsgProcessingResult, PduErrorStatus, PduType, VarBind}; 5 | 6 | /// Scoped PDU contained in an SNMP message. 7 | /// 8 | /// Builder methods are provided to update the scoped PDU. 9 | /// 10 | /// # Examples 11 | /// 12 | /// ``` 13 | /// use snmp_mp::{PduType, ScopedPdu}; 14 | /// 15 | /// let mut scoped_pdu = ScopedPdu::new(1); 16 | /// scoped_pdu 17 | /// .set_pdu_type(PduType::GetNextRequest) 18 | /// .set_engine_id(b"engine_id"); 19 | /// ``` 20 | #[derive(Debug, Clone, Default, Eq, PartialEq, Hash)] 21 | pub struct ScopedPdu { 22 | engine_id: Vec, 23 | context_name: Vec, 24 | pdu_type: PduType, 25 | request_id: i32, 26 | error_status: PduErrorStatus, 27 | error_index: u32, 28 | var_binds: Vec, 29 | } 30 | 31 | impl ScopedPdu { 32 | /// The smallest value that can be used as a request ID. 33 | /// 34 | /// # Examples 35 | /// 36 | /// ``` 37 | /// # use snmp_mp::ScopedPdu; 38 | /// assert_eq!(ScopedPdu::REQUEST_ID_MIN, -214_783_648); 39 | /// ``` 40 | pub const REQUEST_ID_MIN: i32 = -214_783_648; 41 | 42 | /// The largest value that can be used as a request ID. 43 | /// 44 | /// # Examples 45 | /// 46 | /// ``` 47 | /// # use snmp_mp::ScopedPdu; 48 | /// assert_eq!(ScopedPdu::REQUEST_ID_MAX, 214_783_647); 49 | /// ``` 50 | pub const REQUEST_ID_MAX: i32 = 214_783_647; 51 | 52 | /// Constructs a new empty `ScopedPdu`. 53 | /// 54 | /// # Examples 55 | /// 56 | /// ``` 57 | /// # use snmp_mp::ScopedPdu; 58 | /// let scoped_pdu = ScopedPdu::new(1); 59 | /// ``` 60 | pub fn new(request_id: i32) -> Self { 61 | Self { 62 | request_id, 63 | ..Default::default() 64 | } 65 | } 66 | 67 | /// Returns the context engine ID. 68 | /// 69 | /// # Examples 70 | /// 71 | /// ``` 72 | /// # use snmp_mp::ScopedPdu; 73 | /// # let scoped_pdu = ScopedPdu::new(1); 74 | /// let engine_id = scoped_pdu.engine_id(); 75 | /// ``` 76 | pub fn engine_id(&self) -> &[u8] { 77 | &self.engine_id 78 | } 79 | 80 | /// Sets the context engine ID. 81 | /// 82 | /// # Examples 83 | /// 84 | /// ``` 85 | /// # use snmp_mp::ScopedPdu; 86 | /// let mut scoped_pdu = ScopedPdu::new(1); 87 | /// scoped_pdu.set_engine_id(b"engine_id"); 88 | /// assert_eq!(scoped_pdu.engine_id(), b"engine_id"); 89 | /// ``` 90 | pub fn set_engine_id(&mut self, engine_id: &[u8]) -> &mut Self { 91 | self.engine_id.clear(); 92 | self.engine_id.extend_from_slice(engine_id); 93 | self 94 | } 95 | 96 | /// Returns the context name. 97 | /// 98 | /// The context name field in conjunction with the context engine ID field, identifies the 99 | /// particular context associated with the management information contained in the PDU portion 100 | /// of the message. The contextName is unique within the SNMP entity specified by the 101 | /// context engine ID, which may realize the managed objects referenced within the PDU. 102 | /// 103 | /// # Examples 104 | /// 105 | /// ``` 106 | /// # use snmp_mp::ScopedPdu; 107 | /// # let scoped_pdu = ScopedPdu::new(1); 108 | /// let context_name = scoped_pdu.context_name(); 109 | /// ``` 110 | pub fn context_name(&self) -> &[u8] { 111 | &self.context_name 112 | } 113 | 114 | /// Sets the context name. 115 | /// 116 | /// # Examples 117 | /// 118 | /// ``` 119 | /// # use snmp_mp::ScopedPdu; 120 | /// let mut scoped_pdu = ScopedPdu::new(1); 121 | /// scoped_pdu.set_context_name(b"context_name"); 122 | /// assert_eq!(scoped_pdu.context_name(), b"context_name"); 123 | /// ``` 124 | pub fn set_context_name(&mut self, context_name: &[u8]) -> &mut Self { 125 | self.context_name.clear(); 126 | self.context_name.extend_from_slice(context_name); 127 | self 128 | } 129 | 130 | /// Returns the PDU type. 131 | /// 132 | /// # Examples 133 | /// 134 | /// ``` 135 | /// # use snmp_mp::ScopedPdu; 136 | /// # let scoped_pdu = ScopedPdu::new(1); 137 | /// let pdu_type = scoped_pdu.pdu_type(); 138 | /// ``` 139 | pub fn pdu_type(&self) -> PduType { 140 | self.pdu_type 141 | } 142 | 143 | /// Sets the PDU type. 144 | /// 145 | /// # Examples 146 | /// 147 | /// ``` 148 | /// # use snmp_mp::{PduType, ScopedPdu}; 149 | /// let mut scoped_pdu = ScopedPdu::new(1); 150 | /// scoped_pdu.set_pdu_type(PduType::GetNextRequest); 151 | /// assert_eq!(scoped_pdu.pdu_type(), PduType::GetNextRequest); 152 | /// ``` 153 | pub fn set_pdu_type(&mut self, pdu_type: PduType) -> &mut Self { 154 | self.pdu_type = pdu_type; 155 | self 156 | } 157 | 158 | /// Returns the request ID. 159 | /// 160 | /// # Examples 161 | /// 162 | /// ``` 163 | /// # use snmp_mp::ScopedPdu; 164 | /// # let scoped_pdu = ScopedPdu::new(1); 165 | /// let request_id = scoped_pdu.request_id(); 166 | /// ``` 167 | pub fn request_id(&self) -> i32 { 168 | self.request_id 169 | } 170 | 171 | /// Sets the request ID. 172 | /// 173 | /// # Examples 174 | /// 175 | /// ``` 176 | /// # use snmp_mp::ScopedPdu; 177 | /// let mut scoped_pdu = ScopedPdu::new(1); 178 | /// scoped_pdu.set_request_id(1234); 179 | /// assert_eq!(scoped_pdu.request_id(), 1234); 180 | /// ``` 181 | pub fn set_request_id(&mut self, request_id: i32) -> &mut Self { 182 | self.request_id = request_id; 183 | self 184 | } 185 | 186 | /// Returns the error status. 187 | /// 188 | /// # Examples 189 | /// 190 | /// ``` 191 | /// # use snmp_mp::ScopedPdu; 192 | /// # let scoped_pdu = ScopedPdu::new(1); 193 | /// let error_status = scoped_pdu.error_status(); 194 | /// ``` 195 | pub fn error_status(&self) -> PduErrorStatus { 196 | self.error_status 197 | } 198 | 199 | /// Sets the error status. 200 | /// 201 | /// # Examples 202 | /// 203 | /// ``` 204 | /// # use snmp_mp::{PduErrorStatus, PduType, ScopedPdu}; 205 | /// let mut scoped_pdu = ScopedPdu::new(1); 206 | /// scoped_pdu.set_error_status(PduErrorStatus::NoSuchName); 207 | /// assert_eq!(scoped_pdu.error_status(), PduErrorStatus::NoSuchName); 208 | /// ``` 209 | pub fn set_error_status(&mut self, error_status: PduErrorStatus) -> &mut Self { 210 | self.error_status = error_status; 211 | self 212 | } 213 | 214 | /// Returns the error index. 215 | /// 216 | /// # Examples 217 | /// 218 | /// ``` 219 | /// # use snmp_mp::ScopedPdu; 220 | /// # let scoped_pdu = ScopedPdu::new(1); 221 | /// assert_eq!(scoped_pdu.error_index(), 0); 222 | /// ``` 223 | pub fn error_index(&self) -> u32 { 224 | self.error_index 225 | } 226 | 227 | /// Sets the error index. 228 | /// 229 | /// # Examples 230 | /// 231 | /// ``` 232 | /// # use snmp_mp::ScopedPdu; 233 | /// let mut scoped_pdu = ScopedPdu::new(1); 234 | /// scoped_pdu.set_error_index(1); 235 | /// assert_eq!(scoped_pdu.error_index(), 1); 236 | /// ``` 237 | pub fn set_error_index(&mut self, error_index: u32) -> &mut Self { 238 | self.error_index = error_index; 239 | self 240 | } 241 | 242 | /// Returns the variable bindings. 243 | /// 244 | /// # Examples 245 | /// 246 | /// ``` 247 | /// # use snmp_mp::ScopedPdu; 248 | /// # let scoped_pdu = ScopedPdu::new(1); 249 | /// let var_binds = scoped_pdu.var_binds(); 250 | /// ``` 251 | pub fn var_binds(&self) -> &[VarBind] { 252 | &self.var_binds 253 | } 254 | 255 | /// Sets the variable bindings. 256 | /// 257 | /// # Examples 258 | /// 259 | /// ``` 260 | /// # use snmp_mp::{ObjectIdent, ScopedPdu, VarBind, VarValue}; 261 | /// # let oid = ObjectIdent::from_slice(&[0x01, 0x03, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00]); 262 | /// # let var_bind = VarBind::new(oid); 263 | /// # let var_binds = vec![var_bind]; 264 | /// 265 | /// let mut scoped_pdu = ScopedPdu::new(1); 266 | /// scoped_pdu.set_var_binds(var_binds.clone()); 267 | /// assert_eq!(var_binds, scoped_pdu.var_binds()); 268 | /// ``` 269 | pub fn set_var_binds(&mut self, var_binds_iter: I) -> &mut Self 270 | where 271 | I: IntoIterator, 272 | { 273 | self.var_binds.clear(); 274 | self.var_binds.extend(var_binds_iter); 275 | self 276 | } 277 | 278 | /// Appends an element to the back of the list of variable bindings. 279 | /// 280 | /// # Examples 281 | /// 282 | /// ``` 283 | /// # use snmp_mp::{ObjectIdent, ScopedPdu, VarBind}; 284 | /// let oid = ObjectIdent::from_slice(&[0x01, 0x03, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00]); 285 | /// let var_bind = VarBind::new(oid); 286 | /// 287 | /// let mut scoped_pdu = ScopedPdu::new(1); 288 | /// scoped_pdu.push_var_bind(var_bind.clone()); 289 | /// assert_eq!(vec![var_bind], scoped_pdu.var_binds()); 290 | /// ``` 291 | pub fn push_var_bind(&mut self, var_bind: VarBind) -> &mut Self { 292 | self.var_binds.push(var_bind); 293 | self 294 | } 295 | 296 | /// Encodes a scoped PDU. 297 | /// 298 | /// # Examples 299 | /// 300 | /// ``` 301 | /// # use snmp_mp::ScopedPdu; 302 | /// let scoped_pdu = ScopedPdu::new(1); 303 | /// let encoded_scoped_pdu = scoped_pdu.encode(); 304 | /// ``` 305 | pub fn encode(&self) -> Vec { 306 | yasna::construct_der(|writer| { 307 | writer.write_sequence(|writer| { 308 | writer.next().write_bytes(&self.engine_id); 309 | writer.next().write_bytes(&self.context_name); 310 | self.encode_pdu(writer.next()); 311 | }) 312 | }) 313 | } 314 | 315 | /// Decodes an encoded scope PDU. 316 | /// 317 | /// # Errors 318 | /// 319 | /// If the scoped PDU is not properly formed a result with 320 | /// [MalformedMsg](enum.MsgProcessingError.html#variant.MalformedMsg) error is returned. 321 | /// 322 | /// # Examples 323 | /// 324 | /// ```no_run 325 | /// # use snmp_mp::ScopedPdu; 326 | /// # fn main() -> snmp_mp::MsgProcessingResult<()> { 327 | /// # let encoded_scoped_pdu = []; 328 | /// let scoped_pdu = ScopedPdu::decode(&encoded_scoped_pdu)?; 329 | /// # Ok(()) 330 | /// # } 331 | /// ``` 332 | pub fn decode(buf: &[u8]) -> MsgProcessingResult { 333 | // The BER parsing library returns an error when there are bytes remaining at the end of 334 | // the buffer. This might happen when parsing a decrypted scoped PDU since the padding is 335 | // not removed. So return the scoped PDU even if the 'Extra' error is raised. 336 | let mut scoped_pdu = None; 337 | 338 | let result = yasna::parse_ber(buf, |reader| { 339 | scoped_pdu = Some(Self::decode_from_reader(reader)?); 340 | Ok(()) 341 | }); 342 | 343 | if let Err(error) = result { 344 | if error.kind() != ASN1ErrorKind::Extra { 345 | return Err(MsgProcessingError::MalformedMsg); 346 | } 347 | } 348 | 349 | Ok(scoped_pdu.unwrap()) 350 | } 351 | 352 | // Decodes an encoded scope PDU using the supplied BER reader. Used internally to decode 353 | // plaintext and decrypted scoped PDU. 354 | pub(crate) fn decode_from_reader(reader: BERReader) -> ASN1Result { 355 | reader.read_sequence(|reader| { 356 | let engine_id = reader.next().read_bytes()?; 357 | let context_name = reader.next().read_bytes()?; 358 | 359 | // Each PDU type has it's own implicit tag. 360 | let tag = reader.next().lookahead_tag()?; 361 | if tag.tag_class != TagClass::ContextSpecific { 362 | return Err(ASN1Error::new(ASN1ErrorKind::Invalid)); 363 | } 364 | 365 | let pdu_type = PduType::try_from(tag.tag_number) 366 | .map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))?; 367 | 368 | reader.next().read_tagged_implicit(tag, |reader| { 369 | reader.read_sequence(|reader| { 370 | let request_id = reader.next().read_i32()?; 371 | 372 | let error_status = PduErrorStatus::try_from(reader.next().read_u8()?) 373 | .map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))?; 374 | 375 | let error_index = reader.next().read_u32()?; 376 | let var_binds = reader.next().collect_sequence_of(VarBind::decode)?; 377 | 378 | Ok(Self { 379 | engine_id, 380 | context_name, 381 | pdu_type, 382 | request_id, 383 | error_status, 384 | error_index, 385 | var_binds, 386 | }) 387 | }) 388 | }) 389 | }) 390 | } 391 | 392 | fn encode_pdu(&self, writer: DERWriter) { 393 | let pdu_type = self.pdu_type as u64; 394 | let tag = Tag::context(pdu_type); 395 | 396 | writer.write_tagged_implicit(tag, |writer| { 397 | writer.write_sequence(|writer| { 398 | writer.next().write_i32(self.request_id); 399 | writer.next().write_u8(self.error_status as u8); 400 | writer.next().write_u32(self.error_index); 401 | 402 | writer.next().write_sequence_of(|writer| { 403 | for var_bind in &self.var_binds { 404 | var_bind.encode(writer.next()); 405 | } 406 | }); 407 | }); 408 | }) 409 | } 410 | } 411 | -------------------------------------------------------------------------------- /src/snmp_mp/src/scoped_pdu_data.rs: -------------------------------------------------------------------------------- 1 | use crate::ScopedPdu; 2 | 3 | /// Represents either the plaintext scoped PDU if the privacy flag is not set, or it represents an 4 | /// encrypted PDU encoded as a byte string. 5 | /// 6 | /// # Examples 7 | /// 8 | /// ``` 9 | /// use snmp_mp::{ScopedPdu, ScopedPduData}; 10 | /// 11 | /// let scoped_pdu_data = ScopedPduData::Plaintext(ScopedPdu::new(1)); 12 | /// let scoped_pdu = scoped_pdu_data.plaintext(); 13 | /// assert_eq!(scoped_pdu.unwrap(), &ScopedPdu::new(1)); 14 | /// ``` 15 | #[derive(Debug, Clone, Eq, PartialEq, Hash)] 16 | pub enum ScopedPduData { 17 | /// Plaintext scoped PDU. 18 | Plaintext(ScopedPdu), 19 | /// Encrypted PDU as a byte string. 20 | Encrypted(Vec), 21 | } 22 | 23 | impl ScopedPduData { 24 | /// Returns a reference to the plaintext scoped PDU, or `None` if the scoped PDU is encrypted. 25 | /// 26 | /// # Examples 27 | /// 28 | /// ``` 29 | /// # use snmp_mp::{ScopedPdu, ScopedPduData}; 30 | /// let scoped_pdu_data = ScopedPduData::Plaintext(ScopedPdu::new(1)); 31 | /// let scoped_pdu = scoped_pdu_data.plaintext(); 32 | /// assert_eq!(scoped_pdu.unwrap(), &ScopedPdu::new(1)); 33 | /// ``` 34 | pub fn plaintext(&self) -> Option<&ScopedPdu> { 35 | match self { 36 | ScopedPduData::Plaintext(ref scoped_pdu) => Some(scoped_pdu), 37 | _ => None, 38 | } 39 | } 40 | 41 | /// Returns a mutable reference to the plaintext scoped PDU, or `None` if the scoped PDU is 42 | /// encrypted. 43 | /// 44 | /// # Examples 45 | /// 46 | /// ``` 47 | /// # use snmp_mp::{ScopedPdu, ScopedPduData}; 48 | /// let mut scoped_pdu_data = ScopedPduData::Plaintext(ScopedPdu::new(1)); 49 | /// let scoped_pdu = scoped_pdu_data.plaintext_mut().unwrap(); 50 | /// scoped_pdu.set_request_id(1234); 51 | /// assert_eq!(scoped_pdu.request_id(), 1234); 52 | /// ``` 53 | pub fn plaintext_mut(&mut self) -> Option<&mut ScopedPdu> { 54 | match self { 55 | ScopedPduData::Plaintext(ref mut scoped_pdu) => Some(scoped_pdu), 56 | _ => None, 57 | } 58 | } 59 | 60 | /// Returns a reference to the encrypted scoped PDU, or `None` if the scoped PDU is plaintext. 61 | /// 62 | /// # Examples 63 | /// 64 | /// ``` 65 | /// # use snmp_mp::ScopedPduData; 66 | /// # let encrypted_scoped_pdu = b"encrypted".to_vec(); 67 | /// let scoped_pdu_data = ScopedPduData::Encrypted(encrypted_scoped_pdu.clone()); 68 | /// let optional_encrypted_scoped_pdu = scoped_pdu_data.encrypted(); 69 | /// assert_eq!(optional_encrypted_scoped_pdu.unwrap(), &encrypted_scoped_pdu[..]); 70 | /// ``` 71 | pub fn encrypted(&self) -> Option<&[u8]> { 72 | match self { 73 | ScopedPduData::Encrypted(ref encrypted_scoped_pdu) => Some(encrypted_scoped_pdu), 74 | _ => None, 75 | } 76 | } 77 | 78 | // Returns a reference to the plaintext scoped PDU, or panics if the scoped PDU is encrypted. 79 | pub(crate) fn unwrap_plaintext(&self) -> &ScopedPdu { 80 | match self { 81 | ScopedPduData::Plaintext(ref scoped_pdu) => scoped_pdu, 82 | _ => panic!("not a plaintext scoped PDU"), 83 | } 84 | } 85 | } 86 | 87 | impl Default for ScopedPduData { 88 | fn default() -> Self { 89 | Self::Plaintext(ScopedPdu::default()) 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/snmp_mp/tests/scoped_pdu.rs: -------------------------------------------------------------------------------- 1 | use snmp_mp::{MsgProcessingResult, PduErrorStatus, ScopedPdu}; 2 | 3 | #[test] 4 | fn it_encodes_scoped_pdu() { 5 | let mut scoped_pdu = ScopedPdu::new(1893886541); 6 | scoped_pdu 7 | .set_engine_id(b"80001f8880faa811600fa2c55e00000000") 8 | .set_context_name(b"context_name"); 9 | 10 | let encoded_scoped_pdu = scoped_pdu.encode(); 11 | let expected = vec![ 12 | 0x30, 0x42, 0x04, 0x22, 0x38, 0x30, 0x30, 0x30, 0x31, 0x66, 0x38, 0x38, 0x38, 0x30, 0x66, 13 | 0x61, 0x61, 0x38, 0x31, 0x31, 0x36, 0x30, 0x30, 0x66, 0x61, 0x32, 0x63, 0x35, 0x35, 0x65, 14 | 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x04, 0x0C, 0x63, 0x6F, 0x6E, 0x74, 0x65, 15 | 0x78, 0x74, 0x5F, 0x6E, 0x61, 0x6D, 0x65, 0xA0, 0x0E, 0x02, 0x04, 0x70, 0xE2, 0x6A, 0x4D, 16 | 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x00, 17 | ]; 18 | 19 | assert_eq!(encoded_scoped_pdu, expected); 20 | } 21 | 22 | #[test] 23 | fn it_decodes_scoped_pdu() -> MsgProcessingResult<()> { 24 | let encoded_scoped_pdu = vec![ 25 | 0x30, 0x33, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 26 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x1C, 0x02, 0x04, 0x70, 0xE2, 0x6A, 27 | 0x4D, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 28 | 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x05, 0x00, 29 | ]; 30 | let scoped_pdu = ScopedPdu::decode(&encoded_scoped_pdu)?; 31 | 32 | assert_eq!(scoped_pdu.request_id(), 1893886541); 33 | 34 | let engine_id = [ 35 | 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 0xc5, 0x5E, 0x00, 0x00, 36 | 0x00, 0x00, 37 | ]; 38 | assert_eq!(scoped_pdu.engine_id(), engine_id); 39 | 40 | assert_eq!(scoped_pdu.error_status(), PduErrorStatus::NoError); 41 | assert_eq!(scoped_pdu.error_index(), 0); 42 | 43 | Ok(()) 44 | } 45 | 46 | #[test] 47 | fn it_decodes_scoped_pdu_with_extra_bytes_at_the_end() -> MsgProcessingResult<()> { 48 | let encoded_scoped_pdu = vec![ 49 | 0x30, 0x33, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 50 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x1C, 0x02, 0x04, 0x70, 0xE2, 0x6A, 51 | 0x4D, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 52 | 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x05, 0x00, 0x02, 0x02, 53 | ]; 54 | let scoped_pdu = ScopedPdu::decode(&encoded_scoped_pdu)?; 55 | 56 | assert_eq!(scoped_pdu.request_id(), 1893886541); 57 | 58 | let engine_id = [ 59 | 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 0xc5, 0x5E, 0x00, 0x00, 60 | 0x00, 0x00, 61 | ]; 62 | assert_eq!(scoped_pdu.engine_id(), engine_id); 63 | 64 | assert_eq!(scoped_pdu.error_status(), PduErrorStatus::NoError); 65 | assert_eq!(scoped_pdu.error_index(), 0); 66 | 67 | Ok(()) 68 | } 69 | -------------------------------------------------------------------------------- /src/snmp_mp/tests/snmp_msg.rs: -------------------------------------------------------------------------------- 1 | use snmp_mp::{MsgProcessingResult, ObjectIdent, SnmpMsg, VarBind, VarValue}; 2 | 3 | #[test] 4 | fn it_encodes_snmp_msg() { 5 | let security_params = [ 6 | 0x30, 0x3a, 0x04, 0x11, 0x80, 0x00, 0x1f, 0x88, 0x80, 0xfa, 0xa8, 0x11, 0x60, 0x0f, 0xa2, 7 | 0xc5, 0x5e, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x04, 0x02, 0x03, 0x01, 0x1f, 0x27, 0x04, 8 | 0x0d, 0x64, 0x61, 0x76, 0x69, 0x64, 0x64, 0x75, 0x66, 0x72, 0x65, 0x73, 0x6e, 0x65, 0x04, 9 | 0x0c, 0x14, 0xdb, 0x5e, 0xec, 0xdd, 0x43, 0xb1, 0xc5, 0x1f, 0x7c, 0x42, 0xdf, 0x04, 0x00, 10 | ]; 11 | 12 | let mut msg = SnmpMsg::new(837040343); 13 | msg.set_reportable_flag() 14 | .set_auth_flag() 15 | .set_security_params(&security_params); 16 | 17 | if let Some(scoped_pdu) = msg.scoped_pdu_data.plaintext_mut() { 18 | let oid = ObjectIdent::from_slice(&[0x01, 0x03, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00]); 19 | let var_bind = VarBind::with_value(oid, VarValue::Unspecified); 20 | let var_binds = vec![var_bind]; 21 | 22 | let engine_id = [ 23 | 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 0xc5, 0x5E, 0x00, 24 | 0x00, 0x00, 0x00, 25 | ]; 26 | 27 | scoped_pdu 28 | .set_request_id(1918134953) 29 | .set_engine_id(&engine_id) 30 | .set_var_binds(var_binds); 31 | } 32 | 33 | let encoded_msg = msg.encode(); 34 | let expected = vec![ 35 | 0x30, 0x81, 0x89, 0x02, 0x01, 0x03, 0x30, 0x11, 0x02, 0x04, 0x31, 0xE4, 0x38, 0xD7, 0x02, 36 | 0x03, 0x00, 0xFF, 0xE3, 0x04, 0x01, 0x05, 0x02, 0x01, 0x03, 0x04, 0x3C, 0x30, 0x3A, 0x04, 37 | 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 0xC5, 0x5E, 0x00, 38 | 0x00, 0x00, 0x00, 0x02, 0x01, 0x04, 0x02, 0x03, 0x01, 0x1F, 0x27, 0x04, 0x0D, 0x64, 0x61, 39 | 0x76, 0x69, 0x64, 0x64, 0x75, 0x66, 0x72, 0x65, 0x73, 0x6E, 0x65, 0x04, 0x0C, 0x14, 0xDB, 40 | 0x5E, 0xEC, 0xDD, 0x43, 0xB1, 0xC5, 0x1F, 0x7C, 0x42, 0xDF, 0x04, 0x00, 0x30, 0x33, 0x04, 41 | 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 0xC5, 0x5E, 0x00, 42 | 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x1C, 0x02, 0x04, 0x72, 0x54, 0x6A, 0xA9, 0x02, 0x01, 43 | 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x02, 0x01, 44 | 0x01, 0x01, 0x00, 0x05, 0x00, 45 | ]; 46 | 47 | assert_eq!(encoded_msg, expected); 48 | } 49 | 50 | #[test] 51 | fn it_decodes_snmp_msg() -> MsgProcessingResult<()> { 52 | let encoded_msg = vec![ 53 | 0x30, 0x81, 0x89, 0x02, 0x01, 0x03, 0x30, 0x11, 0x02, 0x04, 0x31, 0xE4, 0x38, 0xD7, 0x02, 54 | 0x03, 0x00, 0xFF, 0xE3, 0x04, 0x01, 0x05, 0x02, 0x01, 0x03, 0x04, 0x3C, 0x30, 0x3A, 0x04, 55 | 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 0xC5, 0x5E, 0x00, 56 | 0x00, 0x00, 0x00, 0x02, 0x01, 0x04, 0x02, 0x03, 0x01, 0x1F, 0x27, 0x04, 0x0D, 0x64, 0x61, 57 | 0x76, 0x69, 0x64, 0x64, 0x75, 0x66, 0x72, 0x65, 0x73, 0x6E, 0x65, 0x04, 0x0C, 0x14, 0xDB, 58 | 0x5E, 0xEC, 0xDD, 0x43, 0xB1, 0xC5, 0x1F, 0x7C, 0x42, 0xDF, 0x04, 0x00, 0x30, 0x33, 0x04, 59 | 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 0xC5, 0x5E, 0x00, 60 | 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x1C, 0x02, 0x04, 0x72, 0x54, 0x6A, 0xA9, 0x02, 0x01, 61 | 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x02, 0x01, 62 | 0x01, 0x01, 0x00, 0x05, 0x00, 63 | ]; 64 | let msg = SnmpMsg::decode(&encoded_msg)?; 65 | 66 | assert_eq!(msg.id(), 837040343); 67 | assert!(msg.is_reportable()); 68 | assert!(msg.is_auth()); 69 | 70 | let security_params = [ 71 | 0x30, 0x3a, 0x04, 0x11, 0x80, 0x00, 0x1f, 0x88, 0x80, 0xfa, 0xa8, 0x11, 0x60, 0x0f, 0xa2, 72 | 0xc5, 0x5e, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x04, 0x02, 0x03, 0x01, 0x1f, 0x27, 0x04, 73 | 0x0d, 0x64, 0x61, 0x76, 0x69, 0x64, 0x64, 0x75, 0x66, 0x72, 0x65, 0x73, 0x6e, 0x65, 0x04, 74 | 0x0c, 0x14, 0xdb, 0x5e, 0xec, 0xdd, 0x43, 0xb1, 0xc5, 0x1f, 0x7c, 0x42, 0xdf, 0x04, 0x00, 75 | ]; 76 | assert_eq!(msg.security_params(), &security_params[..]); 77 | 78 | Ok(()) 79 | } 80 | -------------------------------------------------------------------------------- /src/snmp_usm/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.2.1 (2023-03-15) 4 | 5 | * Bump 'aes' and 'cfb-mode' versions 6 | 7 | ## 0.2.0 (2020-08-27) 8 | 9 | * Rename `SecurityParams::discovery()` to `SecurityParams::for_discovery()`. 10 | * Add wrapper around traits needed for digest algorithms. This simplifies specifying trait bounds. 11 | * Use padding scheme described in RFC 3414. The previous padding scheme caused failures when trying to unpad the 12 | encrypted scoped PDU. 13 | * Add `WithLocalizedKey` trait to generically create types with a localized key. 14 | * Change `engine_boots` and `engine_time` type to `u32`. 15 | * Change privacy keys 'salt' type to unsigned integer. 16 | 17 | ## 0.1.0 (2020-07-19) 18 | 19 | Initial release. 20 | -------------------------------------------------------------------------------- /src/snmp_usm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "snmp_usm" 3 | description = "Implementation of the User-based Security Model (USM) for Simple Network Management Protocol (SNMP) version 3." 4 | version = "0.2.1" # remember to update html_root_url 5 | authors = ["David Dufresne "] 6 | license = "MIT OR Apache-2.0" 7 | edition = "2018" 8 | readme = "README.md" 9 | repository = "https://github.com/davedufresne/modern_snmp" 10 | keywords = ["snmp", "snmpv3", "usm", "security"] 11 | categories = ["network-programming"] 12 | 13 | [dependencies] 14 | aes = "0.8.2" 15 | block-modes = "0.5.0" 16 | cfb-mode = "0.8.2" 17 | des = "0.4.0" 18 | hmac = "0.8.1" 19 | md-5 = "0.9.1" 20 | sha-1 = "0.9.1" 21 | yasna = "0.3.2" 22 | -------------------------------------------------------------------------------- /src/snmp_usm/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 David Dufresne 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/snmp_usm/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2020 David Dufresne 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 4 | associated documentation files (the "Software"), to deal in the Software without restriction, 5 | including without limitation the rights to use, copy, modify, merge, publish, distribute, 6 | sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 7 | furnished to do so, subject to the following conditions: 8 | 9 | The above copyright notice and this permission notice shall be included in all copies or 10 | substantial portions of the Software. 11 | 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 13 | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 14 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 15 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 16 | OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/snmp_usm/README.md: -------------------------------------------------------------------------------- 1 | # Implementation of the User-based Security Model (USM) for SNMPv3 2 | 3 | **SNMP USM** provides SNMP message level security according to RFC 3414 and RFC 3826. It implements primitives that can be used by a security subsystem. 4 | 5 | Implemented features of USM: 6 | 7 | * HMAC-MD5-96 Authentication Protocol 8 | * HMAC-SHA-96 Authentication Protocol 9 | * Timeliness verification 10 | * DES encryption 11 | * AES encryption 12 | 13 | ## License 14 | 15 | Licensed under either of 16 | 17 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) 18 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 19 | 20 | at your option. 21 | 22 | ## Contribution 23 | 24 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 25 | -------------------------------------------------------------------------------- /src/snmp_usm/src/auth_key.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | pos_finder::PosFinder, LocalizedKey, Md5, SecurityError, SecurityParams, SecurityResult, Sha1, 3 | AUTH_PARAMS_LEN, AUTH_PARAMS_PLACEHOLDER, 4 | }; 5 | use hmac::{Hmac, Mac, NewMac}; 6 | use md5::digest::{BlockInput, FixedOutput, Reset, Update}; 7 | use std::ops::Range; 8 | 9 | // Duration in seconds. 10 | const TIME_WINDOW: u32 = 150; 11 | 12 | /// Convenience wrapper around `Update`, `BlockInput`, `FixedOutput`, `Reset`, `Default`, and 13 | /// `Clone` traits. Useful as trait bound where a digest algorithm is needed. 14 | pub trait Digest: Update + BlockInput + FixedOutput + Reset + Default + Clone {} 15 | impl Digest for Md5 {} 16 | impl Digest for Sha1 {} 17 | 18 | /// Authentication key used to check data integrity and data origin. 19 | /// 20 | /// It is constructed from a [Localizedkey](struct.LocalizedKey.html) and parameterized to use 21 | /// various authentication protocols. 22 | #[derive(Clone, Debug, Eq, PartialEq, Hash)] 23 | pub struct AuthKey<'a, D> { 24 | localized_key: LocalizedKey<'a, D>, 25 | } 26 | 27 | impl<'a, D: 'a> AuthKey<'a, D> { 28 | /// Constructs a new `AuthKey` using a localized key. 29 | /// 30 | /// # Examples 31 | /// 32 | /// ``` 33 | /// use snmp_usm::{AuthKey, LocalizedSha1Key}; 34 | /// 35 | /// # let passwd = b"1234"; 36 | /// # let engine_id = b"1234"; 37 | /// let localized_key = LocalizedSha1Key::new(passwd, engine_id); 38 | /// let auth_key = AuthKey::new(localized_key); 39 | /// ``` 40 | pub fn new(localized_key: LocalizedKey<'a, D>) -> Self { 41 | Self { localized_key } 42 | } 43 | 44 | // Returns the security parameters and authentication parameters ranges of an SNMP message. 45 | fn params_ranges(msg: &[u8]) -> SecurityResult<(Range, Range)> { 46 | let mut pos_finder = PosFinder::new(msg); 47 | 48 | pos_finder.step_into_seq()?; // Message sequence 49 | pos_finder.skip_int()?; // Version 50 | pos_finder.skip_seq()?; // Header data 51 | // Security parameters as octet string 52 | let security_params_range = pos_finder.step_into_octet_str()?; 53 | 54 | let auth_params_range = Self::find_auth_params_range(&mut pos_finder) 55 | .map_err(|_| SecurityError::MalformedSecurityParams)?; 56 | 57 | let auth_params_len = auth_params_range.end - auth_params_range.start; 58 | if auth_params_len != AUTH_PARAMS_LEN { 59 | return Err(SecurityError::WrongAuthParams); 60 | } 61 | 62 | Ok((security_params_range, auth_params_range)) 63 | } 64 | 65 | fn find_auth_params_range(pos_finder: &mut PosFinder) -> SecurityResult> { 66 | pos_finder.step_into_seq()?; // Security parameters 67 | pos_finder.skip_octet_str()?; // Authoritative engine ID 68 | pos_finder.skip_int()?; // Authoritative engine boots 69 | pos_finder.skip_int()?; // Authoritative engine time 70 | pos_finder.skip_octet_str()?; // Username 71 | 72 | pos_finder.step_into_octet_str() // Authentication parameters 73 | } 74 | 75 | fn validate_timeliness( 76 | security_params: &SecurityParams, 77 | local_engine_id: &[u8], 78 | local_engine_boots: u32, 79 | local_engine_time: u32, 80 | ) -> SecurityResult<()> { 81 | if local_engine_boots >= SecurityParams::ENGINE_BOOTS_MAX { 82 | return Err(SecurityError::NotInTimeWindow); 83 | } 84 | 85 | let is_authoritative_engine = security_params.engine_id() == local_engine_id; 86 | if is_authoritative_engine { 87 | Self::validate_timeliness_for_authoritative( 88 | security_params, 89 | local_engine_boots, 90 | local_engine_time, 91 | )?; 92 | } else { 93 | Self::validate_timeliness_for_non_authoritative( 94 | security_params, 95 | local_engine_boots, 96 | local_engine_time, 97 | )?; 98 | } 99 | 100 | Ok(()) 101 | } 102 | 103 | fn validate_timeliness_for_authoritative( 104 | security_params: &SecurityParams, 105 | local_engine_boots: u32, 106 | local_engine_time: u32, 107 | ) -> SecurityResult<()> { 108 | if security_params.engine_boots() != local_engine_boots { 109 | return Err(SecurityError::NotInTimeWindow); 110 | } 111 | 112 | let time_diff = Self::diff(security_params.engine_time(), local_engine_time); 113 | if time_diff > TIME_WINDOW { 114 | return Err(SecurityError::NotInTimeWindow); 115 | } 116 | 117 | Ok(()) 118 | } 119 | 120 | fn validate_timeliness_for_non_authoritative( 121 | security_params: &SecurityParams, 122 | local_engine_boots: u32, 123 | local_engine_time: u32, 124 | ) -> SecurityResult<()> { 125 | if security_params.engine_boots() < local_engine_boots { 126 | return Err(SecurityError::NotInTimeWindow); 127 | } 128 | 129 | if security_params.engine_boots() == local_engine_boots 130 | && Self::less_than_over( 131 | TIME_WINDOW, 132 | security_params.engine_time(), 133 | local_engine_time, 134 | ) 135 | { 136 | return Err(SecurityError::NotInTimeWindow); 137 | } 138 | 139 | Ok(()) 140 | } 141 | 142 | fn diff(lhs: u32, rhs: u32) -> u32 { 143 | if lhs > rhs { 144 | lhs - rhs 145 | } else { 146 | rhs - lhs 147 | } 148 | } 149 | 150 | fn less_than_over(amount: u32, lhs: u32, rhs: u32) -> bool { 151 | if lhs > rhs { 152 | return false; 153 | } 154 | rhs - lhs > amount 155 | } 156 | } 157 | 158 | impl<'a, D: 'a> AuthKey<'a, D> 159 | where 160 | D: Digest, 161 | { 162 | /// Authenticates an incoming SNMP message. 163 | /// 164 | /// The timeliness check is always preformed when authentication is requested. If the 165 | /// authentication and the timeliness validation succeed, a security subsystem would update its 166 | /// local notion of engine boots, engine time and latest received engine time for the 167 | /// corresponding SNMP engine ID. 168 | /// 169 | /// # Arguments 170 | /// 171 | /// * `msg` - The SNMP message to authenticate 172 | /// * `local_engine_id` - The authoritative engine ID 173 | /// * `local_engine_boots` - The local notion of the authoritative engine boots 174 | /// * `local_engine_time` - The local notion of the authoritative engine time 175 | /// 176 | /// # Errors 177 | /// 178 | /// If the message is not properly formed a result with 179 | /// [MalformedMsg](enum.SecurityError.html#variant.MalformedMsg) error is returned. 180 | /// 181 | /// A [MalformedSecurityParams](enum.SecurityError.html#variant.MalformedSecurityParams) error 182 | /// result is returned if the security parameters are not properly formed. 183 | /// 184 | /// If the message could not be authenticated because the authentication parameters don't 185 | /// match the digest, a result with 186 | /// [WrongAuthParams](enum.SecurityError.html#variant.WrongAuthParams) error is returned. 187 | /// 188 | /// If the timeliness validation fails a result with 189 | /// [NotInTimeWindow](enum.SecurityError.html#variant.NotInTimeWindow) is returned. Timeliness 190 | /// validation will fail if `local_engine_boots` or `local_engine_time` is less than `0`. 191 | /// 192 | /// # Examples 193 | /// 194 | /// ```no_run 195 | /// use snmp_usm::{LocalizedKey, Sha1AuthKey}; 196 | /// 197 | /// # let mut in_msg = []; 198 | /// # let engine_id = []; 199 | /// # let engine_boots = 0; 200 | /// # let engine_time = 0; 201 | /// let localized_key = LocalizedKey::new(b"password", b"engine_id"); 202 | /// let key = Sha1AuthKey::new(localized_key); 203 | /// key.auth_in_msg(&mut in_msg, &engine_id, engine_boots, engine_time); 204 | /// ``` 205 | pub fn auth_in_msg( 206 | &self, 207 | msg: &mut [u8], 208 | local_engine_id: &[u8], 209 | local_engine_boots: u32, 210 | local_engine_time: u32, 211 | ) -> SecurityResult<()> { 212 | let (security_params_range, auth_params_range) = Self::params_ranges(msg)?; 213 | 214 | let mut saved_auth_params: [u8; AUTH_PARAMS_LEN] = [0x0; AUTH_PARAMS_LEN]; 215 | saved_auth_params.copy_from_slice(&msg[auth_params_range.start..auth_params_range.end]); 216 | 217 | msg[auth_params_range.start..auth_params_range.end] 218 | .copy_from_slice(&AUTH_PARAMS_PLACEHOLDER); 219 | let auth_params = self.hmac(msg); 220 | if saved_auth_params != auth_params[..] { 221 | return Err(SecurityError::WrongAuthParams); 222 | } 223 | 224 | msg[auth_params_range].copy_from_slice(&saved_auth_params); 225 | 226 | let security_params = SecurityParams::decode(&msg[security_params_range])?; 227 | Self::validate_timeliness( 228 | &security_params, 229 | local_engine_id, 230 | local_engine_boots, 231 | local_engine_time, 232 | )?; 233 | 234 | Ok(()) 235 | } 236 | 237 | /// Authenticates an outgoing SNMP message. 238 | /// 239 | /// # Errors 240 | /// 241 | /// If the message is not properly formed a result with 242 | /// [MalformedMsg](enum.SecurityError.html#variant.MalformedMsg) error is returned. 243 | /// 244 | /// If the security parameters are not properly formed a result with 245 | /// [MalformedSecurityParams](enum.SecurityError.html#variant.MalformedSecurityParams) error is 246 | /// returned. 247 | /// 248 | /// # Examples 249 | /// 250 | /// ```no_run 251 | /// use snmp_usm::{LocalizedKey, Sha1AuthKey}; 252 | /// 253 | /// # fn main() -> snmp_usm::SecurityResult<()> { 254 | /// # let mut out_msg = []; 255 | /// let localized_key = LocalizedKey::new(b"password", b"engine_id"); 256 | /// let key = Sha1AuthKey::new(localized_key); 257 | /// key.auth_out_msg(&mut out_msg)?; 258 | /// # Ok(()) 259 | /// # } 260 | /// ``` 261 | pub fn auth_out_msg(&self, msg: &mut [u8]) -> SecurityResult<()> { 262 | let (_, auth_params_range) = Self::params_ranges(msg)?; 263 | let auth_params = self.hmac(msg); 264 | msg[auth_params_range].copy_from_slice(&auth_params); 265 | 266 | Ok(()) 267 | } 268 | 269 | // Calculates the HMAC of the SNMP message. 270 | fn hmac(&self, msg: &[u8]) -> Vec { 271 | let mut mac = Hmac::::new_varkey(self.localized_key.bytes()).unwrap(); 272 | 273 | mac.update(msg); 274 | let result = mac.finalize(); 275 | let bytes = result.into_bytes(); 276 | 277 | bytes[0..AUTH_PARAMS_LEN].to_vec() 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /src/snmp_usm/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::fmt::{Display, Formatter, Result}; 3 | use std::io; 4 | 5 | /// The error type for security related operations. 6 | #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] 7 | pub enum SecurityError { 8 | /// Decryption error occurred. 9 | DecryptError, 10 | /// The SNMP message was malformed. 11 | MalformedMsg, 12 | /// The security parameters were malformed. 13 | MalformedSecurityParams, 14 | /// The authentication parameters didn't match the digest. 15 | WrongAuthParams, 16 | /// The SNMP message was considered to be outside the time window. 17 | NotInTimeWindow, 18 | } 19 | 20 | impl Display for SecurityError { 21 | fn fmt(&self, formatter: &mut Formatter) -> Result { 22 | match self { 23 | Self::DecryptError => "decryption error".fmt(formatter), 24 | Self::MalformedMsg => "malformed SNMP message".fmt(formatter), 25 | Self::MalformedSecurityParams => "malformed security parameters".fmt(formatter), 26 | Self::NotInTimeWindow => "not in time window".fmt(formatter), 27 | Self::WrongAuthParams => "wrong authentication parameters".fmt(formatter), 28 | } 29 | } 30 | } 31 | 32 | impl Error for SecurityError {} 33 | 34 | #[doc(hidden)] 35 | impl From for io::Error { 36 | fn from(parse_error: SecurityError) -> Self { 37 | Self::new(io::ErrorKind::InvalidData, parse_error) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/snmp_usm/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc(html_root_url = "https://docs.rs/snmp_usm/0.2.1")] 2 | 3 | //! # Implementation of the User-based Security Model (USM) for SNMPv3 4 | //! 5 | //! SNMP USM provides SNMP message level security according to RFC 3414 and RFC 3826. It implements 6 | //! primitives that can be used by a security subsystem. 7 | //! 8 | //! Implemented features of USM: 9 | //! 10 | //! * HMAC-MD5-96 Authentication Protocol 11 | //! * HMAC-SHA-96 Authentication Protocol 12 | //! * Timeliness verification 13 | //! * DES encryption 14 | //! * AES encryption 15 | //! 16 | //! ## Authentication and Privacy 17 | //! 18 | //! When privacy is used with authentication, the privacy key must use the same message-digest 19 | //! algorithm as the authentication key. As an example, if the [AuthKey](struct.AuthKey.html) is 20 | //! constructed with a [LocalizedKey](struct.LocalizedKey.html) specialized with the MD5 21 | //! message-digest algorithm, then the [PrivKey](struct.PrivKey.html) must be constructed with a 22 | //! `LocalizedKey` specialized with the MD5 message-digest algorithm. 23 | //! 24 | //! ## Authentication and time synchronization 25 | //! 26 | //! If authenticated communication is required, then the discovery process should also establish 27 | //! time synchronization with the authoritative SNMP engine. This may be accomplished by sending an 28 | //! authenticated Request message with the value of msgAuthoritativeEngineID set to the previously 29 | //! learned snmpEngineID and with the values of msgAuthoritativeEngineBoots and 30 | //! msgAuthoritativeEngineTime set to zero. 31 | //! 32 | //! ## Examples 33 | //! 34 | //! A fictional message processing subsystem is used to clarify the examples. 35 | //! 36 | //! ```no_run 37 | //! use snmp_usm::{ 38 | //! Aes128PrivKey, AuthKey, LocalizedMd5Key, PrivKey, SecurityParams, WithLocalizedKey 39 | //! }; 40 | //! 41 | //! # fn main() -> snmp_usm::SecurityResult<()> { 42 | //! # let passwd = []; 43 | //! # let engine_id = []; 44 | //! # let scoped_pdu = vec![]; 45 | //! # let incoming_security_params = []; 46 | //! // The password and engine ID are supplied by the security subsystem. 47 | //! let localized_key = LocalizedMd5Key::new(&passwd, &engine_id); 48 | //! 49 | //! let priv_key = Aes128PrivKey::with_localized_key(localized_key.clone()); 50 | //! # let mut security_params = SecurityParams::decode(&incoming_security_params)?; 51 | //! // The security parameters are constructed from the local authoritative engine data. 52 | //! let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 53 | //! 54 | //! // The message processing service would set the encrypted scoped PDU for the outgoing message. 55 | //! // out_msg.set_encrypted_scoped_pdu(encrypted_scoped_pdu); 56 | //! 57 | //! security_params 58 | //! .set_username(b"username") 59 | //! .set_priv_params(&salt) 60 | //! .set_auth_params_placeholder(); 61 | //! let encoded_security_params = security_params.encode(); 62 | //! 63 | //! // The message processing service would set the security parameters of the outgoing message and 64 | //! // encode it. 65 | //! // out_msg.set_security_params(&encoded_security_params); 66 | //! // let out_msg = out_msg.encode(); 67 | //! 68 | //! let auth_key = AuthKey::new(localized_key); 69 | //! 70 | //! // Authenticate the outgoing message. 71 | //! # let mut out_msg = []; 72 | //! auth_key.auth_out_msg(&mut out_msg)?; 73 | //! 74 | //! // Authenticate an incoming message. 75 | //! # let mut in_msg = []; 76 | //! # let local_engine_id = b""; 77 | //! # let local_engine_boots = 0; 78 | //! # let local_engine_time = 0; 79 | //! auth_key.auth_in_msg(&mut in_msg, local_engine_id, local_engine_boots, local_engine_time)?; 80 | //! # Ok(()) 81 | //! # } 82 | //! ``` 83 | 84 | mod auth_key; 85 | mod error; 86 | mod localized_key; 87 | mod pos_finder; 88 | mod priv_key; 89 | mod security_params; 90 | 91 | pub use auth_key::{AuthKey, Digest}; 92 | pub use error::SecurityError; 93 | pub use localized_key::{LocalizedKey, WithLocalizedKey}; 94 | pub use md5::Md5; 95 | pub use priv_key::{AesPrivKey, DesPrivKey, PrivKey}; 96 | pub use security_params::SecurityParams; 97 | pub use sha1::Sha1; 98 | 99 | /// Type alias for a localized key specialized with the MD5 message-digest algorithm. 100 | pub type LocalizedMd5Key<'a> = LocalizedKey<'a, Md5>; 101 | /// Type alias for a localized key specialized with the SHA-1 message-digest algorithm. 102 | pub type LocalizedSha1Key<'a> = LocalizedKey<'a, Sha1>; 103 | 104 | /// Type alias for an authentication key specialized with the MD5 message-digest algorithm. 105 | pub type Md5AuthKey<'a> = AuthKey<'a, Md5>; 106 | /// Type alias for an authentication key specialized with SHA-1 message-digest algorithm. 107 | pub type Sha1AuthKey<'a> = AuthKey<'a, Sha1>; 108 | 109 | /// Type alias for the result of a security operation. 110 | pub type SecurityResult = Result; 111 | 112 | // Type alias for all AES privacy keys 113 | pub type Aes128PrivKey<'a, D> = AesPrivKey<'a, D, 128>; 114 | pub type Aes192PrivKey<'a, D> = AesPrivKey<'a, D, 192>; 115 | pub type Aes256PrivKey<'a, D> = AesPrivKey<'a, D, 256>; 116 | 117 | const AUTH_PARAMS_LEN: usize = 12; 118 | const AUTH_PARAMS_PLACEHOLDER: [u8; AUTH_PARAMS_LEN] = [0x0; AUTH_PARAMS_LEN]; 119 | -------------------------------------------------------------------------------- /src/snmp_usm/src/localized_key.rs: -------------------------------------------------------------------------------- 1 | use md5::digest::{Digest, FixedOutput, Reset, Update}; 2 | use std::marker::PhantomData; 3 | 4 | // Password to key algorithm: 5 | // 6 | // 1- Forming a string of length 1,048,576 octets by repeating the value of the password as often 7 | // as necessary, truncating accordingly, and using the resulting string as the input to the 8 | // hashing algorithm. The resulting digest, termed "digest1", is used in the next step. 9 | // 2- A second string is formed by concatenating digest1, the SNMP engine's snmpEngineID value, and 10 | // digest1. This string is used as input to the hashing algorithm. 11 | // 12 | // See RFC 3414 for more details. 13 | 14 | const ONE_MEGABYTE: usize = 1_048_576; 15 | const PASSWD_BUF_LEN: usize = 64; 16 | const AES_256_KEY_LEN: usize = 32; 17 | 18 | /// Localized key used to verify the identity of users, verify the integrity of messages and 19 | /// encrypt messages. 20 | /// 21 | /// `LocalizedKey` is parametrize to use different message-digest algorithms. A key is unique for 22 | /// a user at an authoritative SNMP engine. It's usually cached by the security subsystem. 23 | #[derive(Clone, Debug, Eq, PartialEq, Hash)] 24 | pub struct LocalizedKey<'a, D> { 25 | bytes: Vec, 26 | _digest_type: PhantomData<&'a D>, 27 | orig_len: usize, 28 | } 29 | 30 | impl<'a, D> LocalizedKey<'a, D> { 31 | pub(crate) fn bytes(&self) -> &[u8] { 32 | &self.bytes[..self.orig_len] 33 | } 34 | 35 | pub(crate) fn bytes_full(&self) -> &[u8] { 36 | &self.bytes 37 | } 38 | } 39 | 40 | impl<'a, D> LocalizedKey<'a, D> 41 | where 42 | D: Update + FixedOutput + Reset + Default + Clone, 43 | { 44 | /// Creates a key from a user password and an authoritative engine ID. 45 | /// 46 | /// The password should be at least 8 characters in length. 47 | /// 48 | /// # Panics 49 | /// 50 | /// Panics if `passwd` has length 0. 51 | /// 52 | /// # Examples 53 | /// 54 | /// ``` 55 | /// use snmp_usm::LocalizedMd5Key; 56 | /// 57 | /// let key = LocalizedMd5Key::new(b"password", b"engine_id"); 58 | /// ``` 59 | pub fn new(passwd: &[u8], engine_id: &[u8]) -> Self { 60 | let mut bytes = vec![]; 61 | 62 | let mut len = None; 63 | 64 | while bytes.len() < AES_256_KEY_LEN { 65 | let mut data = 66 | Self::key_from_passwd(if bytes.is_empty() { passwd } else { &bytes }, engine_id); 67 | 68 | if len.is_none() { 69 | len = Some(data.len()) 70 | } 71 | 72 | bytes.append(&mut data); 73 | } 74 | 75 | Self { 76 | bytes, 77 | _digest_type: PhantomData, 78 | orig_len: len.expect("No bytes generated"), 79 | } 80 | } 81 | 82 | // Returns a localized key from a user password and an authoritative engine ID. 83 | fn key_from_passwd(passwd: &[u8], engine_id: &[u8]) -> Vec { 84 | assert!( 85 | !passwd.is_empty(), 86 | "password for localized key cannot be empty" 87 | ); 88 | 89 | let mut passwd_buf = vec![0; PASSWD_BUF_LEN]; 90 | let mut passwd_index = 0; 91 | let passwd_len = passwd.len(); 92 | let mut hashing_fn = D::default(); 93 | 94 | for _ in (0..ONE_MEGABYTE).step_by(PASSWD_BUF_LEN) { 95 | for byte in passwd_buf.iter_mut() { 96 | *byte = passwd[passwd_index % passwd_len]; 97 | passwd_index += 1; 98 | } 99 | 100 | hashing_fn.update(&passwd_buf); 101 | } 102 | 103 | let key = hashing_fn.finalize_reset(); 104 | passwd_buf.clear(); 105 | passwd_buf.extend_from_slice(&key); 106 | passwd_buf.extend_from_slice(engine_id); 107 | passwd_buf.extend_from_slice(&key); 108 | 109 | hashing_fn.update(&passwd_buf); 110 | hashing_fn.finalize().to_vec() 111 | } 112 | } 113 | 114 | /// Trait implemented by types created with a localized key. 115 | /// 116 | /// This trait helps simplify code having to create types generically with a localized key. 117 | pub trait WithLocalizedKey<'a, D> { 118 | /// Constructs a new type with a localized key. 119 | /// 120 | /// # Examples 121 | /// 122 | /// ``` 123 | /// use snmp_usm::{DesPrivKey, LocalizedSha1Key, WithLocalizedKey}; 124 | /// 125 | /// # let passwd = b"12345678"; 126 | /// # let engine_id = b"1234"; 127 | /// let localized_key = LocalizedSha1Key::new(passwd, engine_id); 128 | /// let priv_key = DesPrivKey::with_localized_key(localized_key); 129 | /// ``` 130 | fn with_localized_key(localized_key: LocalizedKey<'a, D>) -> Self; 131 | } 132 | 133 | #[cfg(test)] 134 | mod tests { 135 | use super::*; 136 | use md5::Md5; 137 | use sha1::Sha1; 138 | 139 | #[test] 140 | fn it_constructs_localized_key_with_md5() { 141 | let engine_id = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x02]; 142 | let result = LocalizedKey::::new(b"maplesyrup", &engine_id); 143 | 144 | let expected = [ 145 | 0x52, 0x6f, 0x5e, 0xed, 0x9f, 0xcc, 0xe2, 0x6f, 0x89, 0x64, 0xc2, 0x93, 0x07, 0x87, 146 | 0xd8, 0x2b, 147 | ]; 148 | assert_eq!(result.bytes(), expected); 149 | } 150 | 151 | #[test] 152 | fn it_constructs_localized_key_with_sha1() { 153 | let engine_id = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x02]; 154 | let result = LocalizedKey::::new(b"maplesyrup", &engine_id); 155 | 156 | let expected = [ 157 | 0x66, 0x95, 0xfe, 0xbc, 0x92, 0x88, 0xe3, 0x62, 0x82, 0x23, 0x5f, 0xc7, 0x15, 0x1f, 158 | 0x12, 0x84, 0x97, 0xb3, 0x8f, 0x3f, 159 | ]; 160 | assert_eq!(result.bytes(), expected); 161 | } 162 | 163 | #[test] 164 | #[should_panic] 165 | fn it_panics_with_empty_passwd() { 166 | let engine_id = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x02]; 167 | LocalizedKey::::new(b"", &engine_id); 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/snmp_usm/src/pos_finder.rs: -------------------------------------------------------------------------------- 1 | use crate::{SecurityError, SecurityResult}; 2 | use std::ops::Range; 3 | use yasna::{tags, Tag, TagClass}; 4 | 5 | const TAG_CLASSES: [TagClass; 4] = [ 6 | TagClass::Universal, 7 | TagClass::Application, 8 | TagClass::ContextSpecific, 9 | TagClass::Private, 10 | ]; 11 | 12 | const TAG_CLASS_POS: u8 = 6; 13 | const TAG_TYPE_POS: u8 = 5; 14 | const TAG_NUM_MASK: u8 = 0b0001_1111; 15 | const INDEFINITE_LEN: u8 = 0x80; 16 | const RESERVED_FORM_LEN: u8 = 0xFF; 17 | const LONG_FORM_LEN_MASK: u8 = 0x7F; 18 | const INTEGER_BASE: usize = 256; 19 | 20 | // Struct used to find a precise position in an encoded SNMP message. It doesn't support the 21 | // following encoding: 22 | // 23 | // * High tag number. 24 | // * Indefinite length. 25 | // * Long form length larger than usize::MAX 26 | pub struct PosFinder<'a> { 27 | buf: &'a [u8], 28 | pos: usize, 29 | } 30 | 31 | impl<'a> PosFinder<'a> { 32 | pub fn new(buf: &'a [u8]) -> Self { 33 | Self { buf, pos: 0 } 34 | } 35 | 36 | pub fn skip_int(&mut self) -> SecurityResult<()> { 37 | self.skip_field_type(tags::TAG_INTEGER, false) 38 | } 39 | 40 | pub fn skip_octet_str(&mut self) -> SecurityResult<()> { 41 | self.skip_field_type(tags::TAG_OCTETSTRING, false) 42 | } 43 | 44 | pub fn step_into_octet_str(&mut self) -> SecurityResult> { 45 | let range = self.step_into_field_type(tags::TAG_OCTETSTRING, false)?; 46 | Ok(range) 47 | } 48 | 49 | pub fn skip_seq(&mut self) -> SecurityResult<()> { 50 | self.skip_field_type(tags::TAG_SEQUENCE, true) 51 | } 52 | 53 | pub fn step_into_seq(&mut self) -> SecurityResult> { 54 | let range = self.step_into_field_type(tags::TAG_SEQUENCE, true)?; 55 | Ok(range) 56 | } 57 | 58 | fn skip_tag_type(&mut self, tag: Tag, is_constructed: bool) -> SecurityResult<()> { 59 | let (_, is_constr) = self.read_tag_type(tag)?; 60 | if is_constructed != is_constr { 61 | return Err(SecurityError::MalformedMsg); 62 | } 63 | 64 | Ok(()) 65 | } 66 | 67 | fn skip_field_type(&mut self, tag: Tag, is_constructed: bool) -> SecurityResult<()> { 68 | self.skip_tag_type(tag, is_constructed)?; 69 | self.pos += self.read_len()?; 70 | 71 | Ok(()) 72 | } 73 | 74 | fn step_into_field_type( 75 | &mut self, 76 | tag: Tag, 77 | is_constructed: bool, 78 | ) -> SecurityResult> { 79 | self.skip_tag_type(tag, is_constructed)?; 80 | let len = self.read_len()?; 81 | let end = self.pos + len; 82 | 83 | Ok(self.pos..end) 84 | } 85 | 86 | fn read_tag(&mut self) -> SecurityResult<(Tag, bool)> { 87 | let tag_byte = self.read_u8()?; 88 | let tag_number = tag_byte & TAG_NUM_MASK; 89 | // High tag numbers are not supported. 90 | if tag_number == TAG_NUM_MASK { 91 | return Err(SecurityError::MalformedMsg); 92 | } 93 | 94 | let tag_class = TAG_CLASSES[(tag_byte >> TAG_CLASS_POS) as usize]; 95 | let tag_number = tag_number as u64; 96 | 97 | let tag = Tag { 98 | tag_class, 99 | tag_number, 100 | }; 101 | let is_constructed = (tag_byte >> TAG_TYPE_POS) & 1 == 1; 102 | 103 | Ok((tag, is_constructed)) 104 | } 105 | 106 | // Doesn't support indefinite length and long form length larger than usize::MAX. 107 | fn read_len(&mut self) -> SecurityResult { 108 | let len_byte = self.read_u8()?; 109 | 110 | if len_byte == RESERVED_FORM_LEN { 111 | return Err(SecurityError::MalformedMsg); 112 | } 113 | 114 | if len_byte == INDEFINITE_LEN { 115 | return Err(SecurityError::MalformedMsg); 116 | } 117 | 118 | let is_short_form = (len_byte >> 7) == 0; 119 | let len = if is_short_form { 120 | len_byte as usize 121 | } else { 122 | let mut len: usize = 0; 123 | for _ in 0..(len_byte & LONG_FORM_LEN_MASK) { 124 | let part = len 125 | .checked_mul(INTEGER_BASE) 126 | .ok_or(SecurityError::MalformedMsg)?; 127 | len = part + self.read_u8()? as usize; 128 | } 129 | 130 | len 131 | }; 132 | 133 | if self.pos + len > self.buf.len() { 134 | return Err(SecurityError::MalformedMsg); 135 | } 136 | 137 | Ok(len) 138 | } 139 | 140 | fn read_tag_type(&mut self, tag: Tag) -> SecurityResult<(Tag, bool)> { 141 | let (read_tag, is_constructed) = self.read_tag()?; 142 | if tag != read_tag { 143 | return Err(SecurityError::MalformedMsg); 144 | } 145 | 146 | Ok((tag, is_constructed)) 147 | } 148 | 149 | fn read_u8(&mut self) -> SecurityResult { 150 | if self.pos >= self.buf.len() { 151 | return Err(SecurityError::MalformedMsg); 152 | } 153 | 154 | let byte = self.buf[self.pos]; 155 | self.pos += 1; 156 | Ok(byte) 157 | } 158 | } 159 | 160 | #[cfg(test)] 161 | mod tests { 162 | use super::*; 163 | use yasna::tags; 164 | 165 | #[test] 166 | fn it_skips_int() { 167 | let int = [0x02, 0x03, 0x01, 0x00, 0x01]; 168 | let mut finder = PosFinder::new(&int); 169 | finder.skip_int().unwrap(); 170 | 171 | assert_eq!(finder.pos, int.len()); 172 | } 173 | 174 | #[test] 175 | fn it_skips_octet_str() { 176 | let octet_str = [0x04, 0x03, 0x01, 0x02, 0x03]; 177 | let mut finder = PosFinder::new(&octet_str); 178 | finder.skip_octet_str().unwrap(); 179 | 180 | assert_eq!(finder.pos, octet_str.len()); 181 | } 182 | 183 | #[test] 184 | fn it_steps_into_octet_str() { 185 | let octet_str = [0x04, 0x03, 0x01, 0x02, 0x03]; 186 | let mut finder = PosFinder::new(&octet_str); 187 | let result = finder.step_into_octet_str().unwrap(); 188 | 189 | assert_eq!(finder.pos, 2); 190 | assert_eq!(result, 2..5); 191 | } 192 | 193 | #[test] 194 | fn it_skips_seq() { 195 | let seq = [0x30, 0x03, 0x01, 0x02, 0x03]; 196 | let mut finder = PosFinder::new(&seq); 197 | finder.skip_seq().unwrap(); 198 | 199 | assert_eq!(finder.pos, seq.len()); 200 | } 201 | 202 | #[test] 203 | fn it_steps_into_seq() { 204 | let seq = [0x30, 0x03, 0x01, 0x02, 0x03]; 205 | let mut finder = PosFinder::new(&seq); 206 | let result = finder.step_into_seq().unwrap(); 207 | 208 | assert_eq!(finder.pos, 2); 209 | assert_eq!(result, 2..5); 210 | } 211 | 212 | #[test] 213 | fn it_returns_invalid_error_for_high_tag_num() { 214 | let time_of_day = [0x1F, 0x20, 0x06, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30]; 215 | let mut finder = PosFinder::new(&time_of_day); 216 | let result = finder.read_tag(); 217 | 218 | assert_eq!(result, Err(SecurityError::MalformedMsg)); 219 | } 220 | 221 | #[test] 222 | fn it_returns_invalid_error_for_invalid_short_len() { 223 | let octet_str = [0x04, 0x04, 0x01, 0x02, 0x03]; 224 | let mut finder = PosFinder::new(&octet_str); 225 | finder.read_tag().unwrap(); 226 | let result = finder.read_len(); 227 | 228 | assert_eq!(result, Err(SecurityError::MalformedMsg)); 229 | } 230 | 231 | #[test] 232 | fn it_returns_invalid_error_for_invalid_long_len() { 233 | let long_len = [0x82, 0x01, 0x01, 0x00]; 234 | let mut finder = PosFinder::new(&long_len); 235 | let result = finder.read_len(); 236 | 237 | assert_eq!(result, Err(SecurityError::MalformedMsg)); 238 | } 239 | 240 | #[test] 241 | fn it_returns_invalid_error_for_indefinite_len() { 242 | let indefinite_len = [0x80, 0x01, 0x00, 0x00]; 243 | let mut finder = PosFinder::new(&indefinite_len); 244 | let result = finder.read_len(); 245 | 246 | assert_eq!(result, Err(SecurityError::MalformedMsg)); 247 | } 248 | 249 | #[test] 250 | fn it_returns_invalid_error_for_len_larger_than_usize_max() { 251 | let very_long_len = [0x89, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; 252 | let mut finder = PosFinder::new(&very_long_len); 253 | let result = finder.read_len(); 254 | 255 | assert_eq!(result, Err(SecurityError::MalformedMsg)); 256 | } 257 | 258 | #[test] 259 | fn it_returns_error_for_wrong_tag() { 260 | let int = [0x02, 0x03, 0x01, 0x00, 0x01]; 261 | let mut finder = PosFinder::new(&int); 262 | let result = finder.read_tag_type(tags::TAG_OCTETSTRING); 263 | 264 | assert_eq!(result, Err(SecurityError::MalformedMsg)); 265 | } 266 | 267 | #[test] 268 | fn it_returns_error_when_reading_end_of_buf() { 269 | let buf = []; 270 | let mut finder = PosFinder::new(&buf); 271 | let result = finder.read_u8(); 272 | 273 | assert_eq!(result, Err(SecurityError::MalformedMsg)); 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /src/snmp_usm/src/priv_key.rs: -------------------------------------------------------------------------------- 1 | mod aes_priv_key; 2 | mod des_priv_key; 3 | 4 | use crate::{SecurityParams, SecurityResult}; 5 | pub use aes_priv_key::AesPrivKey; 6 | pub use des_priv_key::DesPrivKey; 7 | 8 | const PRIV_KEY_LEN: usize = 16; 9 | 10 | /// A trait for privacy keys. 11 | /// 12 | /// Privacy keys are used to encrypt scoped PDUs. 13 | pub trait PrivKey { 14 | /// The type of the "salt" used for encryption. 15 | type Salt; 16 | 17 | /// Encrypts a scoped PDU in place. 18 | /// 19 | /// It returns the encrypted scoped PDU and the "salt" that was used for the encryption. This 20 | /// "salt" must be placed in the privacy parameters to enable the receiving entity to compute 21 | /// the correct IV and to decrypt the scoped PDU. 22 | /// 23 | /// # Arguments 24 | /// 25 | /// * `scoped_pdu` - The encoded scoped PDU 26 | /// * `security_params` - Security parameters related to the scoped PDU to encrypt 27 | /// * `salt` - "Salt" integer that as to be modified after being used to encrypt a message. How 28 | /// exactly the value of the "salt" (and thus of the IV) varies, is an implementation issue, 29 | /// as long as the measures are taken to avoid producing a duplicate IV 30 | /// 31 | /// # Examples 32 | /// 33 | /// ``` 34 | /// # use snmp_usm::{LocalizedSha1Key, SecurityParams}; 35 | /// use snmp_usm::{Aes128PrivKey, PrivKey, WithLocalizedKey}; 36 | /// 37 | /// # let scoped_pdu = b"1234".to_vec(); 38 | /// # let security_params = SecurityParams::new(); 39 | /// # let localized_key = LocalizedSha1Key::new(b"1234", b"1234"); 40 | /// let priv_key = Aes128PrivKey::with_localized_key(localized_key); 41 | /// let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 42 | /// ``` 43 | fn encrypt( 44 | &self, 45 | scoped_pdu: Vec, 46 | security_params: &SecurityParams, 47 | salt: Self::Salt, 48 | ) -> (Vec, Vec); 49 | 50 | /// Decrypts an encrypted scoped PDU in place. 51 | /// 52 | /// # Arguments 53 | /// 54 | /// * `encrypted_scoped_pdu` - The encrypted scoped PDU 55 | /// * `security_params` - Security parameters related to the scoped PDU to decrypt 56 | /// 57 | /// # Errors 58 | /// 59 | /// If the decryption failed a result with 60 | /// [DecryptError](enum.SecurityError.html#variant.DecryptError) error is returned. 61 | /// 62 | /// # Examples 63 | /// 64 | /// ```no_run 65 | /// # use snmp_usm::{LocalizedMd5Key, SecurityParams}; 66 | /// use snmp_usm::{DesPrivKey, PrivKey, WithLocalizedKey}; 67 | /// 68 | /// # fn main() -> snmp_usm::SecurityResult<()> { 69 | /// # let encrypted_scoped_pdu = b"1234".to_vec(); 70 | /// # let security_params = SecurityParams::new(); 71 | /// # let localized_key = LocalizedMd5Key::new(b"1234", b"1234"); 72 | /// let priv_key = DesPrivKey::with_localized_key(localized_key); 73 | /// let decrypted_scoped_pdu = priv_key.decrypt(encrypted_scoped_pdu, &security_params)?; 74 | /// # Ok(()) 75 | /// # } 76 | /// ``` 77 | fn decrypt( 78 | &self, 79 | encrypted_scoped_pdu: Vec, 80 | security_params: &SecurityParams, 81 | ) -> SecurityResult>; 82 | } 83 | -------------------------------------------------------------------------------- /src/snmp_usm/src/priv_key/aes_priv_key.rs: -------------------------------------------------------------------------------- 1 | use super::PrivKey; 2 | use crate::{LocalizedKey, SecurityError, SecurityParams, SecurityResult, WithLocalizedKey}; 3 | use aes::cipher::{AsyncStreamCipher, IvSizeUser, KeyIvInit}; 4 | use aes::{Aes128, Aes192, Aes256}; 5 | use cfb_mode::{Decryptor, Encryptor}; 6 | 7 | /// Privacy key used for AES encryption. 8 | /// 9 | /// It is constructed from a [Localizedkey](struct.LocalizedKey.html). 10 | /// 11 | /// Authentication must always be performed when encryption is requested. 12 | #[derive(Clone, Debug, Eq, PartialEq, Hash)] 13 | pub struct AesPrivKey<'a, D, const BITS: usize> { 14 | localized_key: LocalizedKey<'a, D>, 15 | } 16 | 17 | impl<'a, D, const BITS: usize> AesPrivKey<'a, D, BITS> { 18 | fn iv(&self, engine_boots: u32, engine_time: u32, salt: &[u8]) -> Vec { 19 | let mut iv = Vec::with_capacity(match BITS { 20 | 128 => as IvSizeUser>::iv_size(), 21 | 192 => as IvSizeUser>::iv_size(), 22 | 256 => as IvSizeUser>::iv_size(), 23 | _ => unreachable!("Invalid number of bits"), 24 | }); 25 | 26 | iv.extend_from_slice(&engine_boots.to_be_bytes()); 27 | iv.extend_from_slice(&engine_time.to_be_bytes()); 28 | iv.extend_from_slice(salt); 29 | 30 | iv 31 | } 32 | 33 | fn key(&self) -> &[u8] { 34 | let key = self.localized_key.bytes_full(); 35 | 36 | &key[..(BITS / 8)] 37 | } 38 | } 39 | 40 | impl<'a, D, const BITS: usize> PrivKey for AesPrivKey<'a, D, BITS> { 41 | type Salt = u64; 42 | 43 | // Encrypts a scoped PDU using AES. 44 | fn encrypt( 45 | &self, 46 | mut scoped_pdu: Vec, 47 | security_params: &SecurityParams, 48 | salt: Self::Salt, 49 | ) -> (Vec, Vec) { 50 | let salt = salt.to_be_bytes(); 51 | let iv = self.iv( 52 | security_params.engine_boots(), 53 | security_params.engine_time(), 54 | &salt, 55 | ); 56 | 57 | match BITS { 58 | 128 => Encryptor::::new_from_slices(self.key(), &iv) 59 | .unwrap() 60 | .encrypt(&mut scoped_pdu), 61 | 192 => Encryptor::::new_from_slices(self.key(), &iv) 62 | .unwrap() 63 | .encrypt(&mut scoped_pdu), 64 | 256 => Encryptor::::new_from_slices(self.key(), &iv) 65 | .unwrap() 66 | .encrypt(&mut scoped_pdu), 67 | _ => unreachable!("Invalid number of bits"), 68 | }; 69 | 70 | (scoped_pdu, salt.to_vec()) 71 | } 72 | 73 | // Decrypts a scoped PDU that was encrypted using AES. 74 | fn decrypt( 75 | &self, 76 | mut encrypted_scoped_pdu: Vec, 77 | security_params: &SecurityParams, 78 | ) -> SecurityResult> { 79 | let iv = self.iv( 80 | security_params.engine_boots(), 81 | security_params.engine_time(), 82 | security_params.priv_params(), 83 | ); 84 | 85 | match BITS { 86 | 128 => Decryptor::::new_from_slices(self.key(), &iv) 87 | .map_err(|_| SecurityError::DecryptError)? 88 | .decrypt(&mut encrypted_scoped_pdu), 89 | 192 => Decryptor::::new_from_slices(self.key(), &iv) 90 | .map_err(|_| SecurityError::DecryptError)? 91 | .decrypt(&mut encrypted_scoped_pdu), 92 | 256 => Decryptor::::new_from_slices(self.key(), &iv) 93 | .map_err(|_| SecurityError::DecryptError)? 94 | .decrypt(&mut encrypted_scoped_pdu), 95 | _ => unreachable!("Invalid number of bits"), 96 | }; 97 | 98 | Ok(encrypted_scoped_pdu) 99 | } 100 | } 101 | 102 | impl<'a, D, const BITS: usize> WithLocalizedKey<'a, D> for AesPrivKey<'a, D, BITS> { 103 | fn with_localized_key(localized_key: LocalizedKey<'a, D>) -> Self { 104 | match BITS { 105 | 128 | 192 | 256 => Self { localized_key }, 106 | _ => panic!("Invalid number of bits"), 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/snmp_usm/src/priv_key/des_priv_key.rs: -------------------------------------------------------------------------------- 1 | use super::{PrivKey, PRIV_KEY_LEN}; 2 | use crate::{LocalizedKey, SecurityError, SecurityParams, SecurityResult, WithLocalizedKey}; 3 | use block_modes::{block_padding::NoPadding, BlockMode, Cbc, InvalidKeyIvLength}; 4 | use des::{ 5 | block_cipher::{generic_array::typenum::Unsigned, BlockCipher, NewBlockCipher}, 6 | Des, 7 | }; 8 | 9 | type DesCbc = Cbc; 10 | 11 | /// Privacy key used for DES encryption. 12 | /// 13 | /// It is constructed from a [Localizedkey](struct.LocalizedKey.html). When decrypting the padding 14 | /// is not removed. 15 | /// 16 | /// Authentication must always be performed when encryption is requested. 17 | #[derive(Clone, Debug, Eq, PartialEq, Hash)] 18 | pub struct DesPrivKey<'a, D> { 19 | localized_key: LocalizedKey<'a, D>, 20 | } 21 | 22 | impl<'a, D> DesPrivKey<'a, D> { 23 | // Returns a DES block cipher. 24 | fn cipher(&self, salt: &[u8]) -> Result { 25 | let des_key_len = ::KeySize::to_usize(); 26 | let key = self.localized_key.bytes(); 27 | let (des_key, pre_iv) = key[..PRIV_KEY_LEN].split_at(des_key_len); 28 | 29 | let iv: Vec<_> = salt 30 | .iter() 31 | .zip(pre_iv.iter()) 32 | .map(|(salt, pre_iv)| salt ^ pre_iv) 33 | .collect(); 34 | 35 | DesCbc::new_var(des_key, &iv) 36 | } 37 | 38 | fn add_padding_space(buf: &mut Vec) { 39 | let len = buf.len(); 40 | let block_size = ::BlockSize::to_usize(); 41 | 42 | let rem = len % block_size; 43 | if rem != 0 { 44 | let padding_space = block_size - rem; 45 | buf.resize(len + padding_space, 0); 46 | } 47 | } 48 | } 49 | 50 | impl<'a, D> PrivKey for DesPrivKey<'a, D> { 51 | type Salt = u32; 52 | 53 | // Encrypts a scoped PDU using DES. 54 | fn encrypt( 55 | &self, 56 | mut scoped_pdu: Vec, 57 | security_params: &SecurityParams, 58 | salt: Self::Salt, 59 | ) -> (Vec, Vec) { 60 | let salt = [ 61 | security_params.engine_boots().to_be_bytes(), 62 | salt.to_be_bytes(), 63 | ] 64 | .concat(); 65 | 66 | if scoped_pdu.is_empty() { 67 | return (scoped_pdu, salt); 68 | } 69 | 70 | let cipher = self.cipher(&salt).unwrap(); 71 | 72 | Self::add_padding_space(&mut scoped_pdu); 73 | let len = scoped_pdu.len(); 74 | cipher.encrypt(&mut scoped_pdu, len).unwrap(); 75 | 76 | (scoped_pdu, salt) 77 | } 78 | 79 | // Decrypts a scoped PDU that was encrypted using DES. 80 | fn decrypt( 81 | &self, 82 | mut encrypted_scoped_pdu: Vec, 83 | security_params: &SecurityParams, 84 | ) -> SecurityResult> { 85 | if encrypted_scoped_pdu.is_empty() { 86 | return Ok(encrypted_scoped_pdu); 87 | } 88 | 89 | let salt = security_params.priv_params(); 90 | self.cipher(salt) 91 | .map_err(|_| SecurityError::DecryptError)? 92 | .decrypt(&mut encrypted_scoped_pdu) 93 | .map_err(|_| SecurityError::DecryptError)?; 94 | 95 | Ok(encrypted_scoped_pdu) 96 | } 97 | } 98 | 99 | impl<'a, D> WithLocalizedKey<'a, D> for DesPrivKey<'a, D> { 100 | fn with_localized_key(localized_key: LocalizedKey<'a, D>) -> Self { 101 | Self { localized_key } 102 | } 103 | } 104 | 105 | #[cfg(test)] 106 | mod tests { 107 | use super::*; 108 | use crate::Md5; 109 | 110 | #[test] 111 | fn it_adds_padding_if_not_multiple_of_block_size() { 112 | let block_size = ::BlockSize::to_usize(); 113 | let mut buf = vec![0; block_size + block_size / 2]; 114 | 115 | DesPrivKey::::add_padding_space(&mut buf); 116 | assert_eq!(buf.len(), block_size * 2); 117 | } 118 | 119 | #[test] 120 | fn it_does_not_add_padding_if_multiple_of_block_size() { 121 | let block_size = ::BlockSize::to_usize(); 122 | let mut buf = vec![0; block_size]; 123 | 124 | DesPrivKey::::add_padding_space(&mut buf); 125 | assert_eq!(buf.len(), block_size); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/snmp_usm/src/security_params.rs: -------------------------------------------------------------------------------- 1 | use crate::{SecurityError, SecurityResult, AUTH_PARAMS_PLACEHOLDER}; 2 | 3 | /// Security parameters used by the User-based Security Model. 4 | /// 5 | /// It contains the necessary information to achieve the following goals: 6 | /// 7 | /// * Verification that each received SNMP message has not been modified. 8 | /// * User identity verification. 9 | /// * Detection of received SNMP messages whose time of generation was not recent. 10 | /// * Message encryption. 11 | /// 12 | /// Empty security params can be generated using [SecurityParams::new()](#method.new). Additional 13 | /// builder methods allow the security parameters to be changed. 14 | /// 15 | /// # Examples 16 | /// 17 | /// ``` 18 | /// use snmp_usm::SecurityParams; 19 | /// 20 | /// let mut security_params = SecurityParams::new(); 21 | /// security_params.set_username(b"username") 22 | /// .set_priv_params(b"saltsalt") 23 | /// .set_auth_params_placeholder(); 24 | /// ``` 25 | #[derive(Debug, Clone, Default, Eq, PartialEq, Hash)] 26 | pub struct SecurityParams { 27 | engine_id: Vec, 28 | engine_boots: u32, 29 | engine_time: u32, 30 | username: Vec, 31 | auth_params: Vec, 32 | priv_params: Vec, 33 | } 34 | 35 | impl SecurityParams { 36 | /// The largest value for [engine_boots](#method.engine_boots). 37 | /// 38 | /// Whenever the local value of `engine_boots` has a value equal to or greater than 39 | /// 2_147_483_647 an authenticated message always causes an 40 | /// [NotInTimeWindow](enum.SecurityError.html#variant.NotInTimeWindow) authentication failure. 41 | /// 42 | /// # Examples 43 | /// 44 | /// ``` 45 | /// # use snmp_usm::SecurityParams; 46 | /// assert_eq!(SecurityParams::ENGINE_BOOTS_MAX, 2_147_483_647); 47 | /// ``` 48 | pub const ENGINE_BOOTS_MAX: u32 = 2_147_483_647; 49 | 50 | /// The largest value for [engine_time](#method.engine_time). 51 | /// 52 | /// # Examples 53 | /// 54 | /// ``` 55 | /// # use snmp_usm::SecurityParams; 56 | /// assert_eq!(SecurityParams::ENGINE_TIME_MAX, 2_147_483_647); 57 | /// ``` 58 | pub const ENGINE_TIME_MAX: u32 = 2_147_483_647; 59 | 60 | /// Alias for [for_discovery](#method.for_discovery). 61 | pub fn new() -> Self { 62 | Self::default() 63 | } 64 | 65 | /// Returns security parameters with a security username of zero-length and an authoritative 66 | /// engine ID of zero-length. 67 | /// 68 | /// The User-based Security Model requires that a discovery process obtains sufficient 69 | /// information about other SNMP engines in order to communicate with them. Discovery requires 70 | /// an non-authoritative SNMP engine to learn the authoritative SNMP engine's ID value before 71 | /// communication may proceed. This function returns security parameters that can be included 72 | /// in a discovery message. 73 | /// 74 | /// # Examples 75 | /// 76 | /// ``` 77 | /// use snmp_usm::SecurityParams; 78 | /// 79 | /// let security_params = SecurityParams::for_discovery(); 80 | /// assert_eq!(security_params.username(), b""); 81 | /// assert_eq!(security_params.engine_id(), b""); 82 | /// 83 | /// // A message processing subsystem would set the security parameters of the discovery 84 | /// // message. 85 | /// // discovery_msg.set_security_params(&security_params.encode()); 86 | /// ``` 87 | pub fn for_discovery() -> Self { 88 | Self::default() 89 | } 90 | 91 | /// Returns the authoritative engine's ID. 92 | /// 93 | /// # Examples 94 | /// 95 | /// ``` 96 | /// use snmp_usm::SecurityParams; 97 | /// 98 | /// # let security_params = SecurityParams::for_discovery(); 99 | /// let engine_id = security_params.engine_id(); 100 | /// ``` 101 | pub fn engine_id(&self) -> &[u8] { 102 | &self.engine_id 103 | } 104 | 105 | /// Sets the authoritative engine's ID. 106 | /// 107 | /// # Examples 108 | /// 109 | /// ``` 110 | /// use snmp_usm::SecurityParams; 111 | /// 112 | /// let mut security_params = SecurityParams::new(); 113 | /// security_params.set_engine_id(b"engine_id"); 114 | /// assert_eq!(security_params.engine_id(), b"engine_id"); 115 | /// ``` 116 | pub fn set_engine_id(&mut self, engine_id: &[u8]) -> &mut Self { 117 | self.engine_id.clear(); 118 | self.engine_id.extend_from_slice(engine_id); 119 | self 120 | } 121 | 122 | /// Returns the authoritative engine's boots. 123 | /// 124 | /// # Examples 125 | /// 126 | /// ``` 127 | /// use snmp_usm::SecurityParams; 128 | /// 129 | /// # let security_params = SecurityParams::for_discovery(); 130 | /// let engine_boots = security_params.engine_boots(); 131 | /// ``` 132 | pub fn engine_boots(&self) -> u32 { 133 | self.engine_boots 134 | } 135 | 136 | /// Sets the authoritative engine's boots. 137 | /// 138 | /// The value should not be larger than 139 | /// [ENGINE_BOOTS_MAX](#associatedconstant.ENGINE_BOOTS_MAX). 140 | /// 141 | /// # Examples 142 | /// 143 | /// ``` 144 | /// use snmp_usm::SecurityParams; 145 | /// 146 | /// let mut security_params = SecurityParams::new(); 147 | /// security_params.set_engine_boots(1); 148 | /// assert_eq!(security_params.engine_boots(), 1); 149 | /// ``` 150 | pub fn set_engine_boots(&mut self, engine_boots: u32) -> &mut Self { 151 | self.engine_boots = engine_boots; 152 | self 153 | } 154 | 155 | /// Returns the authoritative engine's time. 156 | /// 157 | /// # Examples 158 | /// 159 | /// ``` 160 | /// use snmp_usm::SecurityParams; 161 | /// 162 | /// # let security_params = SecurityParams::for_discovery(); 163 | /// let engine_time = security_params.engine_time(); 164 | /// ``` 165 | pub fn engine_time(&self) -> u32 { 166 | self.engine_time 167 | } 168 | 169 | /// Sets the authoritative engine's time. 170 | /// 171 | /// The value should not be larger than 172 | /// [ENGINE_TIME_MAX](#associatedconstant.ENGINE_TIME_MAX). 173 | /// 174 | /// # Examples 175 | /// 176 | /// ``` 177 | /// use snmp_usm::SecurityParams; 178 | /// 179 | /// let mut security_params = SecurityParams::new(); 180 | /// security_params.set_engine_boots(1); 181 | /// assert_eq!(security_params.engine_boots(), 1); 182 | /// ``` 183 | pub fn set_engine_time(&mut self, engine_time: u32) -> &mut Self { 184 | self.engine_time = engine_time; 185 | self 186 | } 187 | 188 | /// Returns the username. 189 | /// 190 | /// # Examples 191 | /// 192 | /// ``` 193 | /// use snmp_usm::SecurityParams; 194 | /// 195 | /// # let security_params = SecurityParams::for_discovery(); 196 | /// let username = security_params.username(); 197 | /// ``` 198 | pub fn username(&self) -> &[u8] { 199 | &self.username 200 | } 201 | 202 | /// Sets the username. 203 | /// 204 | /// # Examples 205 | /// 206 | /// ``` 207 | /// use snmp_usm::SecurityParams; 208 | /// 209 | /// let mut security_params = SecurityParams::new(); 210 | /// security_params.set_username(b"username"); 211 | /// assert_eq!(security_params.username(), b"username"); 212 | /// ``` 213 | pub fn set_username(&mut self, username: &[u8]) -> &mut Self { 214 | self.username.clear(); 215 | self.username.extend_from_slice(username); 216 | self 217 | } 218 | 219 | // Returns the authentication parameters. 220 | /// 221 | /// # Examples 222 | /// 223 | /// ``` 224 | /// use snmp_usm::SecurityParams; 225 | /// 226 | /// # let security_params = SecurityParams::for_discovery(); 227 | /// let auth_params = security_params.auth_params(); 228 | /// ``` 229 | pub fn auth_params(&self) -> &[u8] { 230 | &self.auth_params 231 | } 232 | 233 | /// Sets the authentication parameters. 234 | /// 235 | /// # Examples 236 | /// 237 | /// ``` 238 | /// use snmp_usm::SecurityParams; 239 | /// 240 | /// let mut security_params = SecurityParams::new(); 241 | /// security_params.set_auth_params(b"auth_params"); 242 | /// assert_eq!(security_params.auth_params(), b"auth_params"); 243 | /// ``` 244 | pub fn set_auth_params(&mut self, auth_params: &[u8]) -> &mut Self { 245 | self.auth_params.clear(); 246 | self.auth_params.extend_from_slice(auth_params); 247 | self 248 | } 249 | 250 | /// Sets the authentication parameters placeholder. 251 | /// 252 | /// # Examples 253 | /// 254 | /// ``` 255 | /// use snmp_usm::SecurityParams; 256 | /// 257 | /// let mut security_params = SecurityParams::new(); 258 | /// security_params.set_auth_params_placeholder(); 259 | /// assert_eq!(security_params.auth_params(), [0x0; 12]); 260 | /// ``` 261 | pub fn set_auth_params_placeholder(&mut self) -> &mut Self { 262 | self.set_auth_params(&AUTH_PARAMS_PLACEHOLDER); 263 | self 264 | } 265 | 266 | /// Returns the privacy parameters. 267 | /// 268 | /// They contain the "salt" used in the scoped PDU encryption. 269 | /// 270 | /// # Examples 271 | /// 272 | /// ``` 273 | /// use snmp_usm::SecurityParams; 274 | /// 275 | /// # let security_params = SecurityParams::for_discovery(); 276 | /// let priv_params = security_params.priv_params(); 277 | /// ``` 278 | pub fn priv_params(&self) -> &[u8] { 279 | &self.priv_params 280 | } 281 | 282 | /// Sets the privacy parameters. 283 | /// 284 | /// # Examples 285 | /// 286 | /// ``` 287 | /// use snmp_usm::SecurityParams; 288 | /// 289 | /// let mut security_params = SecurityParams::new(); 290 | /// security_params.set_priv_params(b"saltsalt"); 291 | /// assert_eq!(security_params.priv_params(), b"saltsalt"); 292 | /// ``` 293 | pub fn set_priv_params(&mut self, priv_params: &[u8]) -> &mut Self { 294 | self.priv_params.clear(); 295 | self.priv_params.extend_from_slice(priv_params); 296 | self 297 | } 298 | 299 | /// Encodes the security parameters. 300 | /// 301 | /// A message processing subsystem can add the encoded security parameters to a message as a 302 | /// byte string. 303 | /// 304 | /// # Examples 305 | /// 306 | /// ``` 307 | /// use snmp_usm::SecurityParams; 308 | /// 309 | /// let security_params = SecurityParams::new(); 310 | /// let encoded_security_params = security_params.encode(); 311 | /// ``` 312 | pub fn encode(&self) -> Vec { 313 | yasna::construct_der(|writer| { 314 | writer.write_sequence(|writer| { 315 | writer.next().write_bytes(&self.engine_id); 316 | writer.next().write_u32(self.engine_boots); 317 | writer.next().write_u32(self.engine_time); 318 | writer.next().write_bytes(&self.username); 319 | writer.next().write_bytes(&self.auth_params); 320 | writer.next().write_bytes(&self.priv_params); 321 | }) 322 | }) 323 | } 324 | 325 | /// Decodes incoming security parameters. 326 | /// 327 | /// The decoded values can be used to build response or report messages. 328 | /// 329 | /// # Errors 330 | /// 331 | /// If the message is not properly formed a result with 332 | /// [MalformedSecurityParams](enum.SecurityError.html#variant.MalformedSecurityParams) error is 333 | /// returned. 334 | /// 335 | /// # Examples 336 | /// 337 | /// ```no_run 338 | /// use snmp_usm::SecurityParams; 339 | /// 340 | /// # fn main() -> snmp_usm::SecurityResult<()> { 341 | /// # let in_security_params = []; 342 | /// let mut security_params = 343 | /// SecurityParams::decode(&in_security_params)?; 344 | /// security_params.set_username(b"username") 345 | /// .set_auth_params_placeholder(); 346 | /// // A message processing subsystem would set the security parameters of the outgoing message. 347 | /// // out_msg.set_security_params(&security_params); 348 | /// # Ok(()) 349 | /// # } 350 | /// ``` 351 | pub fn decode(buf: &[u8]) -> SecurityResult { 352 | let result = yasna::parse_ber(buf, |reader| { 353 | reader.read_sequence(|reader| { 354 | let engine_id = reader.next().read_bytes()?; 355 | let engine_boots = reader.next().read_u32()?; 356 | let engine_time = reader.next().read_u32()?; 357 | let username = reader.next().read_bytes()?; 358 | let auth_params = reader.next().read_bytes()?; 359 | let priv_params = reader.next().read_bytes()?; 360 | 361 | Ok(Self { 362 | engine_id, 363 | engine_boots, 364 | engine_time, 365 | username, 366 | auth_params, 367 | priv_params, 368 | }) 369 | }) 370 | }); 371 | 372 | result.map_err(|_| SecurityError::MalformedSecurityParams) 373 | } 374 | } 375 | -------------------------------------------------------------------------------- /src/snmp_usm/tests/aes128_priv_key.rs: -------------------------------------------------------------------------------- 1 | use snmp_usm::{ 2 | self, Aes128PrivKey, LocalizedMd5Key, LocalizedSha1Key, PrivKey, SecurityError, SecurityParams, 3 | WithLocalizedKey, 4 | }; 5 | 6 | const ENGINE_ID: [u8; 17] = [ 7 | 0x80, 0x00, 0x1f, 0x88, 0x80, 0xfa, 0xa8, 0x11, 0x60, 0x0f, 0xa2, 0xc5, 0x5e, 0x00, 0x00, 0x00, 8 | 0x00, 9 | ]; 10 | 11 | #[test] 12 | fn it_encrypts_scoped_pdu_using_localized_md5_key() { 13 | let priv_key = Aes128PrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 14 | 15 | let scoped_pdu = vec![ 16 | 0x30, 0x30, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 17 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x19, 0x02, 0x01, 0x01, 0x02, 0x01, 18 | 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x02, 0x01, 19 | 0x01, 0x01, 0x00, 0x05, 0x00, 20 | ]; 21 | 22 | let mut security_params = SecurityParams::new(); 23 | security_params.set_engine_boots(45).set_engine_time(68902); 24 | 25 | let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 26 | 27 | let expected_scoped_pdu = vec![ 28 | 0x09, 0x97, 0x08, 0xD3, 0x62, 0x4D, 0x89, 0x08, 0x39, 0x41, 0xDB, 0x0C, 0x92, 0xD5, 0x36, 29 | 0xDC, 0xFF, 0xC0, 0x61, 0x6A, 0x6C, 0x88, 0x15, 0x4D, 0x9A, 0x85, 0x30, 0x10, 0x05, 0x4B, 30 | 0x9E, 0xBA, 0xA6, 0x0A, 0x52, 0x38, 0x08, 0x86, 0x4F, 0x5F, 0x44, 0x0E, 0x8C, 0x60, 0x63, 31 | 0x5A, 0xD2, 0x8E, 0x99, 0x00, 32 | ]; 33 | assert_eq!(encrypted_scoped_pdu, expected_scoped_pdu); 34 | 35 | let expected_salt = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; 36 | assert_eq!(salt, expected_salt); 37 | } 38 | 39 | #[test] 40 | fn it_encrypts_scoped_pdu_using_localized_sha1_key() { 41 | let priv_key = 42 | Aes128PrivKey::with_localized_key(LocalizedSha1Key::new(b"12345678", &ENGINE_ID)); 43 | 44 | let scoped_pdu = vec![ 45 | 0x30, 0x30, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 46 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x19, 0x02, 0x01, 0x01, 0x02, 0x01, 47 | 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x02, 0x01, 48 | 0x01, 0x01, 0x00, 0x05, 0x00, 49 | ]; 50 | 51 | let mut security_params = SecurityParams::new(); 52 | security_params.set_engine_boots(46).set_engine_time(195); 53 | 54 | let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 55 | 56 | let expected_scoped_pdu = vec![ 57 | 0xDB, 0x67, 0xD4, 0x26, 0xD3, 0x24, 0xD7, 0x5B, 0x84, 0x68, 0x25, 0x3F, 0x30, 0xE0, 0x71, 58 | 0xE4, 0xD2, 0x55, 0x2E, 0xC1, 0xB1, 0x9D, 0xA8, 0xB9, 0x11, 0x3E, 0x0D, 0xCF, 0x76, 0xBC, 59 | 0xE1, 0xDD, 0x7D, 0x02, 0x7C, 0x15, 0x91, 0xD9, 0x91, 0x76, 0xB4, 0x83, 0x38, 0x12, 0x08, 60 | 0x13, 0xF3, 0x72, 0x0D, 0xA8, 61 | ]; 62 | assert_eq!(encrypted_scoped_pdu, expected_scoped_pdu); 63 | 64 | let expected_salt = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; 65 | assert_eq!(salt, expected_salt); 66 | } 67 | 68 | #[test] 69 | fn it_decrypts_scoped_pdu_using_localized_md5_key() { 70 | let priv_key = Aes128PrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 71 | 72 | let encrypted_scoped_pdu = vec![ 73 | 0x5C, 0x91, 0xA4, 0x5F, 0x81, 0x44, 0xEF, 0xA0, 0x42, 0x9D, 0x8B, 0x38, 0x30, 0x9D, 0x25, 74 | 0x1F, 0x10, 0x96, 0x35, 0xBE, 0x8B, 0xD3, 0xCD, 0xB4, 0x7F, 0x33, 0xDE, 0xE8, 0xE2, 0xF6, 75 | 0x90, 0xE1, 0xA4, 0x63, 0x83, 0xA4, 0x2D, 0x8B, 0x5F, 0x4A, 0x62, 0x69, 0xC0, 0xD9, 0x7F, 76 | 0x93, 0xD0, 0x03, 0x26, 0xC8, 0xDA, 0x37, 0xF4, 0x0C, 0x44, 0x0E, 0x2D, 0x6B, 0x55, 0xE7, 77 | 0x17, 0xF8, 0xBF, 0x43, 0xC9, 0x10, 0xC0, 0x6F, 0x7A, 0xB4, 0x3A, 0xAD, 0x68, 0xE4, 0x3F, 78 | 0x42, 0x22, 0x79, 0x80, 0xEF, 0x4E, 0xC1, 0x4A, 0x9D, 0xF6, 0x15, 0x9B, 0x41, 0x8F, 0x69, 79 | 0x62, 0x08, 0x89, 0xBE, 0xCF, 0xC7, 0xAC, 0xC9, 0x85, 0xB0, 0xCF, 0xD8, 0xBD, 0x93, 0x9D, 80 | 0x51, 0xE1, 0x95, 0x65, 0x02, 0xB1, 0xCB, 0x93, 0x62, 0x58, 0x8F, 0x7E, 0x09, 0xE5, 0x06, 81 | 0xB4, 0xBD, 0x81, 0xE0, 0x7C, 0x3F, 0x81, 0xE2, 0x99, 0x91, 0x33, 0x1A, 0x30, 0x4F, 0x90, 82 | 0x18, 0xC1, 0xC5, 0x7B, 0x5D, 0x32, 0xFD, 0xE8, 0x3D, 0x34, 0xBA, 0x21, 0xA5, 0xA6, 0x5C, 83 | 0x1D, 0x3C, 0x77, 0xCD, 0x9E, 0x91, 0x28, 0x65, 0x0F, 0xDA, 0x13, 0x6D, 0xDB, 0x38, 0x86, 84 | 0x86, 0x34, 0x0B, 0xD5, 0xCF, 0x29, 0xD0, 0xD2, 0xB6, 0x2D, 0xAF, 0x6D, 0x7D, 0x8E, 0xC9, 85 | 0x6A, 0x90, 0x68, 0xCD, 0x0C, 0xB7, 0x8F, 86 | ]; 87 | let mut security_params = SecurityParams::new(); 88 | security_params 89 | .set_engine_boots(46) 90 | .set_engine_time(2190) 91 | .set_priv_params(&[0xFC, 0x3C, 0x76, 0xDE, 0xAB, 0xC6, 0xAD, 0xED]); 92 | 93 | let decrypted_scoped_pdu = priv_key 94 | .decrypt(encrypted_scoped_pdu, &security_params) 95 | .unwrap(); 96 | 97 | let expected = vec![ 98 | 0x30, 0x81, 0xB8, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 99 | 0xA2, 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA2, 0x81, 0xA0, 0x02, 0x01, 0x01, 100 | 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x81, 0x94, 0x30, 0x81, 0x91, 0x06, 0x08, 0x2B, 101 | 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x04, 0x81, 0x84, 0x44, 0x61, 0x72, 0x77, 0x69, 102 | 0x6E, 0x20, 0x64, 0x61, 0x76, 0x69, 0x64, 0x73, 0x2D, 0x6D, 0x62, 0x70, 0x2E, 0x6C, 0x61, 103 | 0x6E, 0x20, 0x31, 0x39, 0x2E, 0x35, 0x2E, 0x30, 0x20, 0x44, 0x61, 0x72, 0x77, 0x69, 0x6E, 104 | 0x20, 0x4B, 0x65, 0x72, 0x6E, 0x65, 0x6C, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 105 | 0x20, 0x31, 0x39, 0x2E, 0x35, 0x2E, 0x30, 0x3A, 0x20, 0x54, 0x75, 0x65, 0x20, 0x4D, 0x61, 106 | 0x79, 0x20, 0x32, 0x36, 0x20, 0x32, 0x30, 0x3A, 0x34, 0x31, 0x3A, 0x34, 0x34, 0x20, 0x50, 107 | 0x44, 0x54, 0x20, 0x32, 0x30, 0x32, 0x30, 0x3B, 0x20, 0x72, 0x6F, 0x6F, 0x74, 0x3A, 0x78, 108 | 0x6E, 0x75, 0x2D, 0x36, 0x31, 0x35, 0x33, 0x2E, 0x31, 0x32, 0x31, 0x2E, 0x32, 0x7E, 0x32, 109 | 0x2F, 0x52, 0x45, 0x4C, 0x45, 0x41, 0x53, 0x45, 0x5F, 0x58, 0x38, 0x36, 0x5F, 0x36, 0x34, 110 | 0x20, 0x78, 0x38, 0x36, 0x5F, 0x36, 0x34, 111 | ]; 112 | assert_eq!(decrypted_scoped_pdu, expected); 113 | } 114 | 115 | #[test] 116 | fn it_decrypts_scoped_pdu_using_localized_sha1_key() { 117 | let priv_key = 118 | Aes128PrivKey::with_localized_key(LocalizedSha1Key::new(b"12345678", &ENGINE_ID)); 119 | 120 | let encrypted_scoped_pdu = vec![ 121 | 0xFB, 0x91, 0x0B, 0xBC, 0xD3, 0x42, 0xF8, 0x65, 0xD4, 0xAF, 0x89, 0xE5, 0xC1, 0x92, 0x2B, 122 | 0x9B, 0xBA, 0x37, 0x94, 0x59, 0x84, 0x84, 0x8E, 0x01, 0x76, 0xF3, 0xDE, 0x51, 0x50, 0xCB, 123 | 0x30, 0x4D, 0x7E, 0xFC, 0x3D, 0x3C, 0xDF, 0xC0, 0x7A, 0x3C, 0xFB, 0x94, 0xC9, 0x05, 0x87, 124 | 0xE2, 0x5D, 0xD1, 0x16, 0x03, 0xBD, 0x7B, 0xE6, 0x04, 0x2A, 0xD8, 0x2B, 0xEC, 0x0C, 0xA0, 125 | 0xB6, 0x4B, 0xCD, 0xC4, 0xFD, 0xE4, 0x80, 0x06, 0x2D, 0x57, 0x8D, 0x79, 0x36, 0xA5, 0x29, 126 | 0xB2, 0x58, 0x6B, 0x02, 0x91, 0x4D, 0xB8, 0x73, 0x44, 0xB3, 0x9B, 0x69, 0xE8, 0xC4, 0x73, 127 | 0x2A, 0x42, 0x5B, 0x42, 0x9F, 0x20, 0x7D, 0x57, 0x8E, 0x98, 0x84, 0xDF, 0xEE, 0x49, 0x77, 128 | 0x18, 0x6E, 0xB1, 0x57, 0x3E, 0xCA, 0x66, 0xD2, 0x33, 0x67, 0xD4, 0x18, 0x48, 0x44, 0x55, 129 | 0xE2, 0xB7, 0x93, 0xA4, 0xFB, 0xDF, 0x7F, 0x9E, 0x9D, 0xC2, 0x73, 0x5A, 0x87, 0x36, 0xA7, 130 | 0x22, 0xCA, 0xF5, 0x6F, 0x33, 0x2E, 0xC3, 0x37, 0x34, 0xEE, 0x96, 0x10, 0x34, 0x95, 0x5F, 131 | 0xCA, 0x4E, 0x83, 0x5A, 0x64, 0x22, 0xA1, 0xAC, 0xBA, 0x2E, 0xA4, 0xBC, 0x2A, 0xCF, 0xDA, 132 | 0x88, 0xF0, 0xD9, 0xB8, 0xCC, 0x03, 0xDF, 0x2F, 0xD1, 0x27, 0x01, 0x8E, 0x34, 0xB5, 0x6C, 133 | 0x32, 0x45, 0x5F, 0x63, 0x19, 0x5B, 0xE8, 134 | ]; 135 | let mut security_params = SecurityParams::new(); 136 | security_params 137 | .set_engine_boots(46) 138 | .set_engine_time(69550) 139 | .set_priv_params(&[0xFC, 0x3C, 0x76, 0xDE, 0xAB, 0xC6, 0xAD, 0xEE]); 140 | 141 | let decrypted_scoped_pdu = priv_key 142 | .decrypt(encrypted_scoped_pdu, &security_params) 143 | .unwrap(); 144 | 145 | let expected = vec![ 146 | 0x30, 0x81, 0xB8, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 147 | 0xA2, 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA2, 0x81, 0xA0, 0x02, 0x01, 0x01, 148 | 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x81, 0x94, 0x30, 0x81, 0x91, 0x06, 0x08, 0x2B, 149 | 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x04, 0x81, 0x84, 0x44, 0x61, 0x72, 0x77, 0x69, 150 | 0x6E, 0x20, 0x64, 0x61, 0x76, 0x69, 0x64, 0x73, 0x2D, 0x6D, 0x62, 0x70, 0x2E, 0x6C, 0x61, 151 | 0x6E, 0x20, 0x31, 0x39, 0x2E, 0x35, 0x2E, 0x30, 0x20, 0x44, 0x61, 0x72, 0x77, 0x69, 0x6E, 152 | 0x20, 0x4B, 0x65, 0x72, 0x6E, 0x65, 0x6C, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 153 | 0x20, 0x31, 0x39, 0x2E, 0x35, 0x2E, 0x30, 0x3A, 0x20, 0x54, 0x75, 0x65, 0x20, 0x4D, 0x61, 154 | 0x79, 0x20, 0x32, 0x36, 0x20, 0x32, 0x30, 0x3A, 0x34, 0x31, 0x3A, 0x34, 0x34, 0x20, 0x50, 155 | 0x44, 0x54, 0x20, 0x32, 0x30, 0x32, 0x30, 0x3B, 0x20, 0x72, 0x6F, 0x6F, 0x74, 0x3A, 0x78, 156 | 0x6E, 0x75, 0x2D, 0x36, 0x31, 0x35, 0x33, 0x2E, 0x31, 0x32, 0x31, 0x2E, 0x32, 0x7E, 0x32, 157 | 0x2F, 0x52, 0x45, 0x4C, 0x45, 0x41, 0x53, 0x45, 0x5F, 0x58, 0x38, 0x36, 0x5F, 0x36, 0x34, 158 | 0x20, 0x78, 0x38, 0x36, 0x5F, 0x36, 0x34, 159 | ]; 160 | assert_eq!(decrypted_scoped_pdu, expected); 161 | } 162 | 163 | #[test] 164 | fn it_returns_error_for_priv_params_with_wrong_len() { 165 | let priv_key = 166 | Aes128PrivKey::with_localized_key(LocalizedSha1Key::new(b"12345678", &ENGINE_ID)); 167 | 168 | let encrypted_scoped_pdu = vec![ 169 | 0xFB, 0x91, 0x0B, 0xBC, 0xD3, 0x42, 0xF8, 0x65, 0xD4, 0xAF, 0x89, 0xE5, 0xC1, 0x92, 0x2B, 170 | 0x9B, 0xBA, 0x37, 0x94, 0x59, 0x84, 0x84, 0x8E, 0x01, 0x76, 0xF3, 0xDE, 0x51, 0x50, 0xCB, 171 | 0x30, 0x4D, 0x7E, 0xFC, 0x3D, 0x3C, 0xDF, 0xC0, 0x7A, 0x3C, 0xFB, 0x94, 0xC9, 0x05, 0x87, 172 | 0xE2, 0x5D, 0xD1, 0x16, 0x03, 0xBD, 0x7B, 0xE6, 0x04, 0x2A, 0xD8, 0x2B, 0xEC, 0x0C, 0xA0, 173 | 0xB6, 0x4B, 0xCD, 0xC4, 0xFD, 0xE4, 0x80, 0x06, 0x2D, 0x57, 0x8D, 0x79, 0x36, 0xA5, 0x29, 174 | 0xB2, 0x58, 0x6B, 0x02, 0x91, 0x4D, 0xB8, 0x73, 0x44, 0xB3, 0x9B, 0x69, 0xE8, 0xC4, 0x73, 175 | 0x2A, 0x42, 0x5B, 0x42, 0x9F, 0x20, 0x7D, 0x57, 0x8E, 0x98, 0x84, 0xDF, 0xEE, 0x49, 0x77, 176 | 0x18, 0x6E, 0xB1, 0x57, 0x3E, 0xCA, 0x66, 0xD2, 0x33, 0x67, 0xD4, 0x18, 0x48, 0x44, 0x55, 177 | 0xE2, 0xB7, 0x93, 0xA4, 0xFB, 0xDF, 0x7F, 0x9E, 0x9D, 0xC2, 0x73, 0x5A, 0x87, 0x36, 0xA7, 178 | 0x22, 0xCA, 0xF5, 0x6F, 0x33, 0x2E, 0xC3, 0x37, 0x34, 0xEE, 0x96, 0x10, 0x34, 0x95, 0x5F, 179 | 0xCA, 0x4E, 0x83, 0x5A, 0x64, 0x22, 0xA1, 0xAC, 0xBA, 0x2E, 0xA4, 0xBC, 0x2A, 0xCF, 0xDA, 180 | 0x88, 0xF0, 0xD9, 0xB8, 0xCC, 0x03, 0xDF, 0x2F, 0xD1, 0x27, 0x01, 0x8E, 0x34, 0xB5, 0x6C, 181 | 0x32, 0x45, 0x5F, 0x63, 0x19, 0x5B, 0xE8, 182 | ]; 183 | let mut security_params = SecurityParams::new(); 184 | security_params 185 | .set_engine_boots(46) 186 | .set_engine_time(69550) 187 | // Missing last byte 0xEE. 188 | .set_priv_params(&[0xFC, 0x3C, 0x76, 0xDE, 0xAB, 0xC6, 0xAD]); 189 | 190 | let result = priv_key.decrypt(encrypted_scoped_pdu, &security_params); 191 | assert_eq!(result, Err(SecurityError::DecryptError)); 192 | } 193 | 194 | #[test] 195 | fn it_returns_empty_vec_when_encrypting_empty_scoped_pdu() { 196 | let priv_key = Aes128PrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 197 | 198 | let scoped_pdu = vec![]; 199 | 200 | let mut security_params = SecurityParams::new(); 201 | security_params.set_engine_boots(45).set_engine_time(68902); 202 | 203 | let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 204 | 205 | assert_eq!(encrypted_scoped_pdu, vec![]); 206 | 207 | let expected_salt = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; 208 | assert_eq!(salt, expected_salt); 209 | } 210 | 211 | #[test] 212 | fn it_returns_empty_vec_when_decrypting_empty_scoped_pdu() { 213 | let priv_key = Aes128PrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 214 | 215 | let encrypted_scoped_pdu = vec![]; 216 | let mut security_params = SecurityParams::new(); 217 | security_params 218 | .set_engine_boots(46) 219 | .set_engine_time(2190) 220 | .set_priv_params(&[0xFC, 0x3C, 0x76, 0xDE, 0xAB, 0xC6, 0xAD, 0xED]); 221 | 222 | let decrypted_scoped_pdu = priv_key 223 | .decrypt(encrypted_scoped_pdu, &security_params) 224 | .unwrap(); 225 | 226 | assert_eq!(decrypted_scoped_pdu, vec![]); 227 | } 228 | -------------------------------------------------------------------------------- /src/snmp_usm/tests/des_priv_key.rs: -------------------------------------------------------------------------------- 1 | use snmp_usm::{ 2 | self, DesPrivKey, LocalizedMd5Key, LocalizedSha1Key, PrivKey, SecurityError, SecurityParams, 3 | WithLocalizedKey, 4 | }; 5 | 6 | const ENGINE_ID: [u8; 17] = [ 7 | 0x80, 0x00, 0x1f, 0x88, 0x80, 0xfa, 0xa8, 0x11, 0x60, 0x0f, 0xa2, 0xc5, 0x5e, 0x00, 0x00, 0x00, 8 | 0x00, 9 | ]; 10 | 11 | #[test] 12 | fn it_encrypts_scoped_pdu_using_localized_md5_key() { 13 | let priv_key = DesPrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 14 | 15 | let scoped_pdu = vec![ 16 | 0x30, 0x30, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 17 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x19, 0x02, 0x01, 0x01, 0x02, 0x01, 18 | 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x02, 0x01, 19 | 0x01, 0x03, 0x00, 0x05, 0x00, 20 | ]; 21 | 22 | let mut security_params = SecurityParams::new(); 23 | security_params 24 | .set_engine_id(&ENGINE_ID) 25 | .set_engine_boots(47); 26 | 27 | let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 28 | 29 | let expected_scoped_pdu = vec![ 30 | 0xD7, 0xD8, 0xF9, 0x8F, 0xD7, 0xF0, 0x80, 0x76, 0x6D, 0xC9, 0xC8, 0x68, 0x41, 0xEE, 0x60, 31 | 0x08, 0x31, 0xC6, 0x69, 0x97, 0x7D, 0xC3, 0x17, 0x7C, 0x9F, 0x30, 0x34, 0xAB, 0x8D, 0xAF, 32 | 0x16, 0xA6, 0x64, 0x89, 0x2D, 0xFB, 0xA6, 0x97, 0x18, 0x84, 0x2B, 0xBA, 0xEC, 0x38, 0x9B, 33 | 0x89, 0x0F, 0x90, 0x84, 0x78, 0xC2, 0x94, 0xFD, 0x4B, 0x97, 0x53, 34 | ]; 35 | assert_eq!(encrypted_scoped_pdu, expected_scoped_pdu); 36 | 37 | let expected_salt = [0x00, 0x00, 0x00, 0x2F, 0x00, 0x00, 0x00, 0x00]; 38 | assert_eq!(salt, expected_salt); 39 | } 40 | 41 | #[test] 42 | fn it_encrypts_scoped_pdu_using_localized_sha1_key() { 43 | let priv_key = DesPrivKey::with_localized_key(LocalizedSha1Key::new(b"87654321", &ENGINE_ID)); 44 | 45 | let scoped_pdu = vec![ 46 | 0x30, 0x30, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 47 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0, 0x19, 0x02, 0x01, 0x01, 0x02, 0x01, 48 | 0x00, 0x02, 0x01, 0x00, 0x30, 0x0E, 0x30, 0x0C, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x02, 0x01, 49 | 0x01, 0x01, 0x00, 0x05, 0x00, 50 | ]; 51 | 52 | let mut security_params = SecurityParams::new(); 53 | security_params 54 | .set_engine_id(&ENGINE_ID) 55 | .set_engine_boots(48); 56 | 57 | let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 58 | 59 | let expected_scoped_pdu = vec![ 60 | 0x8F, 0xE2, 0x4F, 0x12, 0x76, 0xA0, 0x13, 0x34, 0x7D, 0x86, 0x63, 0x02, 0xE4, 0x4F, 0x42, 61 | 0x87, 0x4C, 0x94, 0x61, 0x8C, 0xA1, 0xD2, 0x98, 0xF8, 0x8D, 0x69, 0x7E, 0xB1, 0x9A, 0x55, 62 | 0xE9, 0x83, 0xFA, 0xE9, 0xDF, 0x1F, 0x98, 0x61, 0x16, 0x97, 0x81, 0xF1, 0x4A, 0xBA, 0xFA, 63 | 0x09, 0x79, 0x13, 0x77, 0x8C, 0xE6, 0xD6, 0x8C, 0x61, 0xA3, 0xEA, 64 | ]; 65 | assert_eq!(encrypted_scoped_pdu, expected_scoped_pdu); 66 | 67 | let expected_salt = [0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00]; 68 | assert_eq!(salt, expected_salt); 69 | } 70 | 71 | #[test] 72 | fn it_decrypts_scoped_pdu_using_localized_md5_key() { 73 | let priv_key = DesPrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 74 | 75 | let encrypted_scoped_pdu = vec![ 76 | 0xA8, 0xB6, 0x99, 0x8C, 0xE0, 0xE2, 0xF7, 0x88, 0x20, 0x6B, 0x55, 0x11, 0x00, 0x17, 0x4A, 77 | 0x78, 0x4C, 0x8B, 0x9D, 0x3B, 0x13, 0xE1, 0xAD, 0x68, 0x0B, 0xBB, 0xFD, 0xDB, 0xE5, 0xCE, 78 | 0x89, 0xF7, 0xB9, 0x57, 0x4B, 0x38, 0xDC, 0x46, 0x76, 0x3F, 0x29, 0xA8, 0x2C, 0x47, 0x00, 79 | 0xF9, 0x37, 0x45, 0x88, 0x33, 0x49, 0x6D, 0x7E, 0x19, 0x50, 0xFF, 80 | ]; 81 | let mut security_params = SecurityParams::new(); 82 | security_params.set_priv_params(&[0x00, 0x00, 0x00, 0x30, 0x1F, 0xFF, 0x4A, 0x99]); 83 | 84 | let decrypted_scoped_pdu = priv_key 85 | .decrypt(encrypted_scoped_pdu, &security_params) 86 | .unwrap(); 87 | 88 | let expected = vec![ 89 | 0x30, 0x33, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 90 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA2, 0x1C, 0x02, 0x01, 0x01, 0x02, 0x01, 91 | 0x00, 0x02, 0x01, 0x00, 0x30, 0x11, 0x30, 0x0F, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x02, 0x01, 92 | 0x01, 0x03, 0x00, 0x43, 0x03, 0x02, 0x20, 0x3B, 0x03, 0x03, 0x03, 93 | ]; 94 | assert_eq!(decrypted_scoped_pdu, expected); 95 | } 96 | 97 | #[test] 98 | fn it_decrypts_scoped_pdu_using_localized_sha1_key() { 99 | let priv_key = DesPrivKey::with_localized_key(LocalizedSha1Key::new(b"87654321", &ENGINE_ID)); 100 | 101 | let encrypted_scoped_pdu = vec![ 102 | 0x1F, 0xD0, 0x02, 0xD1, 0x7E, 0xAF, 0xDC, 0x6C, 0x00, 0xFC, 0x32, 0x44, 0x28, 0xAA, 0xFB, 103 | 0x76, 0x99, 0x3D, 0x94, 0xFD, 0x57, 0xB5, 0x5F, 0xC6, 0x87, 0xA2, 0x81, 0x73, 0xB8, 0xAB, 104 | 0x77, 0x29, 0x7E, 0xE5, 0x9F, 0xCE, 0x13, 0xDA, 0xF7, 0xDF, 0xD7, 0xD6, 0xC3, 0xD6, 0x7A, 105 | 0x7E, 0xDA, 0x4A, 0xC8, 0xBF, 0x43, 0x5E, 0xD2, 0xE5, 0xE6, 0xAE, 0x45, 0x5D, 0xA8, 0x64, 106 | 0x42, 0x94, 0x17, 0x44, 0x7B, 0x61, 0xEC, 0xBE, 0xC3, 0xF6, 0xFF, 0x64, 0x4B, 0x55, 0x51, 107 | 0x79, 0x67, 0x90, 0x8E, 0x14, 0x3B, 0xF6, 0xA3, 0xCA, 0x85, 0xC7, 0xC5, 0xA7, 0xC9, 0x29, 108 | 0x3E, 0x43, 0xC6, 0x3F, 0xE0, 0x9F, 0x23, 0x50, 0x8D, 0x97, 0x14, 0xC5, 0x8C, 0xC4, 0x51, 109 | 0x32, 0xFE, 0xF6, 0x4D, 0x22, 0x65, 0xC4, 0x5E, 0x99, 0xA9, 0xD2, 0x80, 0xB8, 0x57, 0x5C, 110 | 0x4D, 0xA0, 0xBC, 0xAE, 0x10, 0x54, 0x1D, 0x5E, 0xE4, 0x7F, 0xAF, 0xE1, 0x70, 0x69, 0x4F, 111 | 0x15, 0xC6, 0x75, 0xAB, 0x69, 0x35, 0xAE, 0x1D, 0x29, 0xE9, 0x2F, 0x7C, 0x9F, 0xF3, 0x70, 112 | 0x92, 0xDF, 0xF0, 0x30, 0x73, 0x98, 0xE3, 0x80, 0xEE, 0x86, 0xA3, 0x2D, 0xCC, 0xE5, 0x7F, 113 | 0xC2, 0x6D, 0xCE, 0xE8, 0xD2, 0xA4, 0x56, 0x14, 0x86, 0x0E, 0x76, 0x87, 0xC4, 0xB3, 0x00, 114 | 0x0B, 0x0E, 0xD9, 0xCD, 0x2C, 0x8A, 0xAD, 0xBE, 0xEF, 0xE7, 0x86, 0x4C, 115 | ]; 116 | let mut security_params = SecurityParams::new(); 117 | security_params.set_priv_params(&[0x00, 0x00, 0x00, 0x30, 0x1F, 0xFF, 0x4A, 0x9A]); 118 | 119 | let decrypted_scoped_pdu = priv_key 120 | .decrypt(encrypted_scoped_pdu, &security_params) 121 | .unwrap(); 122 | 123 | let expected = vec![ 124 | 0x30, 0x81, 0xB8, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 125 | 0xA2, 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA2, 0x81, 0xA0, 0x02, 0x01, 0x01, 126 | 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x81, 0x94, 0x30, 0x81, 0x91, 0x06, 0x08, 0x2B, 127 | 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x04, 0x81, 0x84, 0x44, 0x61, 0x72, 0x77, 0x69, 128 | 0x6E, 0x20, 0x64, 0x61, 0x76, 0x69, 0x64, 0x73, 0x2D, 0x6D, 0x62, 0x70, 0x2E, 0x6C, 0x61, 129 | 0x6E, 0x20, 0x31, 0x39, 0x2E, 0x35, 0x2E, 0x30, 0x20, 0x44, 0x61, 0x72, 0x77, 0x69, 0x6E, 130 | 0x20, 0x4B, 0x65, 0x72, 0x6E, 0x65, 0x6C, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 131 | 0x20, 0x31, 0x39, 0x2E, 0x35, 0x2E, 0x30, 0x3A, 0x20, 0x54, 0x75, 0x65, 0x20, 0x4D, 0x61, 132 | 0x79, 0x20, 0x32, 0x36, 0x20, 0x32, 0x30, 0x3A, 0x34, 0x31, 0x3A, 0x34, 0x34, 0x20, 0x50, 133 | 0x44, 0x54, 0x20, 0x32, 0x30, 0x32, 0x30, 0x3B, 0x20, 0x72, 0x6F, 0x6F, 0x74, 0x3A, 0x78, 134 | 0x6E, 0x75, 0x2D, 0x36, 0x31, 0x35, 0x33, 0x2E, 0x31, 0x32, 0x31, 0x2E, 0x32, 0x7E, 0x32, 135 | 0x2F, 0x52, 0x45, 0x4C, 0x45, 0x41, 0x53, 0x45, 0x5F, 0x58, 0x38, 0x36, 0x5F, 0x36, 0x34, 136 | 0x20, 0x78, 0x38, 0x36, 0x5F, 0x36, 0x34, 0x05, 0x05, 0x05, 0x05, 0x05, 137 | ]; 138 | assert_eq!(decrypted_scoped_pdu, expected); 139 | } 140 | 141 | #[test] 142 | fn it_returns_error_for_priv_params_with_wrong_len() { 143 | let priv_key = DesPrivKey::with_localized_key(LocalizedSha1Key::new(b"87654321", &ENGINE_ID)); 144 | 145 | let encrypted_scoped_pdu = vec![ 146 | 0x49, 0xDB, 0x95, 0xBC, 0xBF, 0xC3, 0x78, 0x60, 0xE0, 0x4B, 0x67, 0xDE, 0xD1, 0xBF, 0xED, 147 | 0x3B, 0x46, 0x7F, 0x6A, 0x23, 0x7B, 0x61, 0x80, 0x6E, 0x49, 0x89, 0xC, 0x21, 0x59, 0x77, 148 | 0xF0, 0x2F, 0x14, 0x6E, 0xE3, 0xF9, 0x76, 0xBD, 0x86, 0x64, 0x22, 0x8A, 0x1D, 0x31, 0x17, 149 | 0x7B, 0x40, 0x5C, 0x9C, 0x40, 0xB7, 0xFC, 0x68, 0x79, 0x5A, 0xC4, 150 | ]; 151 | let mut security_params = SecurityParams::new(); 152 | security_params 153 | // Missing last byte 0x9B. 154 | .set_priv_params(&[0x00, 0x00, 0x00, 0x30, 0x1F, 0xFF, 0x4A]); 155 | 156 | let result = priv_key.decrypt(encrypted_scoped_pdu, &security_params); 157 | assert_eq!(result, Err(SecurityError::DecryptError)); 158 | } 159 | 160 | #[test] 161 | fn it_returns_empty_vec_when_encrypting_empty_scoped_pdu() { 162 | let priv_key = DesPrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 163 | 164 | let scoped_pdu = vec![]; 165 | 166 | let mut security_params = SecurityParams::new(); 167 | security_params 168 | .set_engine_id(&ENGINE_ID) 169 | .set_engine_boots(47); 170 | 171 | let (encrypted_scoped_pdu, salt) = priv_key.encrypt(scoped_pdu, &security_params, 0); 172 | assert_eq!(encrypted_scoped_pdu, vec![]); 173 | 174 | let expected_salt = [0x00, 0x00, 0x00, 0x2F, 0x00, 0x00, 0x00, 0x00]; 175 | assert_eq!(salt, expected_salt); 176 | } 177 | 178 | #[test] 179 | fn it_returns_empty_vec_when_decrypting_empty_scoped_pdu() { 180 | let priv_key = DesPrivKey::with_localized_key(LocalizedMd5Key::new(b"12345678", &ENGINE_ID)); 181 | 182 | let encrypted_scoped_pdu = vec![]; 183 | let mut security_params = SecurityParams::new(); 184 | security_params.set_priv_params(&[0x00, 0x00, 0x00, 0x30, 0x1F, 0xFF, 0x4A, 0x99]); 185 | 186 | let decrypted_scoped_pdu = priv_key 187 | .decrypt(encrypted_scoped_pdu, &security_params) 188 | .unwrap(); 189 | 190 | assert_eq!(decrypted_scoped_pdu, vec![]); 191 | } 192 | -------------------------------------------------------------------------------- /src/snmp_usm/tests/security_params.rs: -------------------------------------------------------------------------------- 1 | use snmp_usm::{SecurityError, SecurityParams}; 2 | 3 | #[test] 4 | fn it_encodes_empty_security_params() { 5 | let result = SecurityParams::for_discovery().encode(); 6 | let expected = [ 7 | 0x30, 0x0E, 0x04, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 8 | 0x00, 9 | ]; 10 | 11 | assert_eq!(result, expected); 12 | } 13 | 14 | #[test] 15 | fn it_creates_security_params_with_username_and_auth_params() { 16 | let incoming_security_params = vec![ 17 | 0x30, 0x21, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 18 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x18, 0x02, 0x03, 0x01, 0x85, 0xFC, 0x04, 19 | 0x00, 0x04, 0x00, 0x04, 0x00, 20 | ]; 21 | let result = SecurityParams::decode(&incoming_security_params) 22 | .unwrap() 23 | .set_username(b"username") 24 | .set_auth_params_placeholder() 25 | .encode(); 26 | let expected = vec![ 27 | 0x30, 0x35, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2, 28 | 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x18, 0x02, 0x03, 0x01, 0x85, 0xFC, 0x04, 29 | 0x08, 0x75, 0x73, 0x65, 0x72, 0x6E, 0x61, 0x6D, 0x65, 0x04, 0x0C, 0x00, 0x00, 0x00, 0x00, 30 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 31 | ]; 32 | 33 | assert_eq!(result, expected); 34 | } 35 | 36 | #[test] 37 | fn it_returns_malformed_security_params_error_for_empty_security_params() { 38 | let incoming_security_params = []; 39 | let result = SecurityParams::decode(&incoming_security_params); 40 | 41 | assert_eq!(result, Err(SecurityError::MalformedSecurityParams)); 42 | } 43 | 44 | #[test] 45 | fn it_returns_malformed_security_params_error_for_negative_engine_boots() { 46 | let security_params = [ 47 | 0x30, 0x0E, 0x04, 0x00, 0x02, 0x01, 0xFF, 0x02, 0x01, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 48 | 0x00, 49 | ]; 50 | let result = SecurityParams::decode(&security_params); 51 | 52 | assert_eq!(result, Err(SecurityError::MalformedSecurityParams)); 53 | } 54 | 55 | #[test] 56 | fn it_returns_malformed_security_params_error_for_negative_engine_time() { 57 | let security_params = [ 58 | 0x30, 0x0E, 0x04, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0xFF, 0x04, 0x00, 0x04, 0x00, 0x04, 59 | 0x00, 60 | ]; 61 | let result = SecurityParams::decode(&security_params); 62 | 63 | assert_eq!(result, Err(SecurityError::MalformedSecurityParams)); 64 | } 65 | --------------------------------------------------------------------------------