├── .coveragerc ├── .editorconfig ├── .flake8 ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml └── workflows │ └── main.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .readthedocs.yaml ├── CONTRIBUTING.md ├── LICENSE ├── Procfile ├── README.md ├── contrib └── oxidized │ ├── cfgchanged.sh │ └── validate_config.sh ├── docs ├── .gitignore ├── Makefile ├── make.bat └── source │ ├── check.rst │ ├── checks.j2 │ ├── checks_index.j2 │ ├── cli.rst │ ├── conf.py │ ├── contributing.rst │ ├── index.rst │ ├── integrations │ ├── index.rst │ └── oxidized.rst │ ├── nos │ ├── cisco_ios.rst │ ├── cisco_nxos.rst │ └── index.rst │ └── usage.rst ├── mypy.ini ├── netlint ├── __init__.py ├── __main__.py ├── checks │ ├── __init__.py │ ├── checker.py │ ├── cisco_ios │ │ └── __init__.py │ ├── cisco_nxos │ │ ├── __init__.py │ │ └── utils.py │ ├── constants.py │ ├── types.py │ ├── utils.py │ └── various │ │ └── __init__.py ├── cli │ ├── __init__.py │ ├── main.py │ ├── types.py │ └── utils.py └── weblint │ ├── __init__.py │ └── templates │ └── base.j2 ├── poetry.lock ├── pyproject.toml └── tests ├── __init__.py ├── configurations ├── check_default_snmp_communities_faulty-0.conf ├── check_default_snmp_communities_good-0.conf ├── cisco_ios │ ├── check_console_password_faulty-0.conf │ ├── check_console_password_good-0.conf │ ├── check_ip_http_server_faulty-0.conf │ ├── check_ip_http_server_good-0.conf │ ├── check_password_hash_strength_faulty-0.conf │ ├── check_password_hash_strength_good-0.conf │ ├── check_plaintext_passwords_faulty-0.conf │ ├── check_plaintext_passwords_good-0.conf │ ├── check_switchport_access_config_faulty-0.conf │ ├── check_switchport_access_config_good-0.conf │ ├── check_switchport_trunk_config_faulty-0.conf │ ├── check_switchport_trunk_config_good-0.conf │ ├── check_unused_access_lists_faulty-0.conf │ ├── check_unused_access_lists_faulty-1.conf │ ├── check_unused_access_lists_good-0.conf │ ├── check_used_but_unconfigured_access_lists_faulty-0.conf │ ├── check_used_but_unconfigured_access_lists_faulty-1.conf │ ├── check_used_but_unconfigured_access_lists_faulty-2.conf │ ├── check_used_but_unconfigured_access_lists_good-0.conf │ ├── faulty.conf │ └── good.conf └── cisco_nxos │ ├── check_bogus_as_faulty-0.conf │ ├── check_bogus_as_good-0.conf │ ├── check_fex_feature_enabled_and_used_faulty-0.conf │ ├── check_fex_feature_enabled_and_used_good-0.conf │ ├── check_fex_feature_set_installed_but_not_enabled_faulty-0.conf │ ├── check_fex_feature_set_installed_but_not_enabled_good-0.conf │ ├── check_fex_without_interface_faulty-0.conf │ ├── check_fex_without_interface_faulty-1.conf │ ├── check_fex_without_interface_good-0.conf │ ├── check_lacp_feature_enabled_and_used_faulty-0.conf │ ├── check_lacp_feature_enabled_and_used_faulty-1.conf │ ├── check_lacp_feature_enabled_and_used_good-0.conf │ ├── check_lacp_feature_enabled_and_used_good-1.conf │ ├── check_password_strength_faulty-0.conf │ ├── check_password_strength_good-0.conf │ ├── check_routing_protocol_enabled_and_used_faulty-0.conf │ ├── check_routing_protocol_enabled_and_used_good-0.conf │ ├── check_switchport_mode_fex_fabric_faulty-0.conf │ ├── check_switchport_mode_fex_fabric_good-0.conf │ ├── check_telnet_enabled_faulty-0.conf │ ├── check_telnet_enabled_good-0.conf │ ├── check_vpc_feature_enabled_and_used_faulty-0.conf │ ├── check_vpc_feature_enabled_and_used_good-0.conf │ ├── check_vpc_feature_enabled_and_used_good-1.conf │ ├── faulty.conf │ └── good.conf ├── test_checkers.py ├── test_cli.py └── utils.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | source = netlint -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.py] 2 | indent_style = space 3 | indent_size = 4 -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 88 3 | ignore = D107, W503 4 | exclude = .git,__pycache__,docs/source/conf.py,tests -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | The CLI command or code you ran that produced the bug. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Output** 20 | The output you got when running into the bug. 21 | 22 | **Additional context** 23 | Add any other context about the problem here. 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: . 5 | schedule: 6 | interval: "daily" 7 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: build 3 | on: [push, pull_request] 4 | jobs: 5 | std_tests: 6 | runs-on: ubuntu-latest 7 | strategy: 8 | max-parallel: 4 9 | matrix: 10 | python-version: [3.6, 3.7, 3.8, 3.9] 11 | 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v2 15 | 16 | - name: Setup Python ${{ matrix.python-version }} 17 | uses: actions/setup-python@v2 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | 21 | - name: Install dependencies 22 | run: | 23 | curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python - 24 | $HOME/.poetry/bin/poetry install 25 | 26 | - name: Run black 27 | run: | 28 | $HOME/.poetry/bin/poetry run black --check . 29 | 30 | - name: Run linter 31 | run: | 32 | $HOME/.poetry/bin/poetry run flake8 33 | 34 | - name: Run type checker 35 | run: | 36 | $HOME/.poetry/bin/poetry run mypy -p netlint 37 | 38 | - name: Run Tests 39 | run: | 40 | $HOME/.poetry/bin/poetry run coverage run -m pytest 41 | build_docs: 42 | needs: std_tests 43 | runs-on: ubuntu-latest 44 | 45 | strategy: 46 | matrix: 47 | python-version: [3.9] 48 | 49 | steps: 50 | - name: Checkout repository 51 | uses: actions/checkout@v2 52 | 53 | - name: Setup Python ${{ matrix.python-version }} 54 | uses: actions/setup-python@v2 55 | with: 56 | python-version: ${{ matrix.python-version }} 57 | 58 | - name: Install dependencies 59 | run: | 60 | curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python - 61 | $HOME/.poetry/bin/poetry install 62 | 63 | - name: Make docs 64 | run: | 65 | cd docs 66 | $HOME/.poetry/bin/poetry run make html 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | .mypy_cache/ 3 | __pycache__/ 4 | .coverage 5 | dist/ 6 | 7 | # Editors 8 | .idea/ 9 | .vscode/ 10 | 11 | # Output 12 | *.csv 13 | /*.json -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v2.3.0 4 | hooks: 5 | - id: check-ast 6 | - id: check-yaml 7 | - repo: https://github.com/psf/black 8 | rev: 20.8b1 9 | hooks: 10 | - id: black 11 | - repo: https://github.com/pycqa/flake8 12 | rev: 3.9.0 13 | hooks: 14 | - id: flake8 -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | 2 | version: 2 3 | 4 | sphinx: 5 | configuration: docs/source/conf.py 6 | 7 | python: 8 | version: 3. 9 | install: 10 | - method: pip 11 | path: . 12 | extra_requirements: 13 | - docs 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thanks for considering a contribution! The following are multiple 4 | ways you could go about your contribution for which you can find 5 | further explanation further below: 6 | 7 | - Adding new checks 8 | - Add documentation or tutorials 9 | - Reporting bugs 10 | 11 | When contributing any code make sure to run 12 | - flake8 13 | - mypy 14 | - black 15 | 16 | on the code and ensure the documentation builds and the tests pass. 17 | A `.pre-commit-config.yaml` configuration file is available if you 18 | want to use git pre-commit hooks. 19 | 20 | ## Setup 21 | 22 | Before you can contribute any code, you will need to set up your 23 | development environment properly by following the instructions 24 | below. 25 | 26 | 1. **Fork Netlint**. In GitHub, fork the Netlint repository to a new 27 | repository under your name. This will allow you to propose changes 28 | to the main Netlint repository through a pull request. For more 29 | information on how to do this, [refer to GitHub's documentation on how to fork a repository](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo). 30 | 2. **Clone Netlint Fork**. Clone your fork of the Netlint repository 31 | into your development environment. [Refer to GitHub's documentation on how to clone a repository](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository). 32 | 3. **Install Poetry**. Netlint utilizes [Poetry](https://python-poetry.org/) 33 | for Python packaging and dependency management. In order to contribute 34 | code, you will need to follow [Poetry's installation instructions](https://python-poetry.org/docs/#installation) 35 | for your operating system of choice. 36 | 4. **Install Dependencies with Poetry**. Use the `poetry install` command 37 | within the clone of your fork of the Netlint repository to install 38 | Netlint's dependencies within your development environment. 39 | 40 | Your development environment is now set up to contribute to Netlint! 41 | 42 | ## Adding new checks 43 | 44 | Right now the main thing that is missing is the implementation of 45 | various configuration checks. A good check must have the following 46 | properties: 47 | 48 | ### Independence from state 49 | 50 | A check has to work on just the textual configuration of the device. 51 | It may not depend on any state such as the operative status of an 52 | interface or the up/down status of a routing protocol neighbor. 53 | 54 | ### Generality 55 | 56 | A check must always be applicable to all of its assigned network 57 | operating systems (NOSes) regardless the context. 58 | 59 | ### Usefulness 60 | 61 | A check must always fulfill any of the following use cases: 62 | 63 | - Indicate redundant or unused configuration such as a feature that 64 | is enabled but never used or an access list that is configured but 65 | never applied 66 | - Indicate a security issue such as leaving telnet enabled 67 | 68 | ## Write documentation or tutorials 69 | 70 | The latest documentation is always present 71 | [here](https://netlint.readthedocs.io). Take a look and see if you can 72 | find any typos, logical issues or unclear passages - contributions of 73 | any size are very welcome. 74 | 75 | ## Reporting bugs 76 | 77 | You can report issues 78 | [here](https://github.com/Kircheneer/netlint/issues/new). -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: uvicorn netlint.weblint:app --host=0.0.0.0 --port=${PORT:-5000} -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **Note: Still in active development and potentially subject to major changes - keep this in mind when using this.** 2 | 3 | # Netlint 4 | 5 | ![Build workflow](https://github.com/Kircheneer/netlint/actions/workflows/main.yml/badge.svg) 6 | [![Documentation Status](https://readthedocs.org/projects/netlint/badge/?version=latest)](https://netlint.readthedocs.io/en/latest/?badge=latest) 7 | 8 | Performs static analysis on network device configuration files. 9 | 10 | Linters have long since been a standard way of assessing code quality 11 | in the software development world. This project aims to take that idea 12 | and apply it to the world of network device configuration files. 13 | 14 | Find the latest copy of the documentation [here](https://netlint.readthedocs.io). 15 | 16 | Try out the web version [here](https://netlint.herokuapp.com) (your 17 | configuration file input is not saved or shared with anyone). 18 | 19 | ## Example usage 20 | 21 | Below is an example of how to use this based on one of the faulty test 22 | configurations (executed from the project root): 23 | 24 | ``` 25 | $ netlint -i tests/configurations/cisco_ios/faulty.conf 26 | IOS101 Plaintext user passwords in configuration. 27 | -> username test password ing 28 | IOS102 HTTP server not disabled 29 | -> ip http server 30 | -> ip http secure-server 31 | IOS103 Console line unauthenticated 32 | -> line con 0 33 | 34 | ``` 35 | 36 | ## Scope 37 | 38 | Some potential use cases of `netlint` are the following: 39 | 40 | - Linting network device configurations generated in 41 | CI/CD automation pipelines 42 | - Assistance when building out new configurations for 43 | both traditional and automated deployment 44 | - Basic security auditing of configuration files 45 | - Validating configuration hygiene such as references to 46 | undefined configuration items (e.g. ACLs) 47 | 48 | The following things are explicitly not in scope of `netlint`: 49 | 50 | - Correlation of configurations (for example answering the question of 51 | whether two BGP neighbors might come up or not) 52 | - Validation of syntactic configuration correctness 53 | - Analysis of network device state that requires connections to the 54 | devices such as interface error counters (`netlint` does however 55 | support getting the configuration from the devices with `netlint get`) 56 | 57 | ## Installation 58 | 59 | There are multiple ways of installing this software. 60 | 61 | A package is available on [PyPI](https://pypi.org/project/netlint/), 62 | therefore you can simply install with `pip install netlint` and 63 | then simply run `netlint`. 64 | 65 | If you prefer to install directly from 66 | GitHub, here is how you would go about that. 67 | 68 | ```bash 69 | $ git clone https://github.com/Kircheneer/netlint.git 70 | $ git checkout $TAG # Optionally checkout a specific tag 71 | $ cd netlint 72 | $ pip install . 73 | $ netlint --help 74 | Usage: netlint [OPTIONS] COMMAND [ARGS]... 75 | 76 | Lint network device configuration files. 77 | 78 | [...] 79 | ``` 80 | -------------------------------------------------------------------------------- /contrib/oxidized/cfgchanged.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Hook for oxidized to initate validation after a changed config is stored 4 | # 5 | # $OX_EVENT 6 | # $OX_NODE_NAME 7 | # $OX_NODE_IP 8 | # $OX_NODE_FROM 9 | # $OX_NODE_MSG 10 | # $OX_NODE_GROUP 11 | # $OX_NODE_MODEL 12 | # $OX_JOB_STATUS 13 | # $OX_JOB_TIME 14 | # $OX_REPO_COMMITREF 15 | # $OX_REPO_NAME 16 | 17 | Storage="data" 18 | MyPath=`dirname $0` 19 | FilePath="$MyPath/$Storage/$OX_NODE_GROUP" 20 | # Find git (makes it independent) 21 | GitCmd=`which git` 22 | 23 | # Clone the last version of the config 24 | if [ -d "$FilePath" ]; then 25 | # Pull 26 | cd "$FilePath" && $GitCmd pull 27 | else 28 | # Clone 29 | mkdir -p $FilePath 30 | $GitCmd clone "$OX_REPO_NAME" "$FilePath" 31 | fi 32 | 33 | # Now run the validator 34 | $MyPath/validate_config.sh "$MyPath/$Storage/$OX_NODE_GROUP/$OX_NODE_NAME" "$OX_NODE_MODEL" 35 | -------------------------------------------------------------------------------- /contrib/oxidized/validate_config.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Initate a config check 4 | # 5 | # arguments: filename oxidixed_modelname 6 | # 7 | 8 | ReportDir="$HOME/lint-reports" 9 | 10 | mkdir -p "$ReportDir" 11 | cfgfile=`basename $1` 12 | netlint -o "$ReportDir/$cfgfile.rpt" -i $1 13 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/source/check.rst: -------------------------------------------------------------------------------- 1 | Implementing checks 2 | =================== 3 | 4 | This section explains how to implement checks. This can be both applied 5 | to development in the core ``netlint`` repository as well as external 6 | collections of checks. 7 | 8 | Implementation 9 | -------------- 10 | 11 | The ``Checker`` class implements a decorator to decorate checks 12 | with. That decorator does two things: 13 | 14 | * Register the check with the ``Checker`` class 15 | * Append metadata from the decorator to the docstring of check 16 | 17 | In practice that might look like this:: 18 | 19 | from netlint.checks.checker import Checker, CheckResult 20 | 21 | @Checker.register(apply_to=["NOS_A", "NOS_B"], name="NOS_A101, tags={Tag.Hygiene}) 22 | def check_example( 23 | configuration: typing.List[str] 24 | ) -> typing.Optional[CheckResult]: 25 | for line in configuration: 26 | if "bad_thing" in line: 27 | return CheckResult( 28 | text="Found bad thing in the configuration", 29 | lines=[line] 30 | ) 31 | return None 32 | 33 | Tests 34 | ----- 35 | 36 | Your new checker will automatically be registered for the basic 37 | pytest test. Put at least one configuration that does not contain 38 | the thing your are checking for at 39 | ``tests/configurations/$NOS/$CHECK_NAME_good-0.conf`` 40 | and one that does contain it at 41 | ``tests/configurations/$NOS/$CHECK_NAME_faulty-0.conf``. 42 | Feel free to add more each time incrementing the index at the end 43 | so that all files are tested against. 44 | 45 | .. NOTE:: 46 | If your check has ``apply_to`` set to more than one NOS, put 47 | the configuration files directly at ``tests/configurations``. 48 | 49 | -------------------------------------------------------------------------------- /docs/source/checks.j2: -------------------------------------------------------------------------------- 1 | {{ nos }} 2 | {{ "=" * nos|length }} 3 | 4 | All checks applying to this NOS (including ones applying to multiple). 5 | 6 | {% for check in checks|sort(attribute='name') %} 7 | {{ check.name }} 8 | {{ "-" * check.name|length }} 9 | 10 | {{ check.function_doc }} 11 | 12 | **Tags** 13 | 14 | {% for tag in check.tags|sort(attribute='name') %} 15 | * {{ tag|capitalize }} 16 | {%- endfor %} 17 | {% endfor %} -------------------------------------------------------------------------------- /docs/source/checks_index.j2: -------------------------------------------------------------------------------- 1 | Supported Checks 2 | ================ 3 | 4 | Overview of all configurations checks available by vendor. 5 | 6 | .. toctree:: 7 | :maxdepth: 1 8 | 9 | {% for nos in nos_list -%} 10 | {{ nos|lower }} 11 | {% endfor %} 12 | 13 | 14 | .. csv-table:: Amount of suported checks 15 | :header: {% for nos in checks_per_nos.keys() %}"{{ nos }}"{% if not loop.last %}, {% endif %}{% endfor %} 16 | :widths: {% for nos in checks_per_nos.keys() %}15{% if not loop.last %}, {% endif %}{% endfor %} 17 | 18 | {% for amount in checks_per_nos.values() -%}{{ amount }}{% if not loop.last %}, {% endif %}{% endfor %} 19 | -------------------------------------------------------------------------------- /docs/source/cli.rst: -------------------------------------------------------------------------------- 1 | CLI documentation 2 | ================= 3 | 4 | The following section is auto-generated from the CLI parameters in the code. 5 | 6 | .. click:: netlint.cli.main:cli 7 | :prog: netlint 8 | :nested: full -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import os 14 | import sys 15 | from pathlib import Path 16 | 17 | from jinja2 import Environment, FileSystemLoader 18 | 19 | from netlint.checks.checker import Checker 20 | 21 | sys.path.insert(0, os.path.abspath("../../")) 22 | 23 | # -- Project information ----------------------------------------------------- 24 | 25 | project = "netlint" 26 | copyright = "2021, Leo Kirchner" 27 | author = "Leo Kirchner" 28 | 29 | # The full version, including alpha/beta/rc tags 30 | release = "v0.1.2-alpha" 31 | 32 | # -- General configuration --------------------------------------------------- 33 | 34 | # Add any Sphinx extension module names here, as strings. They can be 35 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 36 | # ones. 37 | extensions = ["sphinx_rtd_theme", "sphinx.ext.autodoc", "m2r2", "sphinx_click"] 38 | 39 | # Add any paths that contain templates here, relative to this directory. 40 | templates_path = ["_templates"] 41 | 42 | # List of patterns, relative to source directory, that match files and 43 | # directories to ignore when looking for source files. 44 | # This pattern also affects html_static_path and html_extra_path. 45 | exclude_patterns = [] 46 | 47 | # -- Options for HTML output ------------------------------------------------- 48 | 49 | # The theme to use for HTML and HTML Help pages. See the documentation for 50 | # a list of builtin themes. 51 | # 52 | html_theme = "sphinx_rtd_theme" 53 | 54 | # Add any paths that contain custom static files (such as style sheets) here, 55 | # relative to this directory. They are copied after the builtin static files, 56 | # so a file named "default.css" will overwrite the builtin "default.css". 57 | html_static_path = ["_static"] 58 | 59 | source_suffix = [".rst", ".md"] 60 | 61 | # Sort autodoc members by source to keep the numbering correct. 62 | autodoc_member_order = "bysource" 63 | 64 | 65 | def build_checker_docs(app) -> None: 66 | """Automatically build documentation from the available checker functions.""" 67 | nos_dir = Path("./nos") 68 | env = Environment(loader=FileSystemLoader(".")) 69 | for nos, checks in Checker.checks.items(): 70 | nos_template_file = env.get_template("checks.j2") 71 | rendered_template = nos_template_file.render(nos=str(nos), checks=checks) 72 | 73 | with open(nos_dir / f"{str(nos).lower()}.rst", "w") as f: 74 | f.write(rendered_template) 75 | 76 | index_template_file = env.get_template("checks_index.j2") 77 | checks_per_nos = {nos: len(checks) for nos, checks in Checker.checks.items()} 78 | rendered_index = index_template_file.render( 79 | nos_list=Checker.checks.keys(), checks_per_nos=checks_per_nos 80 | ) 81 | with open(nos_dir / "index.rst", "w") as f: 82 | f.write(rendered_index) 83 | 84 | 85 | build_checker_docs(None) 86 | -------------------------------------------------------------------------------- /docs/source/contributing.rst: -------------------------------------------------------------------------------- 1 | .. mdinclude:: ../../CONTRIBUTING.md -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. mdinclude:: ../../README.md 2 | 3 | Table of Contents 4 | ----------------------------------- 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | usage 10 | cli 11 | nos/index 12 | contributing 13 | check 14 | integrations/index 15 | 16 | Indices and tables 17 | ------------------ 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | -------------------------------------------------------------------------------- /docs/source/integrations/index.rst: -------------------------------------------------------------------------------- 1 | Integrations 2 | ============ 3 | 4 | This section describes integrations with other software. 5 | 6 | .. toctree:: 7 | :maxdepth: 1 8 | 9 | oxidized -------------------------------------------------------------------------------- /docs/source/integrations/oxidized.rst: -------------------------------------------------------------------------------- 1 | Oxidized hooks 2 | ============== 3 | 4 | This document describes how to integrate `Oxidized `_ with ``netlint``. 5 | 6 | .. NOTE:: 7 | This tutorial assumes that you are using oxidized with git-based storage rather than file-based storage. 8 | 9 | Installation 10 | ------------ 11 | 12 | #. Create a folder to keep the hooks in. For the purposes of this example that shall be ``/opt/nettools/``. 13 | #. Copy ``contrib/oxidized/cfgchanged.sh`` and ``contrib/oxidized/validate_config.sh`` to said folder and make sure they 14 | are executable. 15 | 16 | Configuration 17 | ------------- 18 | 19 | #. In the oxidized config file ``.config/oxidized/config`` add the following to fire ``/opt/nettools/cfgchanged.sh`` on 20 | every config change oxidized finds in it's targets:: 21 | 22 | hooks: 23 | conf_changed: 24 | type: exec 25 | events: [post_store] 26 | cmd: '/opt/nettools/cfgchanged.sh $OX_EVENT $OX_NODE_NAME $OX_NODE_IP $OX_NODE_FROM $OX_NODE_MSG $OX_NODE_GROUP $OX_NODE_MODEL $OX_JOB_STATUS $OX_JOB_TIME $OX_REPO_COMMITREF $OX_REPO_NAME' 27 | #. Change the output folder in ``validate_config.sh`` to the folder want the linting reports in. 28 | 29 | .. DANGER:: 30 | Any old reports will be overwritten. 31 | 32 | Now whenever oxidized detects a config change, the ``/opt/nettools/cfgchanged.sh`` script is executed. 33 | It also calls the ``validate_config.sh`` script in that same folder, with two parameters: 34 | 35 | - The full name of the device config. 36 | - The device type as defined in oxidized. 37 | 38 | This leaves you with (assuming you did not alter paths): 39 | 40 | - Most recent configuration files in ``/opt/nettools/data/`` (the tree structure below depends upon the oxidized config). 41 | - Lint reports in ``$HOME/lint-reports``. 42 | -------------------------------------------------------------------------------- /docs/source/nos/cisco_ios.rst: -------------------------------------------------------------------------------- 1 | CISCO_IOS 2 | ========= 3 | 4 | All checks applying to this NOS (including ones applying to multiple). 5 | 6 | 7 | IOS101 8 | ------ 9 | 10 | Check if there are any plaintext passwords in the configuration. 11 | 12 | **Tags** 13 | 14 | 15 | * Security 16 | 17 | IOS102 18 | ------ 19 | 20 | Check if the http server is enabled. 21 | 22 | **Tags** 23 | 24 | 25 | * Opinionated 26 | * Security 27 | 28 | IOS103 29 | ------ 30 | 31 | Check for authentication on the console line. 32 | 33 | **Tags** 34 | 35 | 36 | * Opinionated 37 | * Security 38 | 39 | IOS104 40 | ------ 41 | 42 | Check if strong password hash algorithms were used. 43 | 44 | **Tags** 45 | 46 | 47 | * Security 48 | 49 | IOS105 50 | ------ 51 | 52 | Check if the switchport mode matches all config commands per interface. 53 | 54 | **Tags** 55 | 56 | 57 | * Hygiene 58 | 59 | IOS106 60 | ------ 61 | 62 | Check for any ACLs that are used but never configured. 63 | 64 | Potential usages are: 65 | 66 | * Packet filtering 67 | * Rate limiting 68 | * Route maps 69 | 70 | 71 | **Tags** 72 | 73 | 74 | * Hygiene 75 | * Security 76 | 77 | IOS107 78 | ------ 79 | 80 | Check for any ACLs that are configured but never used. 81 | 82 | Potential usages are: 83 | 84 | * Packet filtering 85 | * Rate limiting 86 | * Route maps 87 | 88 | 89 | **Tags** 90 | 91 | 92 | * Hygiene 93 | 94 | IOS108 95 | ------ 96 | 97 | Check if the switchport mode matches all config commands per interface. 98 | 99 | **Tags** 100 | 101 | 102 | * Hygiene 103 | 104 | VAR101 105 | ------ 106 | 107 | Check for presence of default SNMP community strings. 108 | 109 | **Tags** 110 | 111 | 112 | * Security 113 | -------------------------------------------------------------------------------- /docs/source/nos/cisco_nxos.rst: -------------------------------------------------------------------------------- 1 | CISCO_NXOS 2 | ========== 3 | 4 | All checks applying to this NOS (including ones applying to multiple). 5 | 6 | 7 | NXOS101 8 | ------- 9 | 10 | Check if the telnet feature is explicitly enabled. 11 | 12 | **Tags** 13 | 14 | 15 | * Opinionated 16 | * Security 17 | 18 | NXOS102 19 | ------- 20 | 21 | Check if a routing protocol is actually used - should it be enabled. 22 | 23 | **Tags** 24 | 25 | 26 | * Hygiene 27 | 28 | NXOS103 29 | ------- 30 | 31 | Check if the password strength check has been disabled. 32 | 33 | **Tags** 34 | 35 | 36 | * Opinionated 37 | * Security 38 | 39 | NXOS104 40 | ------- 41 | 42 | Check if any bogus autonomous system is used in the configuration. 43 | 44 | **Tags** 45 | 46 | 47 | * Hygiene 48 | 49 | NXOS105 50 | ------- 51 | 52 | Check if the vPC feature is actually used if it is enabled. 53 | 54 | **Tags** 55 | 56 | 57 | * Hygiene 58 | 59 | NXOS106 60 | ------- 61 | 62 | Check if the LACP feature is actually used if it is enabled. 63 | 64 | **Tags** 65 | 66 | 67 | * Hygiene 68 | 69 | NXOS107 70 | ------- 71 | 72 | Check if the fex feature-set is installed but not enabled. 73 | 74 | **Tags** 75 | 76 | 77 | * Hygiene 78 | 79 | NXOS108 80 | ------- 81 | 82 | Check if any interface in switchport mode fex-fabric has a fex-id associated. 83 | 84 | **Tags** 85 | 86 | 87 | * Hygiene 88 | 89 | NXOS109 90 | ------- 91 | 92 | Check whether an enabled fex feature is actually used. 93 | 94 | **Tags** 95 | 96 | 97 | * Hygiene 98 | 99 | NXOS110 100 | ------- 101 | 102 | Check whether every configured fex id also has an associated interface. 103 | 104 | **Tags** 105 | 106 | 107 | * Hygiene 108 | 109 | VAR101 110 | ------ 111 | 112 | Check for presence of default SNMP community strings. 113 | 114 | **Tags** 115 | 116 | 117 | * Security 118 | -------------------------------------------------------------------------------- /docs/source/nos/index.rst: -------------------------------------------------------------------------------- 1 | Supported Checks 2 | ================ 3 | 4 | Overview of all configurations checks available by vendor. 5 | 6 | .. toctree:: 7 | :maxdepth: 1 8 | 9 | cisco_ios 10 | cisco_nxos 11 | 12 | 13 | 14 | .. csv-table:: Amount of suported checks 15 | :header: "CISCO_IOS", "CISCO_NXOS" 16 | :widths: 15, 15 17 | 18 | 9, 11 -------------------------------------------------------------------------------- /docs/source/usage.rst: -------------------------------------------------------------------------------- 1 | Getting started 2 | =============== 3 | 4 | The following section describes how to use ``netlint``. 5 | 6 | Configuration 7 | ------------- 8 | 9 | Configuration is available through 10 | 11 | * Command line parameters (see :doc:`/cli`) 12 | * The ``[tool.netlint]`` section of the ``pyproject.toml`` file 13 | 14 | * Available options mirror the command line parameters 15 | * The config file location is configurable with ``-c/--config``. 16 | If the name of the config file is not ``pyproject.toml`` the 17 | ``[netlint]`` section is expected instead 18 | 19 | Usage in Python code 20 | -------------------- 21 | 22 | If you want to integrate ``netlint`` into your Python application, 23 | you need to import the ``Checker`` class from ``netlint.checks.checker``:: 24 | 25 | from application import do_stuff 26 | 27 | from netlint.checks.checker import Checker 28 | 29 | configuration = [ 30 | "feature ssh", 31 | "feature bgp", 32 | "hostname test.local" 33 | ] 34 | 35 | checker = Checker() 36 | 37 | checker.run_checks(configuration) 38 | 39 | # Check checker.check_results for the results of the checks 40 | for check, result in checker.items() 41 | do_stuff(result) 42 | 43 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | disallow_untyped_defs = True 3 | 4 | [mypy-ciscoconfparse] 5 | ignore_missing_imports = True -------------------------------------------------------------------------------- /netlint/__init__.py: -------------------------------------------------------------------------------- 1 | """Netlint network configuration linter.""" 2 | -------------------------------------------------------------------------------- /netlint/__main__.py: -------------------------------------------------------------------------------- 1 | """Enable python -m netlint.""" 2 | from netlint.cli.main import cli 3 | 4 | 5 | if __name__ == "__main__": 6 | cli() 7 | -------------------------------------------------------------------------------- /netlint/checks/__init__.py: -------------------------------------------------------------------------------- 1 | """The actual checking logics as well as checks are implemented in this module.""" 2 | 3 | # Import all the checks in order for the decorators to execute 4 | from netlint.checks.cisco_ios import * # noqa 5 | from netlint.checks.cisco_nxos import * # noqa 6 | from netlint.checks.various import * # noqa 7 | -------------------------------------------------------------------------------- /netlint/checks/checker.py: -------------------------------------------------------------------------------- 1 | """Implement the Checker class to run the checks.""" 2 | import functools 3 | import typing 4 | 5 | from netlint.checks.types import CheckResult, CheckFunction 6 | from netlint.checks.utils import NOS, Tag 7 | 8 | 9 | class Check: 10 | """Class to represent a check function. 11 | 12 | Auto-generated when @Checker.register() is used on a function. 13 | """ 14 | 15 | def __init__( 16 | self, 17 | check_function: CheckFunction, 18 | apply_to: typing.List[NOS], 19 | name: str, 20 | tags: typing.Set[Tag], 21 | ) -> None: 22 | self.check_function = check_function 23 | self.apply_to = apply_to 24 | self.name = name 25 | self.tags = tags 26 | self.function_doc = check_function.__doc__ 27 | 28 | def __call__(self, configuration: typing.List[str]) -> typing.Optional[CheckResult]: 29 | """Call the underlying function.""" 30 | return self.check_function(configuration) 31 | 32 | 33 | class Checker: 34 | """Class to handle check execution.""" 35 | 36 | # Map NOSes to applicable checks 37 | checks: typing.Dict[NOS, typing.List[Check]] = {} 38 | 39 | def __init__(self) -> None: 40 | pass 41 | 42 | @classmethod 43 | def register( 44 | cls, apply_to: typing.List[NOS], name: str, tags: typing.Set[Tag] 45 | ) -> typing.Callable[ 46 | [typing.Callable[[typing.List[str]], typing.Optional[CheckResult]]], 47 | Check, 48 | ]: 49 | """Decorate a function to register it as a check with any Checker instance. 50 | 51 | :param apply_to: List of NOSes to apply the check for. 52 | :param name: Name of the check. 53 | :param tags: A list of check tags that apply to this check. 54 | """ 55 | 56 | def decorator( 57 | function: typing.Callable[[typing.List[str]], typing.Optional[CheckResult]], 58 | ) -> Check: 59 | @functools.wraps(function) 60 | def wrapper(config: typing.List[str]) -> typing.Optional[CheckResult]: 61 | return function(config) 62 | 63 | check = Check( 64 | check_function=wrapper, apply_to=apply_to, name=name, tags=tags 65 | ) 66 | for nos in apply_to: 67 | if nos in cls.checks: 68 | cls.checks[nos].append(check) 69 | else: 70 | cls.checks[nos] = [check] 71 | return check 72 | 73 | return decorator 74 | 75 | def run_checks( 76 | self, configuration: typing.List[str], nos: NOS 77 | ) -> typing.Dict[str, typing.Optional[CheckResult]]: 78 | """ 79 | Run all the registered checks on the configuration. 80 | 81 | :param configuration: The configuration to check. 82 | :param nos: The NOS the configuration is for. 83 | :return: The check results. 84 | """ 85 | output = {} 86 | for check in self.checks[nos]: 87 | output[check.name] = check(configuration) 88 | return output 89 | -------------------------------------------------------------------------------- /netlint/checks/cisco_ios/__init__.py: -------------------------------------------------------------------------------- 1 | """Checks for the Cisco IOS NOS.""" 2 | import re 3 | import typing 4 | 5 | from netlint.checks import constants as c 6 | from netlint.checks.checker import Checker 7 | from netlint.checks.types import CheckResult 8 | 9 | __all__ = [ 10 | "check_plaintext_passwords", 11 | "check_console_password", 12 | "check_ip_http_server", 13 | "check_password_hash_strength", 14 | "check_used_but_unconfigured_access_lists", 15 | "check_unused_access_lists", 16 | "check_switchport_trunk_config", 17 | "check_switchport_access_config", 18 | ] 19 | 20 | from netlint.checks.utils import ( 21 | get_password_hash_algorithm, 22 | NOS, 23 | Tag, 24 | get_access_list_usage, 25 | get_access_list_definitions, 26 | get_name_from_acl_definition, 27 | parse, 28 | ) 29 | 30 | 31 | @Checker.register(apply_to=[NOS.CISCO_IOS], name="IOS101", tags={Tag.SECURITY}) 32 | def check_plaintext_passwords(config: typing.List[str]) -> typing.Optional[CheckResult]: 33 | """Check if there are any plaintext passwords in the configuration.""" 34 | config = parse("\n".join(config)) 35 | lines = config.find_lines("^username.*password") 36 | if lines: 37 | # If `service password-encryption` is configured, users are saved to the 38 | # config like `username test password 7 $ENCRYPTED. The following for-loop 39 | # checks for that. 40 | for line in lines: 41 | has_hash_algorithm = get_password_hash_algorithm(line) 42 | if not has_hash_algorithm: 43 | break 44 | else: 45 | # If the for loop wasn't exited prematurely, no plaintext passwords 46 | # are present. 47 | return None 48 | return CheckResult( 49 | text="Plaintext user passwords in configuration.", lines=lines 50 | ) 51 | else: 52 | return None 53 | 54 | 55 | @Checker.register( 56 | apply_to=[NOS.CISCO_IOS], name="IOS102", tags={Tag.SECURITY, Tag.OPINIONATED} 57 | ) 58 | def check_ip_http_server(config: typing.List[str]) -> typing.Optional[CheckResult]: 59 | """Check if the http server is enabled.""" 60 | config = parse("\n".join(config)) 61 | lines = config.find_lines("^ip http") 62 | if lines: 63 | return CheckResult(text="HTTP server not disabled.", lines=lines) 64 | else: 65 | return None 66 | 67 | 68 | @Checker.register( 69 | apply_to=[NOS.CISCO_IOS], name="IOS103", tags={Tag.SECURITY, Tag.OPINIONATED} 70 | ) 71 | def check_console_password(config: typing.List[str]) -> typing.Optional[CheckResult]: 72 | """Check for authentication on the console line.""" 73 | config = parse("\n".join(config)) 74 | line_con_config = config.find_all_children("^line con 0") 75 | if len(line_con_config) == 0: 76 | return None # TODO: Log this? 77 | 78 | login = False 79 | password = False 80 | for line in line_con_config: 81 | if "login" in line: 82 | login = True 83 | if "password" in line: 84 | password = True 85 | 86 | if not login or not password: 87 | return CheckResult(text="Console line unauthenticated.", lines=line_con_config) 88 | else: 89 | return None 90 | 91 | 92 | @Checker.register(apply_to=[NOS.CISCO_IOS], name="IOS104", tags={Tag.SECURITY}) 93 | def check_password_hash_strength( 94 | config: typing.List[str], 95 | ) -> typing.Optional[CheckResult]: 96 | """Check if strong password hash algorithms were used.""" 97 | config = parse("\n".join(config)) 98 | lines_with_passwords = config.find_lines(r"^.*(password|secret)\s\d.*$") 99 | bad_lines = [] 100 | for line in lines_with_passwords: 101 | hash_algorithm = get_password_hash_algorithm(line) 102 | if hash_algorithm in c.bad_hash_algorithms: 103 | bad_lines.append(line) 104 | if bad_lines: 105 | return CheckResult("Insecure hash algorithms in use.", lines=bad_lines) 106 | else: 107 | return None 108 | 109 | 110 | @Checker.register(apply_to=[NOS.CISCO_IOS], name="IOS105", tags={Tag.HYGIENE}) 111 | def check_switchport_trunk_config( 112 | config: typing.List[str], 113 | ) -> typing.Optional[CheckResult]: 114 | """Check if the switchport mode matches all config commands per interface.""" 115 | config = parse("\n".join(config)) 116 | interfaces = config.find_objects_w_child( 117 | r"^interface", r"^\s+switchport mode trunk" 118 | ) 119 | bad_lines = [] 120 | for interface in interfaces: 121 | bad_lines_per_interface = [interface.text] 122 | switchport_config_lines = list( 123 | filter(lambda l: re.match(r"^\s+switchport", l.text), interface.children) 124 | ) 125 | for line in switchport_config_lines: 126 | if line.text.strip().startswith("switchport access"): 127 | bad_lines_per_interface.append(line.text) 128 | if len(bad_lines_per_interface) > 1: 129 | bad_lines.extend(bad_lines_per_interface) 130 | if bad_lines: 131 | return CheckResult( 132 | "Access port config present on trunk interfaces.", lines=bad_lines 133 | ) 134 | else: 135 | return None 136 | 137 | 138 | @Checker.register( 139 | apply_to=[NOS.CISCO_IOS], 140 | name="IOS106", 141 | tags={Tag.HYGIENE, Tag.SECURITY}, 142 | ) 143 | def check_used_but_unconfigured_access_lists( 144 | config: typing.List[str], 145 | ) -> typing.Optional[CheckResult]: 146 | """Check for any ACLs that are used but never configured. 147 | 148 | Potential usages are: 149 | 150 | * Packet filtering 151 | * Rate limiting 152 | * Route maps 153 | """ 154 | config = parse("\n".join(config)) 155 | access_list_usages = get_access_list_usage(config) 156 | access_list_definitions = get_access_list_definitions(config) 157 | defined_access_lists = [] 158 | undefined_but_used_access_lists = [] 159 | for definition in access_list_definitions: 160 | name = get_name_from_acl_definition(definition) 161 | defined_access_lists.append(name) 162 | for usage in access_list_usages: 163 | # Get acl name/number from the configuration line for packet filtering usages 164 | # Standard use 165 | acl_in_filtering = re.findall(r"access-(class|group)\s(\S+|\d+)", usage) 166 | if acl_in_filtering and acl_in_filtering[0][1] not in defined_access_lists: 167 | undefined_but_used_access_lists.append(usage) 168 | # Evaluated in other ACLs 169 | acl_evaluated = re.findall(r"^\s+evaluate\s(\S+|\d+)", usage) 170 | if acl_evaluated and acl_evaluated[0] not in defined_access_lists: 171 | undefined_but_used_access_lists.append(usage) 172 | 173 | # Get acl name/number from the configuration line for route-map usages 174 | acl_in_route_map = re.findall(r"\s+match\sip\s\S+\s(\S+|\d+)", usage) 175 | if acl_in_route_map and acl_in_route_map[0] not in defined_access_lists: 176 | undefined_but_used_access_lists.append(usage) 177 | if undefined_but_used_access_lists: 178 | return CheckResult( 179 | text="Access lists used but never defined.", 180 | lines=undefined_but_used_access_lists, 181 | ) 182 | else: 183 | return None 184 | 185 | 186 | @Checker.register(apply_to=[NOS.CISCO_IOS], name="IOS107", tags={Tag.HYGIENE}) 187 | def check_unused_access_lists(config: typing.List[str]) -> typing.Optional[CheckResult]: 188 | """Check for any ACLs that are configured but never used. 189 | 190 | Potential usages are: 191 | 192 | * Packet filtering 193 | * Rate limiting 194 | * Route maps 195 | """ 196 | config = parse("\n".join(config)) 197 | access_lists = get_access_list_definitions(config) 198 | unused_acls = [] 199 | for acl in access_lists: 200 | name = get_name_from_acl_definition(acl) 201 | usages = get_access_list_usage(config, name=name) 202 | if not usages: 203 | unused_acls.append(acl) 204 | if unused_acls: 205 | return CheckResult(text="Unused ACLs configured", lines=unused_acls) 206 | else: 207 | return None 208 | 209 | 210 | @Checker.register(apply_to=[NOS.CISCO_IOS], name="IOS108", tags={Tag.HYGIENE}) 211 | def check_switchport_access_config( 212 | config: typing.List[str], 213 | ) -> typing.Optional[CheckResult]: 214 | """Check if the switchport mode matches all config commands per interface.""" 215 | config = parse("\n".join(config)) 216 | interfaces = config.find_objects_w_child( 217 | r"^interface", r"^\s+switchport mode access" 218 | ) 219 | bad_lines = [] 220 | for interface in interfaces: 221 | bad_lines_per_interface = [interface.text] 222 | switchport_config_lines = list( 223 | filter(lambda l: re.match(r"^\s+switchport", l.text), interface.children) 224 | ) 225 | for line in switchport_config_lines: 226 | if line.text.strip().startswith("switchport trunk"): 227 | bad_lines_per_interface.append(line.text) 228 | if len(bad_lines_per_interface) > 1: 229 | bad_lines.extend(bad_lines_per_interface) 230 | if bad_lines: 231 | return CheckResult( 232 | "Trunk port config present on access interfaces.", lines=bad_lines 233 | ) 234 | else: 235 | return None 236 | -------------------------------------------------------------------------------- /netlint/checks/cisco_nxos/__init__.py: -------------------------------------------------------------------------------- 1 | """Checks for the Cisco NXOS NOS.""" 2 | import typing 3 | 4 | from netlint.checks.checker import Checker 5 | from netlint.checks.cisco_nxos.utils import _feature_enabled_but_not_configured 6 | from netlint.checks.types import CheckResult 7 | 8 | __all__ = [ 9 | "check_telnet_enabled", 10 | "check_routing_protocol_enabled_and_used", 11 | "check_password_strength", 12 | "check_bogus_as", 13 | "check_lacp_feature_enabled_and_used", 14 | "check_vpc_feature_enabled_and_used", 15 | "check_fex_feature_set_installed_but_not_enabled", 16 | "check_switchport_mode_fex_fabric", 17 | ] 18 | 19 | from netlint.checks.constants import bogus_as_numbers 20 | from netlint.checks.utils import NOS, Tag, parse 21 | 22 | 23 | @Checker.register( 24 | apply_to=[NOS.CISCO_NXOS], name="NXOS101", tags={Tag.SECURITY, Tag.OPINIONATED} 25 | ) 26 | def check_telnet_enabled(config: typing.List[str]) -> typing.Optional[CheckResult]: 27 | """Check if the telnet feature is explicitly enabled.""" 28 | config = parse("\n".join(config)) 29 | lines = config.find_lines("^feature telnet") 30 | if lines: 31 | return CheckResult(text="Feature telnet is enabled.", lines=lines) 32 | else: 33 | return None 34 | 35 | 36 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS102", tags={Tag.HYGIENE}) 37 | def check_routing_protocol_enabled_and_used( 38 | config: typing.List[str], 39 | ) -> typing.Optional[CheckResult]: 40 | """Check if a routing protocol is actually used - should it be enabled.""" 41 | config = parse("\n".join(config)) 42 | for protocol in ["bgp", "ospf", "eigrp", "rip"]: 43 | feature_enabled = config.find_lines(f"^feature {protocol}") 44 | if not feature_enabled: 45 | return None 46 | 47 | feature_used = config.find_lines(f"^router {protocol}") 48 | if not feature_used: 49 | return CheckResult( 50 | text=f"{protocol.upper()} enabled but never used.", 51 | lines=feature_enabled + feature_used, 52 | ) 53 | return None 54 | 55 | 56 | @Checker.register( 57 | apply_to=[NOS.CISCO_NXOS], name="NXOS103", tags={Tag.SECURITY, Tag.OPINIONATED} 58 | ) 59 | def check_password_strength(config: typing.List[str]) -> typing.Optional[CheckResult]: 60 | """Check if the password strength check has been disabled.""" 61 | config = parse("\n".join(config)) 62 | disabled = config.find_lines("^no password strength-check") 63 | if disabled: 64 | return CheckResult(text="Password strength-check disabled.", lines=disabled) 65 | else: 66 | return None 67 | 68 | 69 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS104", tags={Tag.HYGIENE}) 70 | def check_bogus_as(config: typing.List[str]) -> typing.Optional[CheckResult]: 71 | """Check if any bogus autonomous system is used in the configuration.""" 72 | config = parse("\n".join(config)) 73 | bgp_routers = config.find_lines("^router bgp") 74 | bad_lines = [] 75 | for line in bgp_routers: 76 | as_number = int(line[11:]) 77 | if as_number in bogus_as_numbers: 78 | bad_lines.append(line) 79 | 80 | if bad_lines: 81 | return CheckResult(text="Bogus AS number in use", lines=bad_lines) 82 | else: 83 | return None 84 | 85 | 86 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS105", tags={Tag.HYGIENE}) 87 | def check_vpc_feature_enabled_and_used( 88 | config: typing.List[str], 89 | ) -> typing.Optional[CheckResult]: 90 | """Check if the vPC feature is actually used if it is enabled.""" 91 | config = parse("\n".join(config)) 92 | return _feature_enabled_but_not_configured( 93 | config, r"^feature vpc", r"^vpc domain", "vPC feature enabled but never used" 94 | ) 95 | 96 | 97 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS106", tags={Tag.HYGIENE}) 98 | def check_lacp_feature_enabled_and_used( 99 | config: typing.List[str], 100 | ) -> typing.Optional[CheckResult]: 101 | """Check if the LACP feature is actually used if it is enabled.""" 102 | config = parse("\n".join(config)) 103 | return _feature_enabled_but_not_configured( 104 | config, 105 | r"^feature lacp", 106 | r"^\s+channel-group \d+ mode active|passive", 107 | "LACP feature enabled but never used", 108 | ) 109 | 110 | 111 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS107", tags={Tag.HYGIENE}) 112 | def check_fex_feature_set_installed_but_not_enabled( 113 | config: typing.List[str], 114 | ) -> typing.Optional[CheckResult]: 115 | """Check if the fex feature-set is installed but not enabled.""" 116 | config = parse("\n".join(config)) 117 | return _feature_enabled_but_not_configured( 118 | config, 119 | r"^install feature-set fex", 120 | r"^feature-set fex", 121 | "Feature-set fex installed but not enabled.", 122 | ) 123 | 124 | 125 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS108", tags={Tag.HYGIENE}) 126 | def check_switchport_mode_fex_fabric( 127 | config: typing.List[str], 128 | ) -> typing.Optional[CheckResult]: 129 | """Check if any interface in switchport mode fex-fabric has a fex-id associated.""" 130 | config = parse("\n".join(config)) 131 | interfaces = config.find_objects_w_child("^interface", "switchport mode fex-fabric") 132 | faulty_lines = [] 133 | for interface in interfaces: 134 | current_lines = [interface.text] 135 | for line in interface.children: 136 | current_lines.append(line.text) 137 | if line.text.strip().startswith("fex associate"): 138 | break 139 | else: 140 | faulty_lines.extend(current_lines) 141 | if faulty_lines: 142 | return CheckResult( 143 | text="Interface in switchport mode fex-fabric without associated fex.", 144 | lines=faulty_lines, 145 | ) 146 | else: 147 | return None 148 | 149 | 150 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS109", tags={Tag.HYGIENE}) 151 | def check_fex_feature_enabled_and_used( 152 | config: typing.List[str], 153 | ) -> typing.Optional[CheckResult]: 154 | """Check whether an enabled fex feature is actually used.""" 155 | config = parse("\n".join(config)) 156 | return _feature_enabled_but_not_configured( 157 | config, 158 | r"^feature-set fex", 159 | r"^fex id", 160 | "Feature-set fex enabled but never used.", 161 | ) 162 | 163 | 164 | @Checker.register(apply_to=[NOS.CISCO_NXOS], name="NXOS110", tags={Tag.HYGIENE}) 165 | def check_fex_without_interface( 166 | config: typing.List[str], 167 | ) -> typing.Optional[CheckResult]: 168 | """Check whether every configured fex id also has an associated interface.""" 169 | config = parse("\n".join(config)) 170 | configured_fex_ids = config.find_lines(r"^fex id") 171 | faulty_fex_ids = [] 172 | for line in configured_fex_ids: 173 | fex_id = line.split()[2] 174 | has_interface = config.find_lines(r"^\s+fex associate {}".format(fex_id)) 175 | if not has_interface: 176 | faulty_fex_ids.append(line) 177 | if faulty_fex_ids: 178 | return CheckResult( 179 | text="FEX without associated interface configured.", lines=faulty_fex_ids 180 | ) 181 | else: 182 | return None 183 | -------------------------------------------------------------------------------- /netlint/checks/cisco_nxos/utils.py: -------------------------------------------------------------------------------- 1 | """Utilities for NXOS checks.""" 2 | 3 | import typing 4 | 5 | from netlint.checks.types import CheckResult 6 | from netlint.checks.utils import NetlintConfParse 7 | 8 | 9 | def _feature_enabled_but_not_configured( 10 | config: NetlintConfParse, 11 | feature_regex: str, 12 | configured_regex: str, 13 | failure_text: str, 14 | ) -> typing.Optional[CheckResult]: 15 | """Wrap common code for feature_enabled_and_used type checks.""" 16 | feature_enabled = config.find_lines(feature_regex) 17 | feature_configured = config.find_lines(configured_regex) 18 | if feature_enabled and not feature_configured: 19 | return CheckResult( 20 | text=failure_text, 21 | lines=feature_enabled + feature_configured, 22 | ) 23 | return None 24 | -------------------------------------------------------------------------------- /netlint/checks/constants.py: -------------------------------------------------------------------------------- 1 | """Provide constants for checks across vendors. 2 | 3 | These might come from standards, but they don't have to. 4 | """ 5 | 6 | bogus_as_numbers = [0, 23456, 4294967295] # RFC6483, RFC7607, RFC6793, RFC7300 7 | bogus_as_numbers += list(range(64496, 64511 + 1)) # RFC5398 8 | bogus_as_numbers += list(range(65536, 65551 + 1)) # RFC4893, RFC5398 9 | 10 | # Cisco password hash algorithms (0 is not included as it has its own check 11 | bad_hash_algorithms = [5, 7] 12 | 13 | # Regex for acl definitions 14 | acl_regex = r"^ip(v6)?\saccess-list\sextended" 15 | -------------------------------------------------------------------------------- /netlint/checks/types.py: -------------------------------------------------------------------------------- 1 | """Custom types for the checker code.""" 2 | 3 | import typing 4 | 5 | 6 | class CheckResult(typing.NamedTuple): 7 | """Result of a single check.""" 8 | 9 | text: str 10 | lines: typing.List[str] 11 | 12 | 13 | # Signature of a check function taking in a list of strings (the configuration) 14 | # and returning a CheckResult. 15 | CheckFunction = typing.Callable[[typing.List[str]], typing.Optional[CheckResult]] 16 | 17 | 18 | class CheckFunctionTuple(typing.NamedTuple): 19 | """Represent check functions along with any metadata.""" 20 | 21 | name: str 22 | function: CheckFunction 23 | -------------------------------------------------------------------------------- /netlint/checks/utils.py: -------------------------------------------------------------------------------- 1 | """Configuration checking utitilites.""" 2 | import functools 3 | import re 4 | import typing 5 | from enum import Enum 6 | 7 | from ciscoconfparse import CiscoConfParse 8 | 9 | from netlint.checks.constants import acl_regex 10 | 11 | 12 | class NetlintConfParse(CiscoConfParse): 13 | """Subclass of CiscoConfParse to implement hashing for use with caches.""" 14 | 15 | def __hash__(self) -> int: 16 | """Convert the underlying config to a string and hash that.""" 17 | configuration_as_string = "" 18 | for line in self.objs: 19 | configuration_as_string += line.text + "\n" 20 | return hash(configuration_as_string) 21 | 22 | 23 | def get_password_hash_algorithm(config_line: str) -> typing.Optional[int]: 24 | """Extract the number of the password hash algorithm from a config line. 25 | 26 | :param config_line: The configuration line that potentially contains the number. 27 | :return: If present, the integer identifying the algorithm. 28 | """ 29 | match = re.match(r"^.*(password|secret)\s\d\s\S+$", config_line) 30 | if not match: 31 | return None 32 | integer = re.search(r"\s\d\s", match[0], flags=re.MULTILINE) 33 | if not integer: 34 | return None 35 | else: 36 | # Guaranteed to be a string containing a single digit because of 37 | # 1) the re.match 38 | # 2) the fact that bool(match) == True 39 | return int(integer[0]) 40 | 41 | 42 | @functools.lru_cache(maxsize=None) 43 | def get_access_list_usage( 44 | config: NetlintConfParse, name: typing.Optional[str] = None 45 | ) -> typing.List[str]: 46 | """Return lines that use access lists. 47 | 48 | :param config: The config to filter in. 49 | :param name: Optionally filter for a specific ACL name. 50 | :return: A list of configuration lines that use this ACL. 51 | """ 52 | all_usages = [] 53 | 54 | # Find all access lists used in packet filtering 55 | access_list_usage_in_filtering_regex = r"(ip)? access-(group|class)" 56 | if name: 57 | access_list_usage_in_filtering_regex += " " + name 58 | all_usages.extend(config.find_lines(access_list_usage_in_filtering_regex)) 59 | access_list_usage_in_filtering_evaluate_regex = r"^\s+evaluate" 60 | if name: 61 | access_list_usage_in_filtering_evaluate_regex += " " + name 62 | all_usages.extend( 63 | config.find_children_w_parents( 64 | r"ip(v6)?\saccess-list\sextended", 65 | access_list_usage_in_filtering_evaluate_regex, 66 | ) 67 | ) 68 | 69 | # Find all access lists used in route-maps 70 | access_list_usage_in_route_map_regex = r"^\s+match ip \S+" 71 | if name: 72 | access_list_usage_in_route_map_regex += " " + name 73 | all_usages.extend( 74 | config.find_children_w_parents( 75 | r"^route-map", access_list_usage_in_route_map_regex 76 | ) 77 | ) 78 | 79 | # Find all access lists used in rate-limiting 80 | access_list_usage_in_rate_limiting_regex = r"^\s+rate-limit\soutput\saccess-group" 81 | if name: 82 | access_list_usage_in_rate_limiting_regex += " " + name 83 | all_usages.extend( 84 | config.find_children_w_parents( 85 | r"^interface", access_list_usage_in_rate_limiting_regex 86 | ) 87 | ) 88 | 89 | return all_usages 90 | 91 | 92 | @functools.lru_cache(maxsize=None) 93 | def get_access_list_definitions(config: NetlintConfParse) -> typing.List[str]: 94 | """Return all lines where access lists are defined.""" 95 | # Definitions of extended ACLs 96 | extended_acls = config.find_lines(acl_regex) 97 | 98 | # Definitions of standard ACLs 99 | standard_acls = config.find_lines(r"^access-list") 100 | 101 | # Definition of reflexive ACLs 102 | reflected_definitions = config.find_children_w_parents( 103 | acl_regex, r"^.*reflect\s(\S+|\d+)" 104 | ) 105 | return extended_acls + standard_acls + reflected_definitions 106 | 107 | 108 | class NOS(Enum): 109 | """Overview of different available NOSes.""" 110 | 111 | CISCO_IOS = "cisco_ios" 112 | CISCO_NXOS = "cisco_nxos" 113 | 114 | def __str__(self) -> str: 115 | """Overwrite __str__ to prettify the documentation.""" 116 | return self.name 117 | 118 | @staticmethod 119 | def from_napalm(driver: str) -> "NOS": 120 | """Convert the NAPALM driver name to a NOS instance.""" 121 | if driver == "ios": 122 | return NOS.CISCO_IOS 123 | elif driver in ["nxos", "nxos_ssh"]: 124 | return NOS.CISCO_NXOS 125 | else: 126 | raise ValueError(f"No NOS mapping found for NAPALM driver name {driver}.") 127 | 128 | 129 | class Tag(Enum): 130 | """Tagging for checks.""" 131 | 132 | # Checks that are not universal best practices but useful 133 | # most of the time. 134 | OPINIONATED = "opinionated" 135 | 136 | # Checks that are concerned with security aspects such as 137 | # missing or weak encryption. 138 | SECURITY = "security" 139 | 140 | # Checks that are concerned with configuration hygiene, such 141 | # as unused configuration items. 142 | HYGIENE = "hygiene" 143 | 144 | def __str__(self) -> str: 145 | """Overwrite __str__ to prettify the documentation.""" 146 | return self.name 147 | 148 | 149 | def detect_nos(configuration: typing.List[str]) -> NOS: 150 | """Automatically detect the NOS in the configuration. 151 | 152 | Very rudimentary as of now, will get more complex support for more NOSes is added. 153 | """ 154 | for line in configuration: 155 | if "feature" in line: 156 | return NOS.CISCO_NXOS 157 | return NOS.CISCO_IOS 158 | 159 | 160 | def get_name_from_acl_definition(acl: str) -> str: 161 | """Extract the ACL name from a ACL definition.""" 162 | if "reflect" in acl: 163 | name = re.findall(r"^.*reflect\s(\S+)", acl)[0] 164 | elif acl.startswith("access-list"): 165 | _, name, _ = acl.split(maxsplit=2) 166 | else: 167 | _, _, _, name = acl.strip().split(" ", maxsplit=4) 168 | return name 169 | 170 | 171 | @functools.lru_cache(maxsize=None) 172 | def parse(configuration: str) -> NetlintConfParse: 173 | """Parse a configuration into a NetlintConfParse object.""" 174 | return NetlintConfParse(configuration.splitlines()) 175 | -------------------------------------------------------------------------------- /netlint/checks/various/__init__.py: -------------------------------------------------------------------------------- 1 | """Checks that apply to more than one NOS.""" 2 | import typing 3 | 4 | from netlint.checks.checker import Checker 5 | from netlint.checks.types import CheckResult 6 | 7 | from netlint.checks.utils import ( 8 | NOS, 9 | Tag, 10 | parse, 11 | ) 12 | 13 | __all__ = [ 14 | "check_default_snmp_communities", 15 | ] 16 | 17 | 18 | @Checker.register( 19 | apply_to=[NOS.CISCO_IOS, NOS.CISCO_NXOS], name="VAR101", tags={Tag.SECURITY} 20 | ) 21 | def check_default_snmp_communities( 22 | config: typing.List[str], 23 | ) -> typing.Optional[CheckResult]: 24 | """Check for presence of default SNMP community strings.""" 25 | config = parse("\n".join(config)) 26 | snmp_communities = config.find_lines("^snmp-server community") 27 | for community in snmp_communities: 28 | if community.startswith("snmp-server community public") or community.startswith( 29 | "snmp-server community private" 30 | ): 31 | return CheckResult( 32 | text="Default SNMP communities present.", lines=snmp_communities 33 | ) 34 | 35 | return None 36 | -------------------------------------------------------------------------------- /netlint/cli/__init__.py: -------------------------------------------------------------------------------- 1 | """CLI specific code.""" 2 | -------------------------------------------------------------------------------- /netlint/cli/main.py: -------------------------------------------------------------------------------- 1 | """CLI entrypoint to netlint.""" 2 | import csv 3 | import json 4 | import os 5 | import typing 6 | from pathlib import Path 7 | 8 | import click 9 | import napalm # type: ignore 10 | import toml 11 | from rich.console import Console 12 | 13 | from netlint.checks.checker import Checker 14 | from netlint.checks.utils import NOS, detect_nos, Tag 15 | from netlint.cli.types import JSONOutputDict 16 | from netlint.cli.utils import smart_open, style, optional 17 | 18 | CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]} 19 | DEFAULT_CONFIG = "pyproject.toml" 20 | 21 | 22 | def configure( 23 | ctx: click.Context, _: typing.Union[click.Option, click.Parameter], filename: str 24 | ) -> None: 25 | """Evaluate the config file and set the default_map accordingly. 26 | 27 | Used as a callback from a click option. 28 | """ 29 | configuration_file = Path(filename).absolute() 30 | configuration_dict = {} 31 | if configuration_file.exists(): 32 | if filename == DEFAULT_CONFIG: 33 | try: 34 | configuration_dict = toml.load(configuration_file)["tool"]["netlint"] 35 | except KeyError: 36 | # If the user uses a pyproject.toml file but chooses not to configure 37 | # netlint there, we don't want to output anything. 38 | return 39 | else: 40 | try: 41 | configuration_dict = toml.load(configuration_file)["netlint"] 42 | except KeyError: 43 | click.secho( 44 | f"Configuration file '{configuration_file} doesn't contain" 45 | f"a [netlint] section." 46 | ) 47 | ctx.default_map = configuration_dict 48 | elif filename != DEFAULT_CONFIG: 49 | # If the the configuration location is not the default and 50 | # it doesn't exist, quit. 51 | click.secho( 52 | f"Configuration file '{configuration_file}' doesn't exist.", err=True 53 | ) 54 | ctx.exit(-1) 55 | else: 56 | # The pyproject.toml file is the configuration file but doesn't exist. 57 | return 58 | 59 | 60 | @click.group( 61 | invoke_without_command=True, context_settings=CONTEXT_SETTINGS, no_args_is_help=True 62 | ) # type: ignore 63 | @click.option( 64 | "-i", 65 | "--input", 66 | "input_path", 67 | type=click.Path( 68 | exists=True, file_okay=True, dir_okay=True, readable=True, resolve_path=True 69 | ), 70 | ) 71 | @click.option( 72 | "--glob", 73 | default="*.conf", 74 | show_default=True, 75 | help="Glob pattern to match files in the path with.", 76 | ) 77 | @click.option( 78 | "--prefix", 79 | default="-> ", 80 | show_default=True, 81 | help="Prefix for configuration lines output to the CLI.", 82 | ) 83 | @click.option( 84 | "-o", "--output", type=click.Path(writable=True), help="Optional output file." 85 | ) 86 | @click.option( 87 | "--exit-zero", 88 | is_flag=True, 89 | default=False, 90 | help="Exit code 0 even if errors are found.", 91 | ) 92 | @click.option( 93 | "--format", 94 | "format_", 95 | default="normal", 96 | type=click.Choice(["json", "normal", "csv"]), 97 | help="The format of the output data.", 98 | ) 99 | @click.option( 100 | "--select", 101 | type=str, 102 | help="Comma-separated list of check names to include" 103 | " (mutually exclusive with --exclude).", 104 | ) 105 | @click.option( 106 | "--exclude", 107 | type=str, 108 | help="Comma-separated list of check names to exclude" 109 | " (mutually exclusive with --select).", 110 | ) 111 | @click.option( 112 | "--exclude-tags", type=str, help="Comma-separated list of check tags to exclude." 113 | ) 114 | @click.option( 115 | "-q", 116 | "--quiet", 117 | is_flag=True, 118 | default=False, 119 | type=bool, 120 | help="Don't output non-errors.", 121 | ) 122 | @click.option( 123 | "-p", "--plain", is_flag=True, default=False, type=bool, help="Plain output." 124 | ) 125 | @click.option( 126 | "--color/--no-color", 127 | default=True, 128 | type=bool, 129 | help="Show colored output.", 130 | envvar="NO_COLOR", 131 | ) 132 | @click.option( 133 | "-c", 134 | "--config", 135 | default="pyproject.toml", 136 | type=click.Path(file_okay=True, dir_okay=False), 137 | callback=configure, 138 | is_eager=True, 139 | show_default=True, 140 | help="Path to TOML configuration file.", 141 | ) 142 | # Passing None as the first parameter leads to autodiscovery via setuptools 143 | @click.version_option(None, "-V", "--version", message="%(version)s") 144 | @click.pass_context 145 | def cli( 146 | ctx: click.Context, 147 | input_path: typing.Optional[str], 148 | glob: str, 149 | prefix: str, 150 | output: typing.Optional[str], 151 | format_: str, 152 | select: typing.Optional[str], 153 | exclude: typing.Optional[str], 154 | exclude_tags: typing.Optional[str], 155 | quiet: bool, 156 | color: bool, 157 | plain: bool, 158 | config: str, 159 | exit_zero: bool, 160 | ) -> None: 161 | """Perform static analysis on network device configuration files.""" 162 | ctx.ensure_object(dict) 163 | 164 | if select and exclude: 165 | click.echo("Error: --select and --exclude are mutually exclusive.") 166 | ctx.exit(-1) 167 | 168 | # Assume the user doesn't want any unnecessary output when not outputting 169 | # normally or outputting to a file. 170 | if format_ != "normal" or output: 171 | quiet = True 172 | plain = True 173 | 174 | # Save the settings into the context 175 | ctx.obj["quiet"] = quiet 176 | ctx.obj["plain"] = plain 177 | ctx.obj["color"] = color 178 | ctx.obj["prefix"] = prefix 179 | ctx.obj["output"] = output 180 | ctx.obj["format"] = format_ 181 | ctx.obj["input_path"] = input_path 182 | ctx.obj["checker"] = Checker() 183 | ctx.obj["console"] = Console() 184 | 185 | # Abort execution of the group if there is a subcommand 186 | if ctx.invoked_subcommand is not None: 187 | return 188 | 189 | has_errors = False 190 | 191 | configurations: typing.Dict[str, typing.List[str]] = {"default": []} 192 | 193 | if not input_path: 194 | click.echo( 195 | "Error: You need to pass -i/--input if you aren't using a" 196 | "subcommand to supply the configuration." 197 | ) 198 | ctx.exit(1) 199 | 200 | path = Path(input_path) 201 | 202 | nos_mapping: typing.Dict[str, NOS] = {} 203 | if path.is_file(): 204 | with open(path) as f: 205 | configurations["default"] = f.readlines() 206 | nos_mapping["default"] = detect_nos(configurations["default"]) 207 | elif path.is_dir(): 208 | path_items = path.glob(glob) 209 | for item in path_items: 210 | dict_key = str(item) 211 | with open(item) as f: 212 | configurations[dict_key] = f.readlines() 213 | nos_mapping[dict_key] = detect_nos(configurations[dict_key]) 214 | 215 | excluded_tags = set() 216 | try: 217 | if exclude_tags: 218 | excluded_tags = {Tag[name.upper()] for name in exclude_tags.split(",")} 219 | except KeyError as e: 220 | click.echo(f"Error: Unknown tag key {e}. Aborting.", err=True) 221 | ctx.exit(1) 222 | if select or exclude or excluded_tags: 223 | selected_checks = [] 224 | excluded_checks = [] 225 | checks_to_select = frozenset(select.split(",")) if select else set() 226 | checks_to_exclude = frozenset(exclude.split(",")) if exclude else set() 227 | for nos in set(nos_mapping.values()): 228 | for check in ctx.obj["checker"].checks[nos]: 229 | if check.name in checks_to_select: 230 | selected_checks.append(check) 231 | elif ( 232 | excluded_tags.intersection(check.tags) 233 | or check.name in checks_to_exclude 234 | ): 235 | excluded_checks.append(check) 236 | if checks_to_select: 237 | ctx.obj["checker"].checks[nos] = selected_checks 238 | for check in excluded_checks: 239 | if check in ctx.obj["checker"].checks[nos]: 240 | ctx.obj["checker"].checks[nos].remove(check) 241 | 242 | if path.is_file(): 243 | processed_config = check_config( 244 | ctx.obj["checker"], configurations["default"], nos_mapping["default"] 245 | ) 246 | if processed_config: 247 | has_errors = True 248 | write_output(ctx, processed_config) 249 | elif path.is_dir(): 250 | path_items = path.glob(glob) 251 | processed_configs: typing.Dict[str, JSONOutputDict] = {} 252 | for item in path_items: 253 | processed_configs[str(item)] = check_config( 254 | ctx.obj["checker"], configurations[str(item)], nos_mapping[str(item)] 255 | ) 256 | if processed_configs: 257 | has_errors = True 258 | newline = "" if format_ == "csv" else os.linesep 259 | with smart_open(output, newline=newline) as f: 260 | if format_ == "normal": 261 | for key, value in processed_configs.items(): 262 | f.write( 263 | style( 264 | f"{'=' * 10} {key}\n", 265 | plain=plain, 266 | bold=True, 267 | ) 268 | ) 269 | results_as_string = checks_to_string(value, plain, color, prefix) 270 | if results_as_string: 271 | f.write(results_as_string) 272 | elif not quiet: 273 | click.secho("No problems found!", bold=not plain) 274 | elif format_ == "json": 275 | json.dump(processed_configs, f) 276 | elif format_ == "csv": 277 | writer = csv.writer(f) 278 | # Find every unique check that is not filtered 279 | all_checks: typing.List[str] = [] 280 | for checks in ctx.obj["checker"].checks.values(): 281 | all_checks.extend(map(lambda c: c.name, checks)) 282 | sorted_unique_checks = sorted(set(all_checks)) 283 | writer.writerow(["Device"] + sorted_unique_checks) 284 | 285 | for key, value in processed_configs.items(): 286 | row = [key] 287 | row.extend(["Passed"] * len(sorted_unique_checks)) 288 | for name, result in value.items(): 289 | if result: 290 | index = sorted_unique_checks.index(name) 291 | row[index + 1] = "Failed" 292 | writer.writerow(row) 293 | 294 | if not has_errors and not quiet: 295 | click.secho("No problems found!", bold=not plain) 296 | 297 | if has_errors and not exit_zero: 298 | ctx.exit(-1) 299 | else: 300 | ctx.exit(0) 301 | 302 | 303 | @cli.command() 304 | @click.pass_context 305 | @click.option( 306 | "-d", 307 | "--driver", 308 | "driver_name", 309 | type=str, 310 | help="Name of the NAPALM driver to connect with.", 311 | ) 312 | @click.option("-u", "--username", prompt=True) 313 | @click.option("-p", "--password", prompt=True, hide_input=True) 314 | @click.argument("hostname", type=str) 315 | def get( 316 | ctx: click.Context, driver_name: str, username: str, password: str, hostname: str 317 | ) -> None: 318 | """Get live configuration off of devices.""" 319 | driver = napalm.get_network_driver(driver_name) 320 | status_color = "[bold green]" if ctx.obj["color"] else "" 321 | with optional( 322 | not ctx.obj["plain"] or ctx.obj["quiet"], 323 | ctx.obj["console"].status(f"{status_color}Retrieving the configuration..."), 324 | ) as _: 325 | with driver( 326 | hostname=hostname, username=username, password=password 327 | ) as connection: 328 | configuration = connection.get_config(retrieve="running")["running"] 329 | processed_config = check_config( 330 | ctx.obj["checker"], configuration.splitlines(), NOS.from_napalm(driver_name) 331 | ) 332 | 333 | write_output(ctx, processed_config) 334 | 335 | if not processed_config and not ctx.obj["quiet"]: 336 | click.secho("No problems found!\n", bold=not ctx.obj["plain"]) 337 | 338 | 339 | def write_output(ctx: click.Context, processed_config: JSONOutputDict) -> None: 340 | """Write the output for a processed configuration. 341 | 342 | :param ctx: The click context where ctx.obj contains the necessary settings. 343 | :param processed_config: The Check output dictionary. 344 | :return: None 345 | """ 346 | newline = "" if ctx.obj["format"] == "csv" else os.linesep 347 | with smart_open(ctx.obj["output"], newline=newline) as f: 348 | if ctx.obj["format"] == "normal": 349 | f.write( 350 | checks_to_string( 351 | processed_config, 352 | ctx.obj["plain"], 353 | ctx.obj["color"], 354 | ctx.obj["prefix"], 355 | ) 356 | ) 357 | elif ctx.obj["format"] == "json": 358 | json.dump(processed_config, f) 359 | elif ctx.obj["format"] == "csv": 360 | writer = csv.writer(f) 361 | headers = ["Device"] 362 | headers.extend(processed_config.keys()) 363 | writer.writerow(headers) 364 | values = [ctx.obj["input_path"]] 365 | values.extend( 366 | ["Failed" if value else "Passed" for value in processed_config.values()] 367 | ) 368 | writer.writerow(values) 369 | 370 | 371 | def check_config( 372 | checker_instance: Checker, configuration: typing.List[str], nos: NOS 373 | ) -> JSONOutputDict: 374 | """Run checks on config at a given path.""" 375 | return_value: JSONOutputDict = {} 376 | 377 | results = checker_instance.run_checks(configuration, nos) 378 | 379 | for check, result in results.items(): 380 | if not result: 381 | return_value[check] = None 382 | else: 383 | return_value[check] = { 384 | "text": result.text, 385 | "lines": result.lines, 386 | } 387 | return return_value 388 | 389 | 390 | def checks_to_string( 391 | check_result_dict: JSONOutputDict, plain: bool, color: bool, prefix: str 392 | ) -> str: 393 | """Convert a check result to its string representation.""" 394 | return_value = "" 395 | for check, result in check_result_dict.items(): 396 | if not result: 397 | continue 398 | lines = [line.strip() for line in result["lines"]] 399 | return_value += style(check, plain, bold=True) 400 | return_value += " " + result["text"] + "\n" 401 | return_value += style( 402 | prefix + f"\n{prefix}".join(lines), 403 | plain, 404 | fg="red" if color else None, 405 | ) 406 | return_value += "\n" 407 | return return_value 408 | 409 | 410 | if __name__ == "__main__": 411 | cli(obj={}) 412 | -------------------------------------------------------------------------------- /netlint/cli/types.py: -------------------------------------------------------------------------------- 1 | """Collection of custom types used.""" 2 | import typing 3 | 4 | import typing_extensions 5 | 6 | 7 | class JSONOutput(typing_extensions.TypedDict): 8 | """Represents a single check on a single configuration.""" 9 | 10 | text: str 11 | lines: typing.List[str] 12 | 13 | 14 | # Represents all checks on a single configuration. 15 | JSONOutputDict = typing.Dict[str, typing.Optional[JSONOutput]] 16 | -------------------------------------------------------------------------------- /netlint/cli/utils.py: -------------------------------------------------------------------------------- 1 | """CLI utilities.""" 2 | import contextlib 3 | import sys 4 | import typing 5 | 6 | import click 7 | 8 | 9 | @contextlib.contextmanager 10 | def smart_open( 11 | filename: typing.Optional[str] = None, mode: str = "w", **kwargs: typing.Any 12 | ) -> typing.Generator[typing.TextIO, None, None]: 13 | """Return a file handler for filename or sys.stdout if filename is None.""" 14 | if filename and filename != "-": 15 | fh = open(filename, mode, **kwargs) 16 | else: 17 | fh = sys.stdout 18 | try: 19 | yield fh # type: ignore 20 | finally: 21 | if fh is not sys.stdout: 22 | fh.close() 23 | 24 | 25 | def style(message: str, plain: bool, **kwargs: typing.Any) -> str: 26 | """Style a message with click.style if quiet is not set.""" 27 | if plain: 28 | return message 29 | else: 30 | return click.style(message, **kwargs) 31 | 32 | 33 | @contextlib.contextmanager 34 | def optional( 35 | condition: bool, context_manager: typing.ContextManager 36 | ) -> typing.Generator: 37 | """Apply the content manager if condition evaluates to True.""" 38 | if condition: 39 | with context_manager: 40 | yield 41 | else: 42 | yield 43 | -------------------------------------------------------------------------------- /netlint/weblint/__init__.py: -------------------------------------------------------------------------------- 1 | """Webserver component for netlint.""" 2 | import random 3 | import typing 4 | from pathlib import Path 5 | 6 | from fastapi import FastAPI 7 | from fastapi.requests import Request 8 | from fastapi.responses import HTMLResponse, Response 9 | from fastapi.templating import Jinja2Templates 10 | from pydantic import BaseModel 11 | 12 | from netlint.checks.checker import Checker 13 | from netlint.checks.utils import NOS 14 | 15 | app = FastAPI() 16 | 17 | this_dir = Path(__file__).parent 18 | 19 | templates = Jinja2Templates(directory=str(this_dir / "templates")) 20 | 21 | 22 | class Configuration(BaseModel): 23 | """The model with which the frontend posts the configuration.""" 24 | 25 | configuration: str 26 | nos: str 27 | 28 | 29 | @app.get("/", response_class=HTMLResponse) 30 | async def root(request: Request) -> Response: 31 | """Return the web site.""" 32 | # Pick a random faulty config from the tests folder 33 | config_folder = Path(__file__).parents[2] / "tests" / "configurations" / "cisco_ios" 34 | faulty_configs = list(config_folder.glob("*_faulty-*.conf")) 35 | with open(random.choice(faulty_configs)) as f: 36 | configuration = f.read() 37 | return templates.TemplateResponse( 38 | "base.j2", context={"request": request, "initial": configuration} 39 | ) 40 | 41 | 42 | @app.post("/check") 43 | async def check(configuration: Configuration) -> typing.Dict: 44 | """Run checks on POSTed configurations.""" 45 | checker = Checker() 46 | nos = NOS.from_napalm(configuration.nos) 47 | results = checker.run_checks(configuration.configuration.splitlines(), nos) 48 | return {key: value._asdict() for key, value in results.items() if value is not None} 49 | -------------------------------------------------------------------------------- /netlint/weblint/templates/base.j2: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 9 | 10 | 11 | 12 | 13 | Netlint 14 | 109 | 110 | 111 |
112 | 125 | 126 |
127 | 129 | 130 |
131 |
132 |
133 | 134 | 135 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "netlint" 3 | version = "0.1.2" 4 | description = "Performs static analysis on network device configuration files." 5 | authors = ["Leo Kirchner "] 6 | license = "GPLv3" 7 | readme = "README.md" 8 | homepage = "https://netlint.readthedocs.io" 9 | repository = "https://github.com/Kircheneer/netlint" 10 | keywords = ["lint", "networking"] 11 | classifiers = [ 12 | "Operating System :: OS Independent", 13 | "Programming Language :: Python :: 3.6", 14 | "Programming Language :: Python :: 3.7", 15 | "Programming Language :: Python :: 3.8", 16 | "Programming Language :: Python :: 3.9", 17 | "Topic :: Software Development :: Documentation", 18 | "Topic :: Software Development :: Quality Assurance", 19 | ] 20 | include = [ 21 | "LICENSE", 22 | ] 23 | 24 | [tool.poetry.dependencies] 25 | python = "^3.6.1" 26 | ciscoconfparse = "^1.5.30" 27 | click = ">=7.1.2,<9.0.0" 28 | sphinx = { version = ">=3.5.3,<5.0.0", optional = true } 29 | sphinx-rtd-theme = { version = "^0.5.2", optional = true } 30 | m2r2 = {version = "^0.2.7", optional = true } 31 | sphinx-click = {version = ">=2.7.1,<4.0.0", optional = true } 32 | typing-extensions = "^3.7.4" 33 | toml = "^0.10.2" 34 | napalm = "^3.2.0" 35 | rich = "^10.1.0" 36 | fastapi = "^0.65.1" 37 | uvicorn = ">=0.13.4,<0.15.0" 38 | Jinja2 = "^3.0.1" 39 | 40 | [tool.poetry.dev-dependencies] 41 | mypy = "^0.812" 42 | black = "^20.8b1" 43 | flake8 = "^3.9.2" 44 | pytest = "^6.2.4" 45 | coverage = "^5.5" 46 | sphinx = ">=3.5.3,<5.0.0" 47 | sphinx-rtd-theme = "^0.5.2" 48 | m2r2 = "^0.2.7" 49 | sphinx-click = ">=2.7.1,<4.0.0" 50 | pre-commit = "^2.13.0" 51 | flake8-docstrings = "^1.6.0" 52 | 53 | [tool.poetry.extras] 54 | # The following section is required to install docs dependencies 55 | # until RTD fully supports poetry: https://github.com/rtfd/readthedocs.org/issues/4912 56 | docs = ["sphinx", "sphinx_rtd_theme", "m2r2", "spinx-click"] 57 | 58 | [tool.poetry.scripts] 59 | netlint = 'netlint.cli.main:cli' 60 | 61 | [tool.netlint] 62 | 63 | [build-system] 64 | requires = ["poetry-core>=1.0.0"] 65 | build-backend = "poetry.core.masonry.api" 66 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kircheneer/netlint/b4e0830b81cba6ebe4aa681bcf5ce36958e252d2/tests/__init__.py -------------------------------------------------------------------------------- /tests/configurations/check_default_snmp_communities_faulty-0.conf: -------------------------------------------------------------------------------- 1 | snmp-server community public ro 2 | snmp-server community private rw -------------------------------------------------------------------------------- /tests/configurations/check_default_snmp_communities_good-0.conf: -------------------------------------------------------------------------------- 1 | snmp-server community read-only ro 2 | snmp-server community read-write rw -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_console_password_faulty-0.conf: -------------------------------------------------------------------------------- 1 | line con 0 2 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_console_password_good-0.conf: -------------------------------------------------------------------------------- 1 | line con 0 2 | password 12345 3 | login 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_ip_http_server_faulty-0.conf: -------------------------------------------------------------------------------- 1 | ip http server 2 | ip http secure-server -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_ip_http_server_good-0.conf: -------------------------------------------------------------------------------- 1 | no ip http server 2 | no ip http secure-server -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_password_hash_strength_faulty-0.conf: -------------------------------------------------------------------------------- 1 | username test password 5 $PASSWORD -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_password_hash_strength_good-0.conf: -------------------------------------------------------------------------------- 1 | username test -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_plaintext_passwords_faulty-0.conf: -------------------------------------------------------------------------------- 1 | username test password PLAINTEXT -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_plaintext_passwords_good-0.conf: -------------------------------------------------------------------------------- 1 | username test secret $ENCRYPTED 2 | username other password 7 $ENCRYPTED -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_switchport_access_config_faulty-0.conf: -------------------------------------------------------------------------------- 1 | interface GigabitEthernet0/1 2 | switchport mode access 3 | switchport trunk allowed vlan 1 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_switchport_access_config_good-0.conf: -------------------------------------------------------------------------------- 1 | interface GigabitEthernet0/1 2 | switchport mode access 3 | switchport access vlan 1 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_switchport_trunk_config_faulty-0.conf: -------------------------------------------------------------------------------- 1 | interface GigabitEthernet0/1 2 | switchport mode trunk 3 | switchport access vlan 1 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_switchport_trunk_config_good-0.conf: -------------------------------------------------------------------------------- 1 | interface GigabitEthernet0/1 2 | switchport mode trunk 3 | switchport trunk allowed vlan 2-5 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_unused_access_lists_faulty-0.conf: -------------------------------------------------------------------------------- 1 | access-list 1 permit any 2 | ! 3 | ip access-list extended extended-acl 4 | deny any log 5 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_unused_access_lists_faulty-1.conf: -------------------------------------------------------------------------------- 1 | ip access-list extended 1 2 | permit tcp any any reflect mirror 3 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_unused_access_lists_good-0.conf: -------------------------------------------------------------------------------- 1 | access-list 1 permit any 2 | access-list 2 permit any 3 | access-list 3 permit any 4 | ip access-list extended extended-acl 5 | deny any log 6 | ! 7 | route-map test 8 | match ip address 2 9 | ! 10 | interface GigabitEthernet0/1 11 | ip access-group extended-acl in 12 | rate-limit output access-group 3 128000 1500 2000 conform-action continue exceed-action drop 13 | ! 14 | line vty 0 15 | access-class 1 16 | ! 17 | -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_used_but_unconfigured_access_lists_faulty-0.conf: -------------------------------------------------------------------------------- 1 | interface GigabitEthernet0/1 2 | ip access-group 2 in 3 | ! 4 | line vty 0 5 | access-class 1 6 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_used_but_unconfigured_access_lists_faulty-1.conf: -------------------------------------------------------------------------------- 1 | route-map 1 2 | match ip address non-existent 3 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_used_but_unconfigured_access_lists_faulty-2.conf: -------------------------------------------------------------------------------- 1 | ip access-list extended name 2 | evaluate non-existent 3 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/check_used_but_unconfigured_access_lists_good-0.conf: -------------------------------------------------------------------------------- 1 | access-list 1 permit any 2 | ip access-list extended extended-acl 3 | deny any log 4 | ! 5 | ip access-list extended evaluating 6 | evaluate extended-acl 7 | ! 8 | interface GigabitEthernet0/1 9 | ip access-group extended-acl in 10 | ! 11 | line vty 0 12 | access-class 1 13 | ! 14 | -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/faulty.conf: -------------------------------------------------------------------------------- 1 | username test password ing 2 | ! 3 | ip http server 4 | ip http secure-server 5 | ! 6 | snmp-server community public ro 7 | snmp-server community private rw 8 | ! 9 | line con 0 10 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_ios/good.conf: -------------------------------------------------------------------------------- 1 | no ip http server 2 | no ip http secure-server 3 | ! 4 | snmp-server community not-public ro 5 | snmp-server community not-private rw 6 | ! 7 | line con 0 8 | login 9 | password testing 10 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_bogus_as_faulty-0.conf: -------------------------------------------------------------------------------- 1 | feature bgp 2 | ! 3 | router bgp 0 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_bogus_as_good-0.conf: -------------------------------------------------------------------------------- 1 | feature bgp 2 | ! 3 | router bgp 12345 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_fex_feature_enabled_and_used_faulty-0.conf: -------------------------------------------------------------------------------- 1 | feature-set fex 2 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_fex_feature_enabled_and_used_good-0.conf: -------------------------------------------------------------------------------- 1 | feature-set fex 2 | ! 3 | fex id 101 4 | pinning max-links 1 5 | description "FAULTY" 6 | ! 7 | interface port-channel101 8 | switchport mode fex-fabric 9 | fex associate 101 10 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_fex_feature_set_installed_but_not_enabled_faulty-0.conf: -------------------------------------------------------------------------------- 1 | install feature-set fex 2 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_fex_feature_set_installed_but_not_enabled_good-0.conf: -------------------------------------------------------------------------------- 1 | install feature-set fex 2 | feature-set fex -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_fex_without_interface_faulty-0.conf: -------------------------------------------------------------------------------- 1 | feature-set fex 2 | ! 3 | fex id 101 4 | pinning max-links 1 5 | description "FAULTY" 6 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_fex_without_interface_faulty-1.conf: -------------------------------------------------------------------------------- 1 | feature-set fex 2 | ! 3 | fex id 101 4 | pinning max-links 1 5 | description "FAULTY" 6 | ! 7 | interface port-channel102 8 | switchport mode fex-fabric 9 | fex associate 102 10 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_fex_without_interface_good-0.conf: -------------------------------------------------------------------------------- 1 | feature-set fex 2 | ! 3 | fex id 101 4 | pinning max-links 1 5 | description "FAULTY" 6 | ! 7 | interface port-channel101 8 | switchport mode fex-fabric 9 | fex associate 101 10 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_lacp_feature_enabled_and_used_faulty-0.conf: -------------------------------------------------------------------------------- 1 | feature lacp 2 | 3 | interface Ethernet1/1 4 | switchport 5 | switchport mode trunk 6 | channel-group 1 7 | 8 | interface port-channel1 9 | switchport 10 | switchport mode trunk 11 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_lacp_feature_enabled_and_used_faulty-1.conf: -------------------------------------------------------------------------------- 1 | feature lacp 2 | 3 | interface Ethernet1/1 4 | switchport 5 | switchport mode trunk 6 | 7 | interface Ethernet1/2 8 | switchport 9 | switchport mode access 10 | switchport access vlan 10 11 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_lacp_feature_enabled_and_used_good-0.conf: -------------------------------------------------------------------------------- 1 | feature lacp 2 | 3 | interface Ethernet1/1 4 | switchport 5 | switchport mode trunk 6 | channel-group 1 mode active 7 | 8 | interface port-channel1 9 | switchport 10 | switchport mode trunk 11 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_lacp_feature_enabled_and_used_good-1.conf: -------------------------------------------------------------------------------- 1 | feature lacp 2 | 3 | interface Ethernet1/1 4 | switchport 5 | switchport mode trunk 6 | channel-group 1 mode passive 7 | 8 | interface port-channel1 9 | switchport 10 | switchport mode trunk 11 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_password_strength_faulty-0.conf: -------------------------------------------------------------------------------- 1 | no password strength-check -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_password_strength_good-0.conf: -------------------------------------------------------------------------------- 1 | password strength-check -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_routing_protocol_enabled_and_used_faulty-0.conf: -------------------------------------------------------------------------------- 1 | feature bgp 2 | feature ospf 3 | feature eigrp 4 | feature rip -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_routing_protocol_enabled_and_used_good-0.conf: -------------------------------------------------------------------------------- 1 | feature bgp 2 | ! 3 | router bgp 12345 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_switchport_mode_fex_fabric_faulty-0.conf: -------------------------------------------------------------------------------- 1 | interface port-channel101 2 | switchport mode fex-fabric 3 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_switchport_mode_fex_fabric_good-0.conf: -------------------------------------------------------------------------------- 1 | interface port-channel101 2 | switchport mode fex-fabric 3 | fex associate 101 4 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_telnet_enabled_faulty-0.conf: -------------------------------------------------------------------------------- 1 | feature telnet -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_telnet_enabled_good-0.conf: -------------------------------------------------------------------------------- 1 | no feature telnet -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_vpc_feature_enabled_and_used_faulty-0.conf: -------------------------------------------------------------------------------- 1 | feature vpc 2 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_vpc_feature_enabled_and_used_good-0.conf: -------------------------------------------------------------------------------- 1 | feature vpc 2 | feature eigrp 3 | 4 | vpc domain 1 5 | peer-keepalive destination 1.2.3.4 source 5.6.7.8 vrf management 6 | peer-gateway 7 | layer3 peer-router 8 | 9 | router eigrp UNDERLAY 10 | router-id 192.0.2.100 11 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/check_vpc_feature_enabled_and_used_good-1.conf: -------------------------------------------------------------------------------- 1 | feature eigrp 2 | 3 | router eigrp UNDERLAY 4 | router-id 192.0.2.100 5 | -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/faulty.conf: -------------------------------------------------------------------------------- 1 | feature telnet 2 | feature bgp 3 | feature ospf 4 | feature eigrp 5 | feature rip 6 | ! 7 | no password strength-check 8 | ! 9 | snmp-server community public ro 10 | snmp-server community private rw 11 | ! -------------------------------------------------------------------------------- /tests/configurations/cisco_nxos/good.conf: -------------------------------------------------------------------------------- 1 | no feature telnet 2 | feature bgp 3 | ! 4 | router bgp 65536 5 | ! 6 | snmp-server community not-public ro 7 | snmp-server community not-private rw 8 | ! -------------------------------------------------------------------------------- /tests/test_checkers.py: -------------------------------------------------------------------------------- 1 | import typing 2 | from pathlib import Path 3 | 4 | import pytest 5 | 6 | from netlint.checks.checker import Checker, Check 7 | from netlint.checks.utils import NOS 8 | 9 | CONFIG_DIR = Path(__file__).parent / "configurations" 10 | 11 | # Build a list of tuples to allow for precise parametrization of the 12 | # test function. 13 | checks: typing.List[typing.Tuple[NOS, Check]] = [] 14 | for nos, check_list in Checker.checks.items(): 15 | for check in check_list: 16 | checks.append((nos, check)) 17 | 18 | 19 | def name_for_check_parameter(parameter: typing.List[typing.Tuple[NOS, Check]]) -> str: 20 | """Output nice name for the test naming with `pytest -v`.""" 21 | nos_instance, check_instance = parameter 22 | return f"{str(nos_instance)}/{check_instance.check_function.__name__}" 23 | 24 | 25 | @pytest.mark.parametrize("state", ["faulty", "good"]) 26 | @pytest.mark.parametrize("check_tuple", checks, ids=name_for_check_parameter) 27 | def test_basic(state: str, check_tuple: typing.List[typing.Tuple[NOS, Check]]): 28 | """Runs basic tests for checker functions. 29 | 30 | This depends on the Checker class. All checks registered with Checker.register 31 | will be processed by this test. The process goes as follows: 32 | - If the check applies to a single NOS, check 33 | ``tests/configurations/$NOS/$CHECK_FUNCTION_NAME_(faulty|good).conf`` 34 | for the configuration file. 35 | - If the check applies to multiple NOSes, check 36 | ``tests/configurations/$CHECK_FUNCTION_NAME_(faulty|good).conf`` 37 | for the configuration file. 38 | - Read the file, run the check against it, and check whether the output 39 | corresponds to the state. 40 | """ 41 | nos_instance, check_instance = check_tuple 42 | nos_dir = CONFIG_DIR / str(nos_instance).lower() 43 | check_name = check_instance.check_function.__name__ 44 | configuration_name_template = "{check}_{state}-{index}.conf" 45 | 46 | # Execute while new configurations files remain (iterating over the index 47 | # in the filename of the configuration files. 48 | index = 0 49 | while True: 50 | filename = configuration_name_template.format( 51 | check=check_name, state=state, index=index 52 | ) 53 | configuration_file = None 54 | if len(check_instance.apply_to) == 1: 55 | # If the check only applies to a single NOS, use the NOS specific 56 | # configurations folder 57 | configuration_file = nos_dir / filename 58 | elif len(check_instance.apply_to) >= 1: 59 | # If the check applies to multiple NOSes, use the parent 60 | # configurations folder 61 | configuration_file = CONFIG_DIR / filename 62 | else: 63 | AssertionError(f"Check {check_name} doesn't apply to any NOS") 64 | 65 | if not configuration_file.is_file(): 66 | if index == 0: 67 | # Fail if there is not a single configuration file for any given check 68 | pytest.fail( 69 | f"No configuration file {configuration_file} found for" 70 | f"check {check_name}." 71 | ) 72 | else: 73 | # If one configuration file was already processed, finish the test 74 | return 75 | 76 | # The checker is ran right here (through the __call__ function of the 77 | # Checker instance) 78 | with open(configuration_file) as f: 79 | result = check_instance(f.readlines()) 80 | if state == "good": 81 | assert result is None, f"Failed for {configuration_file.name}" 82 | elif state == "faulty": 83 | assert result is not None, f"Failed for {configuration_file.name}" 84 | 85 | index += 1 86 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import json 3 | from pathlib import Path 4 | 5 | import pytest 6 | from click.testing import CliRunner 7 | 8 | from netlint.cli.main import cli 9 | 10 | TESTS_DIR = Path(__file__).parent 11 | 12 | 13 | @pytest.mark.parametrize("plain", [True, False]) 14 | @pytest.mark.parametrize("format_", ["normal", "json", "csv"]) 15 | def test_lint_basic(plain: bool, format_: str): 16 | """Basic test for CLI linting functionality.""" 17 | runner = CliRunner() 18 | 19 | cisco_ios_faulty_conf = TESTS_DIR / "configurations" / "cisco_ios" / "faulty.conf" 20 | 21 | commands = ["-i", str(cisco_ios_faulty_conf)] 22 | 23 | if plain: 24 | commands.insert(0, "--plain") 25 | commands.extend(["--format", format_]) 26 | result = runner.invoke(cli, commands) 27 | 28 | # Assert the result contains an error 29 | if not result.exception: 30 | raise AssertionError("The result should contain errors here.") 31 | elif type(result.exception) != SystemExit: 32 | raise result.exception 33 | 34 | # Check for ANSI escape codes in the output if --quiet is set 35 | if plain: 36 | assert "\x1b" not in result.output 37 | 38 | if format_ == "json": 39 | result = json.loads(result.output) 40 | assert result 41 | elif format_ == "csv": 42 | result = list(csv.reader(result.output)) 43 | assert result 44 | 45 | # Test if the result no longer contains an error with --exit-zero 46 | commands.append("--exit-zero") 47 | result = runner.invoke(cli, commands) 48 | assert not result.exception 49 | 50 | 51 | def test_select_exclude_exclusivity(): 52 | """Test that --select and --exclude don't work together each other.""" 53 | runner = CliRunner() 54 | 55 | cisco_ios_faulty_conf = TESTS_DIR / "configurations" / "cisco_ios" / "faulty.conf" 56 | 57 | result = runner.invoke( 58 | cli, ["-i", str(cisco_ios_faulty_conf), "--select", "ABC", "--exclude", "XYZ"] 59 | ) 60 | 61 | assert "mutually exclusive" in result.stdout 62 | assert result.exception 63 | 64 | 65 | def test_config_file_not_found(): 66 | """Assert an exception is raised for a non-existant config file.""" 67 | runner = CliRunner() 68 | 69 | result = runner.invoke(cli, ["-c", "non-existent.toml"]) 70 | 71 | assert isinstance(result.exception, SystemExit) 72 | 73 | 74 | def test_input_dir(): 75 | """Test if passing a dictionary for -i works.""" 76 | runner = CliRunner() 77 | 78 | result = runner.invoke( 79 | cli, ["-i", str(TESTS_DIR / "configurations"), "--exit-zero"] 80 | ) 81 | 82 | assert not result.exception, result.exception 83 | 84 | 85 | def test_select_exclude(tmpdir: Path): 86 | """Test if the --select/--exclude options works correctly.""" 87 | runner = CliRunner() 88 | 89 | config_file = tmpdir / "test.conf" 90 | 91 | with open(config_file, "w") as f: 92 | f.writelines(["ip http server"]) 93 | 94 | commands = ["-i", str(tmpdir), "--exclude", "IOS101", "--exit-zero"] 95 | 96 | result = runner.invoke(cli, commands) 97 | 98 | assert not result.exception 99 | 100 | commands = ["-i", str(tmpdir), "--select", "IOS102", "--exit-zero"] 101 | 102 | result = runner.invoke(cli, commands) 103 | 104 | assert not result.exception 105 | 106 | commands = ["-i", str(tmpdir), "--exclude-tags", "security", "--exit-zero"] 107 | 108 | result = runner.invoke(cli, commands) 109 | 110 | assert not result.exception 111 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | import typing 2 | from types import ModuleType 3 | 4 | from netlint.checks.types import CheckFunction 5 | 6 | 7 | def get_method(check: str, module: ModuleType) -> typing.Optional[CheckFunction]: 8 | """Get a check method from a module.""" 9 | method = getattr(module, check) 10 | # Check is method is registered with any Checker (and therefore has to be tested) 11 | registered = getattr(method, "test", False) 12 | if registered: 13 | return method 14 | else: 15 | return None 16 | --------------------------------------------------------------------------------