├── .github ├── dependabot.yml └── workflows │ ├── rust.yml │ └── security-audit.yml ├── .gitignore ├── .travis.yml ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── assets ├── snmpv1_req.bin ├── snmpv1_trap_coldstart.bin ├── snmpv2c-get-response.bin ├── snmpv3-report.bin ├── snmpv3_req.bin └── snmpv3_req_encrypted.bin ├── fuzz ├── .gitignore ├── Cargo.toml └── fuzz_targets │ ├── fuzzer_snmp_generic.rs │ ├── fuzzer_snmp_v1.rs │ └── fuzzer_snmp_v3.rs ├── src ├── error.rs ├── generic.rs ├── lib.rs ├── snmp.rs ├── snmpv3.rs └── usm.rs └── tests ├── v1.rs ├── v2c.rs └── v3.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "cargo" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | - package-ecosystem: github-actions 8 | directory: "/" 9 | schedule: 10 | interval: weekly 11 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Continuous integration 2 | 3 | on: 4 | push: 5 | pull_request: 6 | merge_group: 7 | schedule: 8 | - cron: '0 18 * * *' 9 | 10 | env: 11 | check_ext_rust_version: nightly-2024-06-30 12 | # ^ sync with https://github.com/awslabs/cargo-check-external-types/blob/main/rust-toolchain.toml 13 | 14 | jobs: 15 | check: 16 | name: Check 17 | runs-on: ubuntu-latest 18 | strategy: 19 | matrix: 20 | rust: 21 | - stable 22 | - 1.63.0 23 | - nightly 24 | steps: 25 | - uses: actions/checkout@v4 26 | - name: Install ${{ matrix.rust }} toolchain 27 | uses: dtolnay/rust-toolchain@master 28 | with: 29 | profile: minimal 30 | toolchain: ${{ matrix.rust }} 31 | override: true 32 | - name: Cargo update 33 | run: cargo update 34 | - run: RUSTFLAGS="-D warnings" cargo check 35 | 36 | test_features: 37 | name: Test suite (with features) 38 | runs-on: ubuntu-latest 39 | strategy: 40 | matrix: 41 | features: 42 | - --all-features 43 | steps: 44 | - uses: actions/checkout@v4 45 | - name: Install stable toolchain 46 | uses: dtolnay/rust-toolchain@stable 47 | - run: cargo test ${{ matrix.features }} 48 | 49 | fmt: 50 | name: Rustfmt 51 | runs-on: ubuntu-latest 52 | steps: 53 | - uses: actions/checkout@v4 54 | - name: Install stable rustfmt 55 | uses: dtolnay/rust-toolchain@stable 56 | with: 57 | components: rustfmt 58 | - run: cargo fmt --all -- --check 59 | 60 | clippy: 61 | name: Clippy 62 | runs-on: ubuntu-latest 63 | steps: 64 | - uses: actions/checkout@v4 65 | - name: Install nightly clippy 66 | uses: dtolnay/rust-toolchain@nightly 67 | with: 68 | components: clippy 69 | - run: cargo clippy -- -D warnings 70 | 71 | doc: 72 | name: Build documentation 73 | runs-on: ubuntu-latest 74 | env: 75 | RUSTDOCFLAGS: --cfg docsrs 76 | steps: 77 | - uses: actions/checkout@v4 78 | - name: Install nightly rust 79 | uses: dtolnay/rust-toolchain@nightly 80 | - run: cargo doc --workspace --no-deps --all-features 81 | 82 | semver: 83 | name: Check semver compatibility 84 | runs-on: ubuntu-latest 85 | steps: 86 | - name: Checkout sources 87 | uses: actions/checkout@v4 88 | - name: Check semver 89 | uses: obi1kenobi/cargo-semver-checks-action@v2 90 | 91 | check-external-types: 92 | name: Validate external types appearing in public API 93 | runs-on: ubuntu-latest 94 | steps: 95 | - name: Checkout sources 96 | uses: actions/checkout@v4 97 | - name: Install rust toolchain 98 | uses: dtolnay/rust-toolchain@master 99 | with: 100 | toolchain: ${{ env.check_ext_rust_version }} 101 | - run: cargo install --locked cargo-check-external-types 102 | - run: cargo check-external-types 103 | -------------------------------------------------------------------------------- /.github/workflows/security-audit.yml: -------------------------------------------------------------------------------- 1 | name: Security audit 2 | on: 3 | schedule: 4 | - cron: "0 8 * * *" 5 | push: 6 | paths: 7 | - "**/Cargo.*" 8 | jobs: 9 | security_audit: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: rustsec/audit-check@v2 14 | with: 15 | token: ${{ secrets.GITHUB_TOKEN }} 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | matrix: 4 | include: 5 | - rust: stable 6 | env: 7 | - NAME="stable" 8 | - FEATURES='' 9 | - rust: nightly 10 | env: 11 | - NAME="nightly" 12 | - FEATURES='' 13 | script: 14 | - | 15 | cargo build --verbose --features "$FEATURES" && 16 | cargo test --verbose --features "$FEATURES" && 17 | ([ "$BENCH" != 1 ] || cargo bench --verbose --features "$FEATURES") 18 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "asn1-rs" 7 | version = "0.7.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "607495ec7113b178fbba7a6166a27f99e774359ef4823adbefd756b5b81d7970" 10 | dependencies = [ 11 | "asn1-rs-derive", 12 | "asn1-rs-impl", 13 | "displaydoc", 14 | "nom", 15 | "num-traits", 16 | "rusticata-macros", 17 | "thiserror", 18 | ] 19 | 20 | [[package]] 21 | name = "asn1-rs-derive" 22 | version = "0.6.0" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" 25 | dependencies = [ 26 | "proc-macro2", 27 | "quote", 28 | "syn", 29 | "synstructure", 30 | ] 31 | 32 | [[package]] 33 | name = "asn1-rs-impl" 34 | version = "0.2.0" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" 37 | dependencies = [ 38 | "proc-macro2", 39 | "quote", 40 | "syn", 41 | ] 42 | 43 | [[package]] 44 | name = "autocfg" 45 | version = "1.4.0" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" 48 | 49 | [[package]] 50 | name = "diff" 51 | version = "0.1.13" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" 54 | 55 | [[package]] 56 | name = "displaydoc" 57 | version = "0.2.5" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" 60 | dependencies = [ 61 | "proc-macro2", 62 | "quote", 63 | "syn", 64 | ] 65 | 66 | [[package]] 67 | name = "hex-literal" 68 | version = "0.4.1" 69 | source = "registry+https://github.com/rust-lang/crates.io-index" 70 | checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" 71 | 72 | [[package]] 73 | name = "memchr" 74 | version = "2.7.4" 75 | source = "registry+https://github.com/rust-lang/crates.io-index" 76 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 77 | 78 | [[package]] 79 | name = "minimal-lexical" 80 | version = "0.2.1" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" 83 | 84 | [[package]] 85 | name = "nom" 86 | version = "7.1.3" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" 89 | dependencies = [ 90 | "memchr", 91 | "minimal-lexical", 92 | ] 93 | 94 | [[package]] 95 | name = "num-traits" 96 | version = "0.2.19" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 99 | dependencies = [ 100 | "autocfg", 101 | ] 102 | 103 | [[package]] 104 | name = "pretty_assertions" 105 | version = "1.4.1" 106 | source = "registry+https://github.com/rust-lang/crates.io-index" 107 | checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" 108 | dependencies = [ 109 | "diff", 110 | "yansi", 111 | ] 112 | 113 | [[package]] 114 | name = "proc-macro2" 115 | version = "1.0.93" 116 | source = "registry+https://github.com/rust-lang/crates.io-index" 117 | checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" 118 | dependencies = [ 119 | "unicode-ident", 120 | ] 121 | 122 | [[package]] 123 | name = "quote" 124 | version = "1.0.38" 125 | source = "registry+https://github.com/rust-lang/crates.io-index" 126 | checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" 127 | dependencies = [ 128 | "proc-macro2", 129 | ] 130 | 131 | [[package]] 132 | name = "rusticata-macros" 133 | version = "4.1.0" 134 | source = "registry+https://github.com/rust-lang/crates.io-index" 135 | checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" 136 | dependencies = [ 137 | "nom", 138 | ] 139 | 140 | [[package]] 141 | name = "snmp-parser" 142 | version = "0.11.0" 143 | dependencies = [ 144 | "asn1-rs", 145 | "hex-literal", 146 | "nom", 147 | "pretty_assertions", 148 | "rusticata-macros", 149 | "thiserror", 150 | ] 151 | 152 | [[package]] 153 | name = "syn" 154 | version = "2.0.98" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" 157 | dependencies = [ 158 | "proc-macro2", 159 | "quote", 160 | "unicode-ident", 161 | ] 162 | 163 | [[package]] 164 | name = "synstructure" 165 | version = "0.13.1" 166 | source = "registry+https://github.com/rust-lang/crates.io-index" 167 | checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" 168 | dependencies = [ 169 | "proc-macro2", 170 | "quote", 171 | "syn", 172 | ] 173 | 174 | [[package]] 175 | name = "thiserror" 176 | version = "2.0.11" 177 | source = "registry+https://github.com/rust-lang/crates.io-index" 178 | checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" 179 | dependencies = [ 180 | "thiserror-impl", 181 | ] 182 | 183 | [[package]] 184 | name = "thiserror-impl" 185 | version = "2.0.11" 186 | source = "registry+https://github.com/rust-lang/crates.io-index" 187 | checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" 188 | dependencies = [ 189 | "proc-macro2", 190 | "quote", 191 | "syn", 192 | ] 193 | 194 | [[package]] 195 | name = "unicode-ident" 196 | version = "1.0.16" 197 | source = "registry+https://github.com/rust-lang/crates.io-index" 198 | checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034" 199 | 200 | [[package]] 201 | name = "yansi" 202 | version = "1.0.1" 203 | source = "registry+https://github.com/rust-lang/crates.io-index" 204 | checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" 205 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "snmp-parser" 3 | version = "0.11.0" 4 | description = "Parser for the SNMP protocol" 5 | license = "MIT/Apache-2.0" 6 | keywords = ["SNMP","protocol","parser","nom"] 7 | authors = ["Pierre Chifflier "] 8 | homepage = "https://github.com/rusticata/snmp-parser" 9 | repository = "https://github.com/rusticata/snmp-parser.git" 10 | categories = ["parser-implementations"] 11 | readme = "README.md" 12 | edition = "2018" 13 | rust-version = "1.63" 14 | 15 | include = [ 16 | "LICENSE-*", 17 | "README.md", 18 | ".gitignore", 19 | ".travis.yml", 20 | "Cargo.toml", 21 | "assets/*.bin", 22 | "src/*.rs", 23 | "tests/*.rs" 24 | ] 25 | 26 | [dependencies] 27 | asn1-rs = "0.7" 28 | nom = "7.1" 29 | rusticata-macros = "4.0" 30 | thiserror = "2.0" 31 | 32 | [dev-dependencies] 33 | hex-literal = "0.4" 34 | pretty_assertions = "1.0" 35 | 36 | [package.metadata.cargo_check_external_types] 37 | allowed_external_types = [ 38 | "asn1_rs", 39 | "asn1_rs::*", 40 | "nom", 41 | "nom::*", 42 | ] 43 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Pierre Chifflier 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE-MIT) 4 | [![Apache License 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](./LICENSE-APACHE) 5 | [![Build Status](https://travis-ci.org/rusticata/snmp-parser.svg?branch=master)](https://travis-ci.org/rusticata/snmp-parser) 6 | [![Crates.io Version](https://img.shields.io/crates/v/snmp-parser.svg)](https://crates.io/crates/snmp-parser) 7 | 8 | # SNMP Parser 9 | 10 | A SNMP parser, implemented with the [nom](https://github.com/Geal/nom) 11 | parser combinator framework. 12 | 13 | The goal of this parser is to implement SNMP messages analysis, for example 14 | to use rules from a network IDS. 15 | 16 | To read a message, different functions must be used depending on the expected message 17 | version. The main functions for parsing are [`parse_snmp_v1`](https://docs.rs/snmp-parser/latest/snmp_parser/snmp/fn.parse_snmp_v1.html), 18 | [`parse_snmp_v2c`](https://docs.rs/snmp-parser/latest/snmp_parser/snmp/fn.parse_snmp_v2c.html) and 19 | [`parse_snmp_v3`](https://docs.rs/snmp-parser/latest/snmp_parser/snmpv3/fn.parse_snmp_v3.html). 20 | If you don't know the version of the message and want to parse a generic SNMP message, 21 | use the [`parse_snmp_generic_message`](https://docs.rs/snmp-parser/latest/snmp_parser/fn.parse_snmp_generic_message.html) function. 22 | 23 | The code is available on [Github](https://github.com/rusticata/snmp-parser) 24 | and is part of the [Rusticata](https://github.com/rusticata) project. 25 | 26 | 27 | ## Changes 28 | 29 | ### 0.11.0 30 | 31 | - Update asn1-rs to 0.7 32 | - Update thiserror to 2.0 33 | - Fix clippy warnings: elided lifetime has a name 34 | - Use `#[from]` instead of From impl for asn1 error 35 | - Re-export `Oid` and `OidParseError` 36 | - Fix renamed lint 37 | - Implement `FromBer` for all top-level messages 38 | 39 | Thanks: @MattesWhite 40 | 41 | ### 0.10.0 42 | 43 | - Update asn1-rs to 0.6 44 | 45 | ### 0.9.0 46 | 47 | - Convert to asn1-rs 48 | - Set MSRV to 1.57 49 | 50 | ### 0.8.0 51 | 52 | - Upgrade to nom 7 / der-parser 6 53 | 54 | ### 0.7.0 55 | 56 | - Upgrade to nom 6 / der-parser 5 57 | 58 | ### 0.6.0 59 | 60 | - Upgrade to der-parser 4 61 | 62 | ### 0.5.2 63 | 64 | - Use `parse_ber_u32` from der-parser crate 65 | 66 | ### 0.5.1 67 | 68 | - Fix parsing: use BER parsing so DER constraints are not applied 69 | 70 | ### 0.5.0 71 | 72 | - Upgrade to nom 5 and der-parser 3 73 | 74 | ## License 75 | 76 | Licensed under either of 77 | 78 | * Apache License, Version 2.0 79 | ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 80 | * MIT license 81 | ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 82 | 83 | at your option. 84 | 85 | ## Contribution 86 | 87 | Unless you explicitly state otherwise, any contribution intentionally submitted 88 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 89 | dual licensed as above, without any additional terms or conditions. 90 | -------------------------------------------------------------------------------- /assets/snmpv1_req.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rusticata/snmp-parser/38d1a22a4d889fa1cb677c33ec4616a35aac53ba/assets/snmpv1_req.bin -------------------------------------------------------------------------------- /assets/snmpv1_trap_coldstart.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rusticata/snmp-parser/38d1a22a4d889fa1cb677c33ec4616a35aac53ba/assets/snmpv1_trap_coldstart.bin -------------------------------------------------------------------------------- /assets/snmpv2c-get-response.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rusticata/snmp-parser/38d1a22a4d889fa1cb677c33ec4616a35aac53ba/assets/snmpv2c-get-response.bin -------------------------------------------------------------------------------- /assets/snmpv3-report.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rusticata/snmp-parser/38d1a22a4d889fa1cb677c33ec4616a35aac53ba/assets/snmpv3-report.bin -------------------------------------------------------------------------------- /assets/snmpv3_req.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rusticata/snmp-parser/38d1a22a4d889fa1cb677c33ec4616a35aac53ba/assets/snmpv3_req.bin -------------------------------------------------------------------------------- /assets/snmpv3_req_encrypted.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rusticata/snmp-parser/38d1a22a4d889fa1cb677c33ec4616a35aac53ba/assets/snmpv3_req_encrypted.bin -------------------------------------------------------------------------------- /fuzz/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | target 3 | corpus 4 | artifacts 5 | -------------------------------------------------------------------------------- /fuzz/Cargo.toml: -------------------------------------------------------------------------------- 1 | 2 | [package] 3 | name = "snmp-parser-fuzz" 4 | version = "0.0.1" 5 | authors = ["Automatically generated"] 6 | publish = false 7 | 8 | [package.metadata] 9 | cargo-fuzz = true 10 | 11 | [dependencies.snmp-parser] 12 | path = ".." 13 | [dependencies.libfuzzer-sys] 14 | git = "https://github.com/rust-fuzz/libfuzzer-sys.git" 15 | 16 | # Prevent this from interfering with workspaces 17 | [workspace] 18 | members = ["."] 19 | 20 | [[bin]] 21 | name = "fuzzer_snmp_v1" 22 | path = "fuzz_targets/fuzzer_snmp_v1.rs" 23 | 24 | [[bin]] 25 | name = "fuzzer_snmp_v3" 26 | path = "fuzz_targets/fuzzer_snmp_v3.rs" 27 | 28 | [[bin]] 29 | name = "fuzzer_snmp_generic" 30 | path = "fuzz_targets/fuzzer_snmp_generic.rs" 31 | -------------------------------------------------------------------------------- /fuzz/fuzz_targets/fuzzer_snmp_generic.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | #[macro_use] extern crate libfuzzer_sys; 3 | extern crate snmp_parser; 4 | 5 | fuzz_target!(|data: &[u8]| { 6 | // fuzzed code goes here 7 | let _ = snmp_parser::parse_snmp_generic_message(data); 8 | }); 9 | -------------------------------------------------------------------------------- /fuzz/fuzz_targets/fuzzer_snmp_v1.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | #[macro_use] extern crate libfuzzer_sys; 3 | extern crate snmp_parser; 4 | 5 | fuzz_target!(|data: &[u8]| { 6 | // fuzzed code goes here 7 | let _ = snmp_parser::parse_snmp_v1(data); 8 | }); 9 | -------------------------------------------------------------------------------- /fuzz/fuzz_targets/fuzzer_snmp_v3.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | #[macro_use] extern crate libfuzzer_sys; 3 | extern crate snmp_parser; 4 | 5 | fuzz_target!(|data: &[u8]| { 6 | // fuzzed code goes here 7 | let _ = snmp_parser::parse_snmp_v3(data); 8 | }); 9 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use asn1_rs::Error; 2 | use nom::error::{ErrorKind, ParseError}; 3 | use std::convert::From; 4 | 5 | #[derive(Debug, PartialEq, thiserror::Error)] 6 | pub enum SnmpError { 7 | #[error("Invalid message: not a DER sequence, or unexpected number of items, etc.")] 8 | InvalidMessage, 9 | #[error("Invalid version: not a number, or not in supported range (1, 2 or 3)")] 10 | InvalidVersion, 11 | #[error("Unknown or invalid PDU type")] 12 | InvalidPduType, 13 | #[error("Invalid PDU: content does not match type, or content cannot be decoded")] 14 | InvalidPdu, 15 | #[error("Invalid SNMPv3 header data")] 16 | InvalidHeaderData, 17 | #[error("Invalid SNMPv3 scoped PDU")] 18 | InvalidScopedPduData, 19 | #[error("Invalid SNMPv3 security model")] 20 | InvalidSecurityModel, 21 | #[error("Nom error")] 22 | NomError(ErrorKind), 23 | #[error("BER error")] 24 | BerError(#[from] Error), 25 | } 26 | 27 | impl ParseError for SnmpError { 28 | fn from_error_kind(_input: I, kind: ErrorKind) -> Self { 29 | SnmpError::NomError(kind) 30 | } 31 | fn append(_input: I, kind: ErrorKind, _other: Self) -> Self { 32 | SnmpError::NomError(kind) 33 | } 34 | } 35 | 36 | impl From for nom::Err { 37 | fn from(e: SnmpError) -> nom::Err { 38 | nom::Err::Error(e) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/generic.rs: -------------------------------------------------------------------------------- 1 | use crate::error::SnmpError; 2 | use crate::snmp::*; 3 | use crate::snmpv3::*; 4 | use asn1_rs::{Any, FromBer, Tag}; 5 | use nom::combinator::map_res; 6 | use nom::{Err, IResult}; 7 | 8 | /// An SNMP messsage parser, accepting v1, v2c or v3 messages 9 | /// 10 | /// # Examples 11 | /// 12 | /// ```rust 13 | /// use snmp_parser::{ScopedPduData, SecurityModel, SnmpGenericMessage}; 14 | /// use snmp_parser::asn1_rs::FromBer; 15 | /// 16 | /// static SNMPV3_REQ: &[u8] = include_bytes!("../assets/snmpv3_req.bin"); 17 | /// 18 | /// match SnmpGenericMessage::from_ber(&SNMPV3_REQ) { 19 | /// Ok((_, msg)) => { 20 | /// match msg { 21 | /// SnmpGenericMessage::V1(_) => todo!(), 22 | /// SnmpGenericMessage::V2(_) => todo!(), 23 | /// SnmpGenericMessage::V3(msgv3) => { 24 | /// assert!(msgv3.version == 3); 25 | /// assert!(msgv3.header_data.msg_security_model == SecurityModel::USM); 26 | /// match msgv3.data { 27 | /// ScopedPduData::Plaintext(_pdu) => { }, 28 | /// ScopedPduData::Encrypted(_) => (), 29 | /// } 30 | /// } 31 | /// } 32 | /// }, 33 | /// Err(e) => panic!("{}", e), 34 | /// } 35 | /// ``` 36 | #[derive(Debug, PartialEq)] 37 | pub enum SnmpGenericMessage<'a> { 38 | /// SNMP Version 1 (SNMPv1) message 39 | V1(SnmpMessage<'a>), 40 | /// SNMP Version 2c (SNMPv2c) message 41 | V2(SnmpMessage<'a>), 42 | /// SNMP Version 3 (SNMPv3) message 43 | V3(SnmpV3Message<'a>), 44 | } 45 | 46 | impl<'a> FromBer<'a, SnmpError> for SnmpGenericMessage<'a> { 47 | fn from_ber(bytes: &'a [u8]) -> asn1_rs::ParseResult<'a, Self, SnmpError> { 48 | let (rem, any) = Any::from_ber(bytes).or(Err(Err::Error(SnmpError::InvalidMessage)))?; 49 | if any.tag() != Tag::Sequence { 50 | return Err(Err::Error(SnmpError::InvalidMessage)); 51 | } 52 | let (r, version) = u32::from_ber(any.data).map_err(Err::convert)?; 53 | let (_, msg) = match version { 54 | 0 => { 55 | let (rem, msg) = parse_snmp_v1_pdu_content(r)?; 56 | (rem, SnmpGenericMessage::V1(msg)) 57 | } 58 | 1 => { 59 | let (rem, msg) = parse_snmp_v2c_pdu_content(r)?; 60 | (rem, SnmpGenericMessage::V2(msg)) 61 | } 62 | 3 => { 63 | let (rem, msg) = parse_snmp_v3_pdu_content(r)?; 64 | (rem, SnmpGenericMessage::V3(msg)) 65 | } 66 | _ => return Err(Err::Error(SnmpError::InvalidVersion)), 67 | }; 68 | Ok((rem, msg)) 69 | } 70 | } 71 | 72 | fn parse_snmp_v1_pdu_content(i: &[u8]) -> IResult<&[u8], SnmpMessage, SnmpError> { 73 | let (i, community) = parse_ber_octetstring_as_str(i).map_err(Err::convert)?; 74 | let (i, pdu) = parse_snmp_v1_pdu(i)?; 75 | let msg = SnmpMessage { 76 | version: 0, 77 | community: community.to_string(), 78 | pdu, 79 | }; 80 | Ok((i, msg)) 81 | } 82 | 83 | fn parse_snmp_v2c_pdu_content(i: &[u8]) -> IResult<&[u8], SnmpMessage, SnmpError> { 84 | let (i, community) = parse_ber_octetstring_as_str(i).map_err(Err::convert)?; 85 | let (i, pdu) = parse_snmp_v2c_pdu(i)?; 86 | let msg = SnmpMessage { 87 | version: 1, 88 | community: community.to_string(), 89 | pdu, 90 | }; 91 | Ok((i, msg)) 92 | } 93 | 94 | fn parse_snmp_v3_pdu_content(i: &[u8]) -> IResult<&[u8], SnmpV3Message, SnmpError> { 95 | let (i, hdr) = parse_snmp_v3_headerdata(i)?; 96 | let (i, secp) = map_res(<&[u8]>::from_ber, |x| parse_secp(x, &hdr))(i).map_err(Err::convert)?; 97 | let (i, data) = parse_snmp_v3_data(i, &hdr)?; 98 | let msg = SnmpV3Message { 99 | version: 3, 100 | header_data: hdr, 101 | security_params: secp, 102 | data, 103 | }; 104 | Ok((i, msg)) 105 | } 106 | 107 | /// Parse an SNMP messsage, accepting v1, v2c or v3 messages 108 | /// 109 | /// This function is equivalent to `SnmpGenericMessage::from_ber` 110 | pub fn parse_snmp_generic_message(i: &[u8]) -> IResult<&[u8], SnmpGenericMessage, SnmpError> { 111 | SnmpGenericMessage::from_ber(i) 112 | } 113 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE-MIT) 2 | //! [![Apache License 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](./LICENSE-APACHE) 3 | //! [![Build Status](https://travis-ci.org/rusticata/snmp-parser.svg?branch=master)](https://travis-ci.org/rusticata/snmp-parser) 4 | //! [![Crates.io Version](https://img.shields.io/crates/v/snmp-parser.svg)](https://crates.io/crates/snmp-parser) 5 | //! 6 | //! # SNMP Parser 7 | //! 8 | //! An SNMP parser, implemented with the [nom](https://github.com/Geal/nom) 9 | //! parser combinator framework. 10 | //! 11 | //! It is written in pure Rust, fast, and makes extensive use of zero-copy. 12 | //! It also aims to be panic-free. 13 | //! 14 | //! The goal of this parser is to implement SNMP messages analysis, for example 15 | //! to use rules from a network IDS. 16 | //! 17 | //! To read a message, different functions must be used depending on the expected message 18 | //! version. 19 | //! This crate implements the [`asn1_rs::FromBer`] trait, so to parse a message, use the 20 | //! expected object and call function `from_ber`. 21 | //! 22 | //! For example, to parse a SNMP v1 or v2c message (message structure is the same), use 23 | //! [`SnmpMessage`]`::from_ber(input)`. 24 | //! To parse a SNMP v3 message, use [`SnmpV3Message`]`::from_ber(input)`. 25 | //! If you don't know the version of the message and want to parse a generic SNMP message, 26 | //! use [`SnmpGenericMessage`]`::from_ber(input)`. 27 | //! 28 | //! Other methods of parsing (functions) are provided for compatibility: 29 | //! these functions are [`parse_snmp_v1`](snmp/fn.parse_snmp_v1.html), 30 | //! [`parse_snmp_v2c`](snmp/fn.parse_snmp_v2c.html) and 31 | //! [`parse_snmp_v3`](snmpv3/fn.parse_snmp_v3.html). 32 | //! If you don't know the version of the message and want to parse a generic SNMP message, 33 | //! use the [`parse_snmp_generic_message`](fn.parse_snmp_generic_message.html) function. 34 | //! 35 | //! The code is available on [Github](https://github.com/rusticata/snmp-parser) 36 | //! and is part of the [Rusticata](https://github.com/rusticata) project. 37 | 38 | #![deny(/*missing_docs,*/unsafe_code, 39 | unstable_features, 40 | unused_import_braces, unused_qualifications)] 41 | #![warn( 42 | missing_debug_implementations, 43 | /* missing_docs, 44 | rust_2018_idioms,*/ 45 | unreachable_pub 46 | )] 47 | #![forbid(unsafe_code)] 48 | #![deny(rustdoc::broken_intra_doc_links)] 49 | #![doc(test( 50 | no_crate_inject, 51 | attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables)) 52 | ))] 53 | #![cfg_attr(docsrs, feature(doc_cfg))] 54 | 55 | mod generic; 56 | mod usm; 57 | 58 | pub mod error; 59 | pub mod snmp; 60 | pub mod snmpv3; 61 | 62 | pub use generic::*; 63 | pub use snmp::*; 64 | pub use snmpv3::*; 65 | 66 | // re-exports to prevent public dependency on asn1_rs 67 | pub use asn1_rs; 68 | pub use asn1_rs::{Oid, OidParseError}; 69 | 70 | #[cfg(test)] 71 | mod tests { 72 | use asn1_rs::FromBer; 73 | 74 | use super::{SnmpGenericMessage, SnmpMessage, SnmpV3Message, SnmpVariable}; 75 | 76 | #[allow(dead_code)] 77 | fn assert_is_fromber<'a, E, T: FromBer<'a, E>>() {} 78 | 79 | #[test] 80 | fn check_traits() { 81 | assert_is_fromber::<_, SnmpVariable>(); 82 | assert_is_fromber::<_, SnmpMessage>(); 83 | assert_is_fromber::<_, SnmpV3Message>(); 84 | assert_is_fromber::<_, SnmpGenericMessage>(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/snmp.rs: -------------------------------------------------------------------------------- 1 | //! SNMP Parser (v1 and v2c) 2 | //! 3 | //! SNMP is defined in the following RFCs: 4 | //! - [RFC1157](https://tools.ietf.org/html/rfc1157): SNMP v1 5 | //! - [RFC1442](https://tools.ietf.org/html/rfc1442): Structure of Management Information for version 2 of the Simple Network Management Protocol (SNMPv2) 6 | //! - [RFC1902](https://tools.ietf.org/html/rfc1902): SNMP v2 SMI 7 | //! - [RFC2578](https://tools.ietf.org/html/rfc2578): Structure of Management Information Version 2 (SMIv2) 8 | //! - [RFC3416](https://tools.ietf.org/html/rfc3416): SNMP v2 9 | //! - [RFC2570](https://tools.ietf.org/html/rfc2570): Introduction to SNMP v3 10 | 11 | use crate::{error::SnmpError, Oid}; 12 | use asn1_rs::{ 13 | Any, BitString, Class, Error, FromBer, Header, Implicit, Integer, Sequence, Tag, TaggedValue, 14 | }; 15 | use nom::combinator::map; 16 | use nom::{Err, IResult}; 17 | use std::convert::TryFrom; 18 | use std::net::Ipv4Addr; 19 | use std::slice::Iter; 20 | use std::{fmt, str}; 21 | 22 | // This will be merged in next release of asn1-rs 23 | type Application = TaggedValue; 24 | 25 | #[derive(Clone, Copy, Eq, PartialEq)] 26 | pub struct PduType(pub u32); 27 | 28 | #[allow(non_upper_case_globals)] 29 | impl PduType { 30 | pub const GetRequest: PduType = PduType(0); 31 | pub const GetNextRequest: PduType = PduType(1); 32 | pub const Response: PduType = PduType(2); 33 | pub const SetRequest: PduType = PduType(3); 34 | pub const TrapV1: PduType = PduType(4); // Obsolete, was the old Trap-PDU in SNMPv1 35 | pub const GetBulkRequest: PduType = PduType(5); 36 | pub const InformRequest: PduType = PduType(6); 37 | pub const TrapV2: PduType = PduType(7); 38 | pub const Report: PduType = PduType(8); 39 | } 40 | 41 | impl fmt::Debug for PduType { 42 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 43 | match self.0 { 44 | 0 => f.write_str("GetRequest"), 45 | 1 => f.write_str("GetNextRequest"), 46 | 2 => f.write_str("Response"), 47 | 3 => f.write_str("SetRequest"), 48 | 4 => f.write_str("TrapV1"), 49 | 5 => f.write_str("GetBulkRequest"), 50 | 6 => f.write_str("InformRequest"), 51 | 7 => f.write_str("TrapV2"), 52 | 8 => f.write_str("Report"), 53 | n => f.debug_tuple("PduType").field(&n).finish(), 54 | } 55 | } 56 | } 57 | 58 | #[derive(Clone, Copy, Eq, PartialEq)] 59 | pub struct TrapType(pub u8); 60 | 61 | impl TrapType { 62 | pub const COLD_START: TrapType = TrapType(0); 63 | pub const WARM_START: TrapType = TrapType(1); 64 | pub const LINK_DOWN: TrapType = TrapType(2); 65 | pub const LINK_UP: TrapType = TrapType(3); 66 | pub const AUTHENTICATION_FAILURE: TrapType = TrapType(4); 67 | pub const EGP_NEIGHBOR_LOSS: TrapType = TrapType(5); 68 | pub const ENTERPRISE_SPECIFIC: TrapType = TrapType(6); 69 | } 70 | 71 | impl fmt::Debug for TrapType { 72 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 73 | match self.0 { 74 | 0 => f.write_str("coldStart"), 75 | 1 => f.write_str("warmStart"), 76 | 2 => f.write_str("linkDown"), 77 | 3 => f.write_str("linkUp"), 78 | 4 => f.write_str("authenticationFailure"), 79 | 5 => f.write_str("egpNeighborLoss"), 80 | 6 => f.write_str("enterpriseSpecific"), 81 | n => f.debug_tuple("TrapType").field(&n).finish(), 82 | } 83 | } 84 | } 85 | 86 | /// This CHOICE represents an address from one of possibly several 87 | /// protocol families. Currently, only one protocol family, the Internet 88 | /// family, is present in this CHOICE. 89 | #[derive(Copy, Clone, Debug, PartialEq)] 90 | pub enum NetworkAddress { 91 | IPv4(Ipv4Addr), 92 | } 93 | 94 | /// This application-wide type represents a non-negative integer which 95 | /// monotonically increases until it reaches a maximum value, when it 96 | /// wraps around and starts increasing again from zero. This memo 97 | /// specifies a maximum value of 2^32-1 (4294967295 decimal) for 98 | /// counters. 99 | pub type Counter = u32; 100 | 101 | /// This application-wide type represents a non-negative integer, which 102 | /// may increase or decrease, but which latches at a maximum value. This 103 | /// memo specifies a maximum value of 2^32-1 (4294967295 decimal) for 104 | /// gauges. 105 | pub type Gauge = u32; 106 | 107 | /// This application-wide type represents a non-negative integer which 108 | /// counts the time in hundredths of a second since some epoch. When 109 | /// object types are defined in the MIB which use this ASN.1 type, the 110 | /// description of the object type identifies the reference epoch. 111 | pub type TimeTicks = u32; 112 | 113 | #[derive(Clone, Copy, Eq, PartialEq)] 114 | pub struct ErrorStatus(pub u32); 115 | 116 | #[allow(non_upper_case_globals)] 117 | impl ErrorStatus { 118 | pub const NoError: ErrorStatus = ErrorStatus(0); 119 | pub const TooBig: ErrorStatus = ErrorStatus(1); 120 | pub const NoSuchName: ErrorStatus = ErrorStatus(2); 121 | pub const BadValue: ErrorStatus = ErrorStatus(3); 122 | pub const ReadOnly: ErrorStatus = ErrorStatus(4); 123 | pub const GenErr: ErrorStatus = ErrorStatus(5); 124 | } 125 | 126 | impl fmt::Debug for ErrorStatus { 127 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 128 | match self.0 { 129 | 0 => f.write_str("NoError"), 130 | 1 => f.write_str("TooBig"), 131 | 2 => f.write_str("NoSuchName"), 132 | 3 => f.write_str("BadValue"), 133 | 4 => f.write_str("ReadOnly"), 134 | 5 => f.write_str("GenErr"), 135 | n => f.debug_tuple("ErrorStatus").field(&n).finish(), 136 | } 137 | } 138 | } 139 | 140 | #[derive(Debug, PartialEq)] 141 | pub struct SnmpGenericPdu<'a> { 142 | pub pdu_type: PduType, 143 | pub req_id: u32, 144 | pub err: ErrorStatus, 145 | pub err_index: u32, 146 | pub var: Vec>, 147 | } 148 | 149 | #[derive(Debug, PartialEq)] 150 | pub struct SnmpBulkPdu<'a> { 151 | pub req_id: u32, 152 | pub non_repeaters: u32, 153 | pub max_repetitions: u32, 154 | pub var: Vec>, 155 | } 156 | 157 | #[derive(Debug, PartialEq)] 158 | pub struct SnmpTrapPdu<'a> { 159 | pub enterprise: Oid<'a>, 160 | pub agent_addr: NetworkAddress, 161 | pub generic_trap: TrapType, 162 | pub specific_trap: u32, 163 | pub timestamp: TimeTicks, 164 | pub var: Vec>, 165 | } 166 | 167 | #[derive(Debug, PartialEq)] 168 | pub enum SnmpPdu<'a> { 169 | Generic(SnmpGenericPdu<'a>), 170 | Bulk(SnmpBulkPdu<'a>), 171 | TrapV1(SnmpTrapPdu<'a>), 172 | } 173 | 174 | /// An SNMPv1 or SNMPv2c message 175 | /// 176 | /// Use the [`FromBer`] trait to parse messages. The method returns the 177 | /// remaining (unparsed) bytes and the object, or an error. 178 | /// 179 | /// Function [`parse_snmp_v1`] and [`parse_snmp_v2c`] are also provided, for convenience. 180 | /// 181 | /// # Examples 182 | /// 183 | /// ```rust 184 | /// use snmp_parser::SnmpMessage; 185 | /// use snmp_parser::asn1_rs::FromBer; 186 | /// 187 | /// static SNMPV1_REQ: &[u8] = include_bytes!("../assets/snmpv1_req.bin"); 188 | /// 189 | /// # fn main() { 190 | /// match SnmpMessage::from_ber(&SNMPV1_REQ) { 191 | /// Ok((_, ref r)) => { 192 | /// assert!(r.version == 0); 193 | /// assert!(r.community == String::from("public")); 194 | /// assert!(r.vars_iter().count() == 1); 195 | /// }, 196 | /// Err(e) => panic!("{}", e), 197 | /// } 198 | /// # } 199 | /// ``` 200 | #[derive(Debug, PartialEq)] 201 | pub struct SnmpMessage<'a> { 202 | /// Version, as raw-encoded: 0 for SNMPv1, 1 for SNMPv2c 203 | pub version: u32, 204 | pub community: String, 205 | pub pdu: SnmpPdu<'a>, 206 | } 207 | 208 | impl<'a> SnmpGenericPdu<'a> { 209 | pub fn vars_iter(&'a self) -> Iter<'a, SnmpVariable<'a>> { 210 | self.var.iter() 211 | } 212 | } 213 | 214 | impl<'a> SnmpTrapPdu<'a> { 215 | pub fn vars_iter(&'a self) -> Iter<'a, SnmpVariable<'a>> { 216 | self.var.iter() 217 | } 218 | } 219 | 220 | impl<'a> SnmpPdu<'a> { 221 | pub fn pdu_type(&self) -> PduType { 222 | match *self { 223 | SnmpPdu::Generic(ref pdu) => pdu.pdu_type, 224 | SnmpPdu::Bulk(_) => PduType::GetBulkRequest, 225 | SnmpPdu::TrapV1(_) => PduType::TrapV1, 226 | } 227 | } 228 | 229 | pub fn vars_iter(&'a self) -> Iter<'a, SnmpVariable<'a>> { 230 | match *self { 231 | SnmpPdu::Generic(ref pdu) => pdu.var.iter(), 232 | SnmpPdu::Bulk(ref pdu) => pdu.var.iter(), 233 | SnmpPdu::TrapV1(ref pdu) => pdu.var.iter(), 234 | } 235 | } 236 | } 237 | 238 | impl<'a> SnmpMessage<'a> { 239 | pub fn pdu_type(&self) -> PduType { 240 | self.pdu.pdu_type() 241 | } 242 | 243 | pub fn vars_iter(&'a self) -> Iter<'a, SnmpVariable<'a>> { 244 | self.pdu.vars_iter() 245 | } 246 | } 247 | 248 | impl<'a> FromBer<'a, SnmpError> for SnmpMessage<'a> { 249 | fn from_ber(bytes: &'a [u8]) -> asn1_rs::ParseResult<'a, Self, SnmpError> { 250 | // parse a SNMP v1 or V2 message 251 | Sequence::from_der_and_then(bytes, |i| { 252 | let (i, version) = u32::from_ber(i).map_err(Err::convert)?; 253 | if version > 1 { 254 | return Err(Err::Error(SnmpError::InvalidVersion)); 255 | } 256 | let (i, community) = parse_ber_octetstring_as_str(i).map_err(Err::convert)?; 257 | let (i, pdu) = if version == 0 { 258 | parse_snmp_v1_pdu(i)? 259 | } else { 260 | parse_snmp_v2c_pdu(i)? 261 | }; 262 | let msg = SnmpMessage { 263 | version, 264 | community: community.to_string(), 265 | pdu, 266 | }; 267 | Ok((i, msg)) 268 | }) 269 | //.map_err(Err::convert) 270 | } 271 | } 272 | 273 | #[derive(Debug, PartialEq)] 274 | pub struct SnmpVariable<'a> { 275 | pub oid: Oid<'a>, 276 | pub val: VarBindValue<'a>, 277 | } 278 | 279 | #[derive(Debug, PartialEq)] 280 | pub enum VarBindValue<'a> { 281 | Value(ObjectSyntax<'a>), 282 | Unspecified, 283 | NoSuchObject, 284 | NoSuchInstance, 285 | EndOfMibView, 286 | } 287 | 288 | ///
289 | /// VarBind ::= SEQUENCE {
290 | ///     name ObjectName,
291 | ///
292 | ///     CHOICE {
293 | ///         value          ObjectSyntax,
294 | ///         unSpecified    NULL,    -- in retrieval requests
295 | ///
296 | ///                                 -- exceptions in responses
297 | ///         noSuchObject   [0] IMPLICIT NULL,
298 | ///         noSuchInstance [1] IMPLICIT NULL,
299 | ///         endOfMibView   [2] IMPLICIT NULL
300 | ///     }
301 | /// }
302 | /// 
303 | impl<'a> TryFrom> for SnmpVariable<'a> { 304 | type Error = Error; 305 | 306 | fn try_from(any: Any<'a>) -> Result, Self::Error> { 307 | let (rem, oid) = Oid::from_ber(any.data)?; 308 | let (_, choice) = Any::from_ber(rem)?; 309 | let val = if choice.header.is_contextspecific() { 310 | match choice.tag().0 { 311 | 0 => VarBindValue::NoSuchObject, 312 | 1 => VarBindValue::NoSuchInstance, 313 | 2 => VarBindValue::EndOfMibView, 314 | _ => { 315 | return Err(Error::invalid_value( 316 | choice.tag(), 317 | "invalid VarBind tag".to_string(), 318 | )) 319 | } 320 | } 321 | } else if choice.tag() == Tag::Null { 322 | VarBindValue::Unspecified 323 | } else { 324 | VarBindValue::Value(ObjectSyntax::try_from(choice)?) 325 | }; 326 | let var_bind = SnmpVariable { oid, val }; 327 | Ok(var_bind) 328 | } 329 | } 330 | 331 | #[derive(Debug, PartialEq)] 332 | pub enum ObjectSyntax<'a> { 333 | Number(i32), 334 | String(&'a [u8]), 335 | Object(Oid<'a>), 336 | BitString(BitString<'a>), 337 | Empty, 338 | UnknownSimple(Any<'a>), 339 | IpAddress(NetworkAddress), 340 | Counter32(Counter), 341 | Gauge32(Gauge), 342 | TimeTicks(TimeTicks), 343 | Opaque(&'a [u8]), 344 | NsapAddress(&'a [u8]), 345 | Counter64(u64), 346 | UInteger32(u32), 347 | UnknownApplication(Any<'a>), 348 | } 349 | 350 | ///
351 | /// ObjectSyntax ::= CHOICE {
352 | ///     simple           SimpleSyntax,
353 | ///     application-wide ApplicationSyntax }
354 | ///
355 | /// SimpleSyntax ::= CHOICE {
356 | ///     integer-value   INTEGER (-2147483648..2147483647),
357 | ///     string-value    OCTET STRING (SIZE (0..65535)),
358 | ///     objectID-value  OBJECT IDENTIFIER }
359 | ///
360 | /// ApplicationSyntax ::= CHOICE {
361 | ///     ipAddress-value        IpAddress,
362 | ///     counter-value          Counter32,
363 | ///     timeticks-value        TimeTicks,
364 | ///     arbitrary-value        Opaque,
365 | ///     big-counter-value      Counter64,
366 | ///     unsigned-integer-value Unsigned32 }
367 | /// 
368 | impl<'a> TryFrom> for ObjectSyntax<'a> { 369 | type Error = Error; 370 | 371 | fn try_from(any: Any<'a>) -> Result, Self::Error> { 372 | if any.header.is_application() { 373 | // ApplicationSyntax 374 | match any.header.tag().0 { 375 | 0 => { 376 | // IpAddress ::= 377 | // [APPLICATION 0] 378 | // IMPLICIT OCTET STRING (SIZE (4)) 379 | let s = any.data; 380 | if s.len() == 4 { 381 | let ipv4 = NetworkAddress::IPv4(Ipv4Addr::new(s[0], s[1], s[2], s[3])); 382 | Ok(ObjectSyntax::IpAddress(ipv4)) 383 | } else { 384 | Err(Error::InvalidTag) 385 | } 386 | } 387 | tag @ 1..=3 => { 388 | // -- this wraps 389 | // Counter32 ::= 390 | // [APPLICATION 1] 391 | // IMPLICIT INTEGER (0..4294967295) 392 | // 393 | // -- this doesn't wrap 394 | // Gauge32 ::= 395 | // [APPLICATION 2] 396 | // IMPLICIT INTEGER (0..4294967295) 397 | // 398 | // -- an unsigned 32-bit quantity 399 | // -- indistinguishable from Gauge32 400 | // Unsigned32 ::= 401 | // [APPLICATION 2] 402 | // IMPLICIT INTEGER (0..4294967295) 403 | // 404 | // -- hundredths of seconds since an epoch 405 | // TimeTicks ::= 406 | // [APPLICATION 3] 407 | // IMPLICIT INTEGER (0..4294967295) 408 | let x = Integer::new(any.data).as_u32()?; 409 | let obj = match tag { 410 | 1 => ObjectSyntax::Counter32(x), 411 | 2 => ObjectSyntax::Gauge32(x), 412 | 3 => ObjectSyntax::TimeTicks(x), 413 | _ => unreachable!(), 414 | }; 415 | Ok(obj) 416 | } 417 | 4 => Ok(ObjectSyntax::Opaque(any.data)), 418 | 5 => Ok(ObjectSyntax::NsapAddress(any.data)), 419 | 6 => { 420 | let counter = Integer::new(any.data).as_u64()?; 421 | Ok(ObjectSyntax::Counter64(counter)) 422 | } 423 | 7 => { 424 | let number = Integer::new(any.data).as_u32()?; 425 | Ok(ObjectSyntax::UInteger32(number)) 426 | } 427 | _ => Ok(ObjectSyntax::UnknownApplication(any)), 428 | } 429 | } else { 430 | // SimpleSyntax 431 | 432 | // Some implementations do not send NULL, but empty objects 433 | // Treat 0-length objects as ObjectSyntax::Empty 434 | if any.data.is_empty() { 435 | return Ok(ObjectSyntax::Empty); 436 | } 437 | let obj = match any.header.tag() { 438 | Tag::BitString => ObjectSyntax::BitString(any.bitstring()?), 439 | Tag::Integer => { 440 | let number = any.integer()?.as_i32()?; 441 | ObjectSyntax::Number(number) 442 | } 443 | Tag::Null => ObjectSyntax::Empty, 444 | Tag::Oid => ObjectSyntax::Object(any.oid()?), 445 | Tag::OctetString => ObjectSyntax::String(any.data), 446 | _ => ObjectSyntax::UnknownSimple(any), 447 | }; 448 | Ok(obj) 449 | } 450 | } 451 | } 452 | 453 | #[inline] 454 | pub(crate) fn parse_ber_octetstring_as_str(i: &[u8]) -> IResult<&[u8], &str, Error> { 455 | let (rem, b) = <&[u8]>::from_ber(i)?; 456 | let s = core::str::from_utf8(b).map_err(|_| Error::StringInvalidCharset)?; 457 | Ok((rem, s)) 458 | } 459 | 460 | fn parse_varbind_list(i: &[u8]) -> IResult<&[u8], Vec, Error> { 461 | // parse_ber_sequence_of_v(parse_varbind)(i) 462 | >::from_ber(i) 463 | } 464 | 465 | ///
466 | ///  NetworkAddress ::=
467 | ///      CHOICE {
468 | ///          internet
469 | ///              IpAddress
470 | ///      }
471 | /// IpAddress ::=
472 | ///     [APPLICATION 0]          -- in network-byte order
473 | ///         IMPLICIT OCTET STRING (SIZE (4))
474 | /// 
475 | impl<'a> TryFrom> for NetworkAddress { 476 | type Error = Error; 477 | 478 | fn try_from(any: Any<'a>) -> Result { 479 | any.class().assert_eq(Class::Application)?; 480 | let s = any.data; 481 | if s.len() == 4 { 482 | Ok(NetworkAddress::IPv4(Ipv4Addr::new(s[0], s[1], s[2], s[3]))) 483 | } else { 484 | Err(Error::invalid_value( 485 | Tag::OctetString, 486 | "NetworkAddress invalid length".to_string(), 487 | )) 488 | } 489 | } 490 | } 491 | 492 | ///
493 | /// TimeTicks ::=
494 | ///     [APPLICATION 3]
495 | ///         IMPLICIT INTEGER (0..4294967295)
496 | /// 
497 | fn parse_timeticks(i: &[u8]) -> IResult<&[u8], TimeTicks, Error> { 498 | let (rem, tagged) = Application::::from_ber(i)?; 499 | Ok((rem, tagged.into_inner())) 500 | } 501 | 502 | fn parse_snmp_v1_generic_pdu(pdu: &[u8], tag: PduType) -> IResult<&[u8], SnmpPdu, SnmpError> { 503 | let (i, req_id) = u32::from_ber(pdu).map_err(Err::convert)?; 504 | let (i, err) = map(u32::from_ber, ErrorStatus)(i).map_err(Err::convert)?; 505 | let (i, err_index) = u32::from_ber(i).map_err(Err::convert)?; 506 | let (i, var) = parse_varbind_list(i).map_err(Err::convert)?; 507 | let pdu = SnmpPdu::Generic(SnmpGenericPdu { 508 | pdu_type: tag, 509 | req_id, 510 | err, 511 | err_index, 512 | var, 513 | }); 514 | Ok((i, pdu)) 515 | } 516 | 517 | fn parse_snmp_v1_bulk_pdu(i: &[u8]) -> IResult<&[u8], SnmpPdu, SnmpError> { 518 | let (i, req_id) = u32::from_ber(i).map_err(Err::convert)?; 519 | let (i, non_repeaters) = u32::from_ber(i).map_err(Err::convert)?; 520 | let (i, max_repetitions) = u32::from_ber(i).map_err(Err::convert)?; 521 | let (i, var) = parse_varbind_list(i).map_err(Err::convert)?; 522 | let pdu = SnmpBulkPdu { 523 | req_id, 524 | non_repeaters, 525 | max_repetitions, 526 | var, 527 | }; 528 | Ok((i, SnmpPdu::Bulk(pdu))) 529 | } 530 | 531 | fn parse_snmp_v1_trap_pdu(i: &[u8]) -> IResult<&[u8], SnmpPdu, SnmpError> { 532 | let (i, enterprise) = Oid::from_ber(i).map_err(Err::convert)?; 533 | let (i, agent_addr) = NetworkAddress::from_ber(i).map_err(Err::convert)?; 534 | let (i, generic_trap) = u32::from_ber(i).map_err(Err::convert)?; 535 | let (i, specific_trap) = u32::from_ber(i).map_err(Err::convert)?; 536 | let (i, timestamp) = parse_timeticks(i).map_err(Err::convert)?; 537 | let (i, var) = parse_varbind_list(i).map_err(Err::convert)?; 538 | let pdu = SnmpTrapPdu { 539 | enterprise, 540 | agent_addr, 541 | generic_trap: TrapType(generic_trap as u8), 542 | specific_trap, 543 | timestamp, 544 | var, 545 | }; 546 | Ok((i, SnmpPdu::TrapV1(pdu))) 547 | } 548 | 549 | /// Parse a SNMP v1 message. 550 | /// 551 | /// Top-level message 552 | /// 553 | ///
554 | /// Message ::=
555 | ///         SEQUENCE {
556 | ///             version          -- version-1 for this RFC
557 | ///                 INTEGER {
558 | ///                     version-1(0)
559 | ///                 },
560 | ///
561 | ///             community        -- community name
562 | ///                 OCTET STRING,
563 | ///
564 | ///             data             -- e.g., PDUs if trivial
565 | ///                 ANY          -- authentication is being used
566 | ///         }
567 | /// 
568 | /// 569 | /// Example: 570 | /// 571 | /// ```rust 572 | /// use snmp_parser::parse_snmp_v1; 573 | /// 574 | /// static SNMPV1_REQ: &[u8] = include_bytes!("../assets/snmpv1_req.bin"); 575 | /// 576 | /// # fn main() { 577 | /// match parse_snmp_v1(&SNMPV1_REQ) { 578 | /// Ok((_, ref r)) => { 579 | /// assert!(r.version == 0); 580 | /// assert!(r.community == String::from("public")); 581 | /// assert!(r.vars_iter().count() == 1); 582 | /// }, 583 | /// Err(e) => panic!("{}", e), 584 | /// } 585 | /// # } 586 | /// ``` 587 | pub fn parse_snmp_v1(bytes: &[u8]) -> IResult<&[u8], SnmpMessage, SnmpError> { 588 | Sequence::from_der_and_then(bytes, |i| { 589 | let (i, version) = u32::from_ber(i).map_err(Err::convert)?; 590 | if version != 0 { 591 | return Err(Err::Error(SnmpError::InvalidVersion)); 592 | } 593 | let (i, community) = parse_ber_octetstring_as_str(i).map_err(Err::convert)?; 594 | let (i, pdu) = parse_snmp_v1_pdu(i)?; 595 | let msg = SnmpMessage { 596 | version, 597 | community: community.to_string(), 598 | pdu, 599 | }; 600 | Ok((i, msg)) 601 | }) 602 | //.map_err(Err::convert) 603 | } 604 | 605 | pub(crate) fn parse_snmp_v1_pdu(i: &[u8]) -> IResult<&[u8], SnmpPdu, SnmpError> { 606 | match Header::from_ber(i) { 607 | Ok((rem, hdr)) => { 608 | match PduType(hdr.tag().0) { 609 | PduType::GetRequest 610 | | PduType::GetNextRequest 611 | | PduType::Response 612 | | PduType::SetRequest => parse_snmp_v1_generic_pdu(rem, PduType(hdr.tag().0)), 613 | PduType::TrapV1 => parse_snmp_v1_trap_pdu(rem), 614 | _ => Err(Err::Error(SnmpError::InvalidPduType)), 615 | // _ => { return IResult::Error(error_code!(ErrorKind::Custom(SnmpError::InvalidPdu))); }, 616 | } 617 | } 618 | Err(e) => Err(Err::convert(e)), 619 | } 620 | } 621 | 622 | /// Parse a SNMP v2c message. 623 | /// 624 | /// Top-level message 625 | /// 626 | ///
627 | /// Message ::=
628 | ///         SEQUENCE {
629 | ///             version
630 | ///                 INTEGER {
631 | ///                     version(1)  -- modified from RFC 1157
632 | ///                 },
633 | ///
634 | ///             community           -- community name
635 | ///                 OCTET STRING,
636 | ///
637 | ///             data                -- PDUs as defined in [4]
638 | ///                 ANY
639 | ///         }
640 | /// 
641 | pub fn parse_snmp_v2c(bytes: &[u8]) -> IResult<&[u8], SnmpMessage, SnmpError> { 642 | Sequence::from_der_and_then(bytes, |i| { 643 | let (i, version) = u32::from_ber(i).map_err(Err::convert)?; 644 | if version != 1 { 645 | return Err(Err::Error(SnmpError::InvalidVersion)); 646 | } 647 | let (i, community) = parse_ber_octetstring_as_str(i).map_err(Err::convert)?; 648 | let (i, pdu) = parse_snmp_v2c_pdu(i)?; 649 | let msg = SnmpMessage { 650 | version, 651 | community: community.to_string(), 652 | pdu, 653 | }; 654 | Ok((i, msg)) 655 | }) 656 | } 657 | 658 | pub(crate) fn parse_snmp_v2c_pdu(i: &[u8]) -> IResult<&[u8], SnmpPdu, SnmpError> { 659 | match Header::from_ber(i) { 660 | Ok((rem, hdr)) => { 661 | match PduType(hdr.tag().0) { 662 | PduType::GetRequest 663 | | PduType::GetNextRequest 664 | | PduType::Response 665 | | PduType::SetRequest 666 | | PduType::InformRequest 667 | | PduType::TrapV2 668 | | PduType::Report => parse_snmp_v1_generic_pdu(rem, PduType(hdr.tag().0)), 669 | PduType::GetBulkRequest => parse_snmp_v1_bulk_pdu(rem), 670 | PduType::TrapV1 => parse_snmp_v1_trap_pdu(rem), 671 | _ => Err(Err::Error(SnmpError::InvalidPduType)), 672 | // _ => { return IResult::Error(error_code!(ErrorKind::Custom(SnmpError::InvalidPdu))); }, 673 | } 674 | } 675 | Err(e) => Err(Err::convert(e)), 676 | } 677 | } 678 | -------------------------------------------------------------------------------- /src/snmpv3.rs: -------------------------------------------------------------------------------- 1 | //! SNMPv3 Parser 2 | //! 3 | //! SNMPv3 is defined in the following RFCs: 4 | //! - [RFC2570](https://tools.ietf.org/html/rfc2570): Introduction to SNMP v3 5 | //! - [RFC3412](https://tools.ietf.org/html/rfc3412): Message Processing and Dispatching for the 6 | //! Simple Network Management Protocol (SNMP) 7 | //! 8 | //! See also: 9 | //! - [RFC2578](https://tools.ietf.org/html/rfc2578): Structure of Management Information Version 2 (SMIv2) 10 | 11 | use asn1_rs::{Error, FromBer, Sequence}; 12 | use nom::combinator::{map, map_res}; 13 | use nom::{Err, IResult}; 14 | use std::fmt; 15 | 16 | use crate::error::SnmpError; 17 | use crate::snmp::{parse_snmp_v2c_pdu, SnmpPdu}; 18 | pub use crate::usm::{parse_usm_security_parameters, UsmSecurityParameters}; 19 | 20 | #[derive(Clone, Copy, Eq, PartialEq)] 21 | pub struct SecurityModel(pub u32); 22 | 23 | #[allow(non_upper_case_globals)] 24 | impl SecurityModel { 25 | pub const SnmpV1: SecurityModel = SecurityModel(1); 26 | pub const SnmpV2c: SecurityModel = SecurityModel(2); 27 | pub const USM: SecurityModel = SecurityModel(3); 28 | } 29 | 30 | impl fmt::Debug for SecurityModel { 31 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 32 | match self.0 { 33 | 1 => f.write_str("SnmpV1"), 34 | 2 => f.write_str("SnmpV2c"), 35 | 3 => f.write_str("USM"), 36 | n => f.debug_tuple("SecurityModel").field(&n).finish(), 37 | } 38 | } 39 | } 40 | 41 | impl<'a> FromBer<'a> for SecurityModel { 42 | fn from_ber(bytes: &'a [u8]) -> asn1_rs::ParseResult<'a, Self> { 43 | map(u32::from_ber, SecurityModel)(bytes) 44 | } 45 | } 46 | 47 | #[derive(Debug, PartialEq)] 48 | #[allow(clippy::upper_case_acronyms)] 49 | pub enum SecurityParameters<'a> { 50 | Raw(&'a [u8]), 51 | USM(UsmSecurityParameters<'a>), 52 | } 53 | 54 | /// An SNMPv3 message 55 | /// 56 | /// # Examples 57 | /// 58 | /// ```rust 59 | /// use snmp_parser::{ScopedPduData, SecurityModel, SnmpV3Message}; 60 | /// use snmp_parser::asn1_rs::FromBer; 61 | /// 62 | /// static SNMPV3_REQ: &[u8] = include_bytes!("../assets/snmpv3_req.bin"); 63 | /// 64 | /// # fn main() { 65 | /// match SnmpV3Message::from_ber(&SNMPV3_REQ) { 66 | /// Ok((_, ref r)) => { 67 | /// assert!(r.version == 3); 68 | /// assert!(r.header_data.msg_security_model == SecurityModel::USM); 69 | /// match r.data { 70 | /// ScopedPduData::Plaintext(ref _pdu) => { }, 71 | /// ScopedPduData::Encrypted(_) => (), 72 | /// } 73 | /// }, 74 | /// Err(e) => panic!("{}", e), 75 | /// } 76 | /// # } 77 | /// ``` 78 | #[derive(Debug, PartialEq)] 79 | pub struct SnmpV3Message<'a> { 80 | /// Version, as raw-encoded: 3 for SNMPv3 81 | pub version: u32, 82 | pub header_data: HeaderData, 83 | pub security_params: SecurityParameters<'a>, 84 | pub data: ScopedPduData<'a>, 85 | } 86 | 87 | impl<'a> FromBer<'a, SnmpError> for SnmpV3Message<'a> { 88 | fn from_ber(bytes: &'a [u8]) -> asn1_rs::ParseResult<'a, Self, SnmpError> { 89 | Sequence::from_der_and_then(bytes, |i| { 90 | let (i, version) = u32::from_ber(i).map_err(Err::convert)?; 91 | let (i, header_data) = parse_snmp_v3_headerdata(i)?; 92 | let (i, secp) = map_res(<&[u8]>::from_ber, |x| parse_secp(x, &header_data))(i) 93 | .map_err(Err::convert)?; 94 | let (i, data) = parse_snmp_v3_data(i, &header_data)?; 95 | let msg = SnmpV3Message { 96 | version, 97 | header_data, 98 | security_params: secp, 99 | data, 100 | }; 101 | Ok((i, msg)) 102 | }) 103 | } 104 | } 105 | 106 | #[derive(Clone, Copy, Debug, PartialEq)] 107 | pub struct HeaderData { 108 | pub msg_id: u32, 109 | pub msg_max_size: u32, 110 | pub msg_flags: u8, 111 | pub msg_security_model: SecurityModel, 112 | } 113 | 114 | impl HeaderData { 115 | pub fn is_authenticated(&self) -> bool { 116 | self.msg_flags & 0b001 != 0 117 | } 118 | 119 | pub fn is_encrypted(&self) -> bool { 120 | self.msg_flags & 0b010 != 0 121 | } 122 | 123 | pub fn is_reportable(&self) -> bool { 124 | self.msg_flags & 0b100 != 0 125 | } 126 | } 127 | 128 | impl<'a> FromBer<'a> for HeaderData { 129 | fn from_ber(bytes: &'a [u8]) -> asn1_rs::ParseResult<'a, Self> { 130 | Sequence::from_ber_and_then(bytes, |i| { 131 | let (i, msg_id) = u32::from_ber(i)?; 132 | let (i, msg_max_size) = u32::from_ber(i)?; 133 | let (i, b) = <&[u8]>::from_ber(i)?; 134 | let msg_flags = if b.len() == 1 { 135 | b[0] 136 | } else { 137 | return Err(Err::Error(Error::BerValueError)); 138 | }; 139 | let (i, msg_security_model) = map(u32::from_ber, SecurityModel)(i)?; 140 | let hdr = HeaderData { 141 | msg_id, 142 | msg_max_size, 143 | msg_flags, 144 | msg_security_model, 145 | }; 146 | Ok((i, hdr)) 147 | }) 148 | } 149 | } 150 | 151 | #[derive(Debug, PartialEq)] 152 | pub enum ScopedPduData<'a> { 153 | Plaintext(ScopedPdu<'a>), 154 | Encrypted(&'a [u8]), 155 | } 156 | 157 | #[derive(Debug, PartialEq)] 158 | pub struct ScopedPdu<'a> { 159 | pub ctx_engine_id: &'a [u8], 160 | pub ctx_engine_name: &'a [u8], 161 | /// ANY -- e.g., PDUs as defined in [RFC3416](https://tools.ietf.org/html/rfc3416) 162 | pub data: SnmpPdu<'a>, 163 | } 164 | 165 | pub(crate) fn parse_snmp_v3_data<'a>( 166 | i: &'a [u8], 167 | hdr: &HeaderData, 168 | ) -> IResult<&'a [u8], ScopedPduData<'a>, SnmpError> { 169 | if hdr.is_encrypted() { 170 | map(<&[u8]>::from_ber, ScopedPduData::Encrypted)(i).map_err(Err::convert) 171 | } else { 172 | parse_snmp_v3_plaintext_pdu(i) 173 | } 174 | } 175 | 176 | pub(crate) fn parse_secp<'a>( 177 | i: &'a [u8], 178 | hdr: &HeaderData, 179 | ) -> Result, SnmpError> { 180 | match hdr.msg_security_model { 181 | SecurityModel::USM => match parse_usm_security_parameters(i) { 182 | Ok((_, usm)) => Ok(SecurityParameters::USM(usm)), 183 | _ => Err(SnmpError::InvalidSecurityModel), 184 | }, 185 | _ => Ok(SecurityParameters::Raw(i)), 186 | } 187 | } 188 | 189 | /// Parse an SNMPv3 top-level message 190 | /// 191 | /// Example: 192 | /// 193 | /// ```rust 194 | /// use snmp_parser::{parse_snmp_v3,ScopedPduData,SecurityModel}; 195 | /// 196 | /// static SNMPV3_REQ: &[u8] = include_bytes!("../assets/snmpv3_req.bin"); 197 | /// 198 | /// # fn main() { 199 | /// match parse_snmp_v3(&SNMPV3_REQ) { 200 | /// Ok((_, ref r)) => { 201 | /// assert!(r.version == 3); 202 | /// assert!(r.header_data.msg_security_model == SecurityModel::USM); 203 | /// match r.data { 204 | /// ScopedPduData::Plaintext(ref _pdu) => { }, 205 | /// ScopedPduData::Encrypted(_) => (), 206 | /// } 207 | /// }, 208 | /// Err(e) => panic!("{}", e), 209 | /// } 210 | /// # } 211 | /// ``` 212 | pub fn parse_snmp_v3(bytes: &[u8]) -> IResult<&[u8], SnmpV3Message, SnmpError> { 213 | SnmpV3Message::from_ber(bytes) 214 | } 215 | 216 | #[inline] 217 | pub(crate) fn parse_snmp_v3_headerdata(i: &[u8]) -> IResult<&[u8], HeaderData, SnmpError> { 218 | HeaderData::from_ber(i).map_err(Err::convert) 219 | } 220 | 221 | fn parse_snmp_v3_plaintext_pdu(bytes: &[u8]) -> IResult<&[u8], ScopedPduData, SnmpError> { 222 | Sequence::from_der_and_then(bytes, |i| { 223 | let (i, ctx_engine_id) = <&[u8]>::from_ber(i).map_err(Err::convert)?; 224 | let (i, ctx_engine_name) = <&[u8]>::from_ber(i).map_err(Err::convert)?; 225 | let (i, data) = parse_snmp_v2c_pdu(i)?; 226 | let pdu = ScopedPdu { 227 | ctx_engine_id, 228 | ctx_engine_name, 229 | data, 230 | }; 231 | Ok((i, ScopedPduData::Plaintext(pdu))) 232 | }) 233 | } 234 | -------------------------------------------------------------------------------- /src/usm.rs: -------------------------------------------------------------------------------- 1 | //! RFC2274 - User-based Security Model (USM) for version 3 of the Simple Network Management Protocol (SNMPv3) 2 | 3 | use crate::parse_ber_octetstring_as_str; 4 | use asn1_rs::{Error, FromBer, Sequence}; 5 | use nom::IResult; 6 | 7 | #[derive(Debug, PartialEq)] 8 | pub struct UsmSecurityParameters<'a> { 9 | pub msg_authoritative_engine_id: &'a [u8], 10 | pub msg_authoritative_engine_boots: u32, 11 | pub msg_authoritative_engine_time: u32, 12 | pub msg_user_name: String, 13 | pub msg_authentication_parameters: &'a [u8], 14 | pub msg_privacy_parameters: &'a [u8], 15 | } 16 | 17 | pub fn parse_usm_security_parameters(bytes: &[u8]) -> IResult<&[u8], UsmSecurityParameters, Error> { 18 | Sequence::from_der_and_then(bytes, |i| { 19 | let (i, msg_authoritative_engine_id) = <&[u8]>::from_ber(i)?; 20 | let (i, msg_authoritative_engine_boots) = u32::from_ber(i)?; 21 | let (i, msg_authoritative_engine_time) = u32::from_ber(i)?; 22 | let (i, msg_user_name) = parse_ber_octetstring_as_str(i)?; 23 | let (i, msg_authentication_parameters) = <&[u8]>::from_ber(i)?; 24 | let (i, msg_privacy_parameters) = <&[u8]>::from_ber(i)?; 25 | let usm = UsmSecurityParameters { 26 | msg_authoritative_engine_id, 27 | msg_authoritative_engine_boots, 28 | msg_authoritative_engine_time, 29 | msg_user_name: msg_user_name.to_string(), 30 | msg_authentication_parameters, 31 | msg_privacy_parameters, 32 | }; 33 | Ok((i, usm)) 34 | }) 35 | } 36 | -------------------------------------------------------------------------------- /tests/v1.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate hex_literal; 3 | extern crate nom; 4 | extern crate snmp_parser; 5 | 6 | use snmp_parser::*; 7 | use std::net::Ipv4Addr; 8 | 9 | const SNMPV1_RESPONSE: &[u8] = &hex!( 10 | " 11 | 30 82 00 59 02 01 00 04 06 70 75 62 6c 69 63 a2 12 | 82 00 4a 02 02 26 72 02 01 00 02 01 00 30 82 00 13 | 3c 30 82 00 10 06 0b 2b 06 01 02 01 19 03 02 01 14 | 05 01 02 01 03 30 82 00 10 06 0b 2b 06 01 02 01 15 | 19 03 05 01 01 01 02 01 03 30 82 00 10 06 0b 2b 16 | 06 01 02 01 19 03 05 01 02 01 04 01 a0 17 | " 18 | ); 19 | 20 | #[test] 21 | fn test_snmp_v1_response() { 22 | let bytes: &[u8] = SNMPV1_RESPONSE; 23 | match parse_snmp_v1(bytes) { 24 | Ok((rem, pdu)) => { 25 | // println!("pdu: {:?}", pdu); 26 | assert!(rem.is_empty()); 27 | assert_eq!(pdu.version, 0); 28 | assert_eq!(&pdu.community as &str, "public"); 29 | assert_eq!(pdu.pdu_type(), PduType::Response); 30 | } 31 | e => panic!("Error: {:?}", e), 32 | } 33 | } 34 | 35 | static SNMPV1_REQ: &[u8] = include_bytes!("../assets/snmpv1_req.bin"); 36 | 37 | #[test] 38 | fn test_snmp_v1_req() { 39 | let bytes = SNMPV1_REQ; 40 | let expected = SnmpMessage { 41 | version: 0, 42 | community: String::from("public"), 43 | pdu: SnmpPdu::Generic(SnmpGenericPdu { 44 | pdu_type: PduType::GetRequest, 45 | req_id: 38, 46 | err: ErrorStatus(0), 47 | err_index: 0, 48 | var: vec![SnmpVariable { 49 | oid: Oid::from(&[1, 3, 6, 1, 2, 1, 1, 2, 0]).unwrap(), 50 | val: VarBindValue::Unspecified, 51 | }], 52 | }), 53 | }; 54 | let (rem, r) = parse_snmp_v1(bytes).expect("parsing failed"); 55 | // debug!("r: {:?}",r); 56 | eprintln!( 57 | "SNMP: v={}, c={:?}, pdu_type={:?}", 58 | r.version, 59 | r.community, 60 | r.pdu_type() 61 | ); 62 | // debug!("PDU: type={}, {:?}", pdu_type, pdu_res); 63 | for v in r.vars_iter() { 64 | eprintln!("v: {:?}", v); 65 | } 66 | assert!(rem.is_empty()); 67 | assert_eq!(r, expected); 68 | } 69 | 70 | static SNMPV1_TRAP_COLDSTART: &[u8] = include_bytes!("../assets/snmpv1_trap_coldstart.bin"); 71 | 72 | #[test] 73 | fn test_snmp_v1_trap_coldstart() { 74 | let bytes = SNMPV1_TRAP_COLDSTART; 75 | let (rem, pdu) = parse_snmp_v1(bytes).expect("parsing failed"); 76 | // println!("pdu: {:?}", pdu); 77 | assert!(rem.is_empty()); 78 | assert_eq!(pdu.version, 0); 79 | assert_eq!(&pdu.community as &str, "public"); 80 | assert_eq!(pdu.pdu_type(), PduType::TrapV1); 81 | match pdu.pdu { 82 | SnmpPdu::TrapV1(trap) => { 83 | assert_eq!( 84 | trap.enterprise, 85 | Oid::from(&[1, 3, 6, 1, 4, 1, 4, 1, 2, 21]).unwrap() 86 | ); 87 | assert_eq!( 88 | trap.agent_addr, 89 | NetworkAddress::IPv4(Ipv4Addr::new(127, 0, 0, 1)) 90 | ); 91 | } 92 | _ => panic!("unexpected pdu type"), 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /tests/v2c.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate pretty_assertions; 3 | extern crate nom; 4 | extern crate snmp_parser; 5 | 6 | use snmp_parser::*; 7 | 8 | static SNMPV2_GET: &[u8] = include_bytes!("../assets/snmpv2c-get-response.bin"); 9 | 10 | #[test] 11 | fn test_snmp_v2_get() { 12 | let bytes = SNMPV2_GET; 13 | let expected = SnmpMessage { 14 | version: 1, 15 | community: String::from("public"), 16 | pdu: SnmpPdu::Generic(SnmpGenericPdu { 17 | pdu_type: PduType::Response, 18 | req_id: 97083662, 19 | err: ErrorStatus(0), 20 | err_index: 0, 21 | var: vec![ 22 | SnmpVariable { 23 | oid: Oid::from(&[1, 3, 6, 1, 2, 1, 25, 1, 1, 0]).unwrap(), 24 | val: VarBindValue::Value(ObjectSyntax::TimeTicks(970069)), 25 | }, 26 | SnmpVariable { 27 | oid: Oid::from(&[1, 3, 6, 1, 2, 1, 25, 1, 5, 0]).unwrap(), 28 | val: VarBindValue::Value(ObjectSyntax::Gauge32(3)), 29 | }, 30 | SnmpVariable { 31 | oid: Oid::from(&[1, 3, 6, 1, 2, 1, 25, 1, 5, 1]).unwrap(), 32 | val: VarBindValue::NoSuchInstance, 33 | }, 34 | ], 35 | }), 36 | }; 37 | let (rem, r) = parse_snmp_v2c(bytes).expect("parsing failed"); 38 | 39 | // debug!("r: {:?}",r); 40 | eprintln!( 41 | "SNMP: v={}, c={:?}, pdu_type={:?}", 42 | r.version, 43 | r.community, 44 | r.pdu_type() 45 | ); 46 | // debug!("PDU: type={}, {:?}", pdu_type, pdu_res); 47 | for v in r.vars_iter() { 48 | eprintln!("v: {:?}", v); 49 | } 50 | assert!(rem.is_empty()); 51 | assert_eq!(r, expected); 52 | } 53 | -------------------------------------------------------------------------------- /tests/v3.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate pretty_assertions; 3 | 4 | extern crate nom; 5 | extern crate snmp_parser; 6 | 7 | use snmp_parser::*; 8 | 9 | static SNMPV3_REQ: &[u8] = include_bytes!("../assets/snmpv3_req.bin"); 10 | 11 | #[test] 12 | fn test_snmp_v3_req() { 13 | let bytes = SNMPV3_REQ; 14 | let sp = SecurityParameters::USM(UsmSecurityParameters { 15 | msg_authoritative_engine_id: b"", 16 | msg_authoritative_engine_boots: 0, 17 | msg_authoritative_engine_time: 0, 18 | msg_user_name: String::from(""), 19 | msg_authentication_parameters: b"", 20 | msg_privacy_parameters: b"", 21 | }); 22 | let cei = [ 23 | 0x80, 0x00, 0x1f, 0x88, 0x80, 0x59, 0xdc, 0x48, 0x61, 0x45, 0xa2, 0x63, 0x22, 24 | ]; 25 | let data = SnmpPdu::Generic(SnmpGenericPdu { 26 | pdu_type: PduType::GetRequest, 27 | req_id: 2098071598, 28 | err: ErrorStatus::NoError, 29 | err_index: 0, 30 | var: vec![], 31 | }); 32 | let expected = SnmpV3Message { 33 | version: 3, 34 | header_data: HeaderData { 35 | msg_id: 821490644, 36 | msg_max_size: 65507, 37 | msg_flags: 4, 38 | msg_security_model: SecurityModel::USM, 39 | }, 40 | security_params: sp, 41 | data: ScopedPduData::Plaintext(ScopedPdu { 42 | ctx_engine_id: &cei, 43 | ctx_engine_name: b"", 44 | data, 45 | }), 46 | }; 47 | let (rem, res) = parse_snmp_v3(bytes).expect("parsing failed"); 48 | // eprintln!("{:?}", res); 49 | assert!(rem.is_empty()); 50 | assert_eq!(res, expected); 51 | } 52 | 53 | #[test] 54 | fn test_snmp_v3_req_encrypted() { 55 | let bytes = include_bytes!("../assets/snmpv3_req_encrypted.bin"); 56 | let (rem, msg) = parse_snmp_v3(bytes).expect("parsing failed"); 57 | // eprintln!("{:?}", res); 58 | assert!(rem.is_empty()); 59 | assert_eq!(msg.version, 3); 60 | assert_eq!(msg.header_data.msg_security_model, SecurityModel::USM); 61 | } 62 | 63 | #[test] 64 | fn test_snmp_v3_report() { 65 | let bytes = include_bytes!("../assets/snmpv3-report.bin"); 66 | let (rem, msg) = parse_snmp_v3(bytes).expect("parsing failed"); 67 | // eprintln!("{:?}", res); 68 | assert!(rem.is_empty()); 69 | assert_eq!(msg.version, 3); 70 | assert_eq!(msg.header_data.msg_security_model, SecurityModel::USM); 71 | } 72 | 73 | #[test] 74 | fn test_snmp_v3_generic() { 75 | let bytes = SNMPV3_REQ; 76 | let res = parse_snmp_generic_message(bytes); 77 | // eprintln!("{:?}", res); 78 | let (rem, m) = res.expect("parse_snmp_generic_message"); 79 | assert!(rem.is_empty()); 80 | if let SnmpGenericMessage::V3(msg) = m { 81 | assert_eq!(msg.version, 3); 82 | assert_eq!(msg.header_data.msg_security_model, SecurityModel::USM); 83 | } else { 84 | panic!("unexpected PDU type"); 85 | } 86 | } 87 | --------------------------------------------------------------------------------