├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── bandit_plugins ├── __init__.py └── bandit_high_entropy_string.py ├── requirements.txt ├── requirements_testing.txt ├── setup.cfg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | # rope 60 | .ropeproject 61 | 62 | # virtualenv 63 | venv 64 | 65 | # Ignore bandit config files 66 | bandit.yaml 67 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - '2.7' 4 | # command to install dependencies 5 | install: 'pip install -r requirements_testing.txt' 6 | # command to run tests 7 | script: 'make test' 8 | 9 | deploy: 10 | provider: pypi 11 | user: lyftpypi 12 | password: 13 | secure: HjpBidstyJ1sqUy/5b+XAsJAngvc9sD8W3q0v9mi72Ip4lZrhmgcQWlMLCmO69k3O91k+5bguotOfc+fvA29l6kiAs4kM70jIpFgzSVwXbVM8Q+P/cDeY/SALXzNGSQJWWqpavBuhdpbriRYg6WI5mQs0aGJ31ITsH/TuD2k1T9RA950kRQtrpiTIQZ00TLYqfOpcAN3+cwpYFEde5+tdCiR5o5ONr8UWF1/lr9DgO8DAqFbcFoqy2qUtM33XzZvqzcotW1eLnpnU5eKrJl/K038Rh/IoyEOG6mQ+ZIpHYAYftuCf2ZIWJ/P0CpjFYnAS7KK+xecZNADP62gbXdmjASGBVT37uNd7hC1nm6yGRwcFt25nqutdaLsNJkr2ULgJ0EG/of3/5NxsAmEgXV3yTjqyvbl7xcHi6atcqsTCNrUJzngGQjCOUWkJPpXb4aVECPGgbJOZ+4iXAkaweSow8U4eqNoJgll2UOdUq5UUpAImxk36x2xyHTbKFTpW+CzCyrN31J6L6NIth0/8rUAc7ryGlzpHCsdL62AjfgjAlJ1yMc3YoqFtV7l5eazDSHLgxR9M023Z7MtXUnkYp9FbOMEkpeetnfiWPhEAWfLeCL6drR6IOrxFtWGE+Xy4mOyXujKWfMCDDKFpOVgJzlBz0WkXuJ5mErBGcQJpNFi8Qo= 14 | on: 15 | tags: true 16 | distributions: sdist bdist_wheel 17 | repo: lyft/bandit-high-entropy-string 18 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | # 2.1.2 4 | 5 | * Packaging fix. This pypi release is the first usable release in 2.1.x 6 | 7 | # 2.1.1 8 | 9 | This is a broken release, please do not use. 10 | 11 | * Packaging fix 12 | 13 | # 2.1.0 14 | 15 | This is a broken release, please do not use. 16 | 17 | * Split classifer out into high-entropy-string library, and import from the 18 | bandit plugin. 19 | 20 | # 2.0 21 | 22 | ## 2.0.1 23 | 24 | * Fixes to packaging 25 | 26 | ## 2.0.0 27 | 28 | Compatibility with newer bandit. Incompatible with older bandit releases. 29 | 30 | # 1.0 31 | 32 | ## 1.0.1 33 | 34 | * Various fixes 35 | 36 | ## 1.0.0 37 | 38 | * Initial Release 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015-2016 Lyft Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # bash needed for pipefail 2 | SHELL := /bin/bash 3 | 4 | test: test_lint 5 | 6 | test_lint: 7 | mkdir -p build 8 | set -o pipefail; flake8 | sed "s#^\./##" > build/flake8.txt || (cat build/flake8.txt && exit 1) 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ⚠️ This repository has been archived and is no longer accepting contributions ⚠️ 2 | 3 | # bandit-high-entropy-string 4 | 5 | A bandit plugin that looks for high entropy hardcoded strings (secrets). 6 | 7 | This plugin exposes four new tests: 8 | 9 | 1. *high\_entropy\_assign*: Checks for secrets in assignment statements: `target = 'candidate'` 10 | 2. *high\_entropy\_funcarg*: Checks for secrets in function arguments: `caller('candidate', target='candidate'):` 11 | 3. *high\_entropy\_funcdef*: Checks for secrets in function definitions: `def caller('candidate', target='candidate'):` 12 | 4. *high\_entropy\_iter*: Checks for secrets in iterables (lists, tuples, dicts): `['candidate', 13 | 'candidate'] or ('candidate', 'candidate') or {'target': 'candidate'}` 14 | 15 | ## Installation 16 | 17 | First you'll need to install bandit (note that in bandit-high-entropy-string 18 | version 2.0 and higher you'll need to run bandit version 1.0 or higher): 19 | 20 | ```bash 21 | virtualenv venv 22 | source venv/bin/activate 23 | pip install bandit 24 | ``` 25 | 26 | Then you can install the plugin: 27 | 28 | ```bash 29 | pip install bandit-high-entropy-string 30 | ``` 31 | 32 | ## Configuration 33 | 34 | In your bandit.yaml config file, add the tests for inclusion: 35 | 36 | ```yaml 37 | # Backwards compatible configuration for using profiles (only needed if you 38 | # were previously using profiles and need to keep compatibility) 39 | profiles: 40 | Secrets: 41 | include: 42 | - high_entropy_assign 43 | - high_entropy_funcarg 44 | - high_entropy_funcdef 45 | - high_entropy_iter 46 | 47 | # Test inclusion for newer versions of bandit 48 | tests: 49 | # high_entropy_funcdef 50 | - BHES100 51 | # high_entropy_funcarg 52 | - BHES101 53 | # high_entropy_iter 54 | - BHES102 55 | # high_entropy_assign 56 | - BHES103 57 | ``` 58 | 59 | You can also add extra configuration for each test (in the same config file): 60 | 61 | ``` 62 | # Configuration for each test (can be configured for each of the four tests) 63 | 64 | high_entropy_assign: 65 | # Regex patterns to completely ignore for this test 66 | patterns_to_ignore: 67 | - 'public_key_.*' 68 | # Regex patterns to lower confidence for 69 | entropy_patterns_to_discount 70 | - 'maybe_public_key_.*' 71 | ``` 72 | 73 | ## Running the tests 74 | 75 | To run the tests, call bandit against your code base, specifying the profile: 76 | 77 | ``` 78 | $ bandit -r ./myapplication 79 | ``` 80 | 81 | ## Contributing 82 | 83 | ### Code of conduct 84 | 85 | This project is governed by [Lyft's code of 86 | conduct](https://github.com/lyft/code-of-conduct). 87 | All contributors and participants agree to abide by its terms. 88 | 89 | ### Sign the Contributor License Agreement (CLA) 90 | 91 | We require a CLA for code contributions, so before we can accept a pull request 92 | we need to have a signed CLA. Please [visit our CLA 93 | service](https://oss.lyft.com/cla) 94 | follow the instructions to sign the CLA. 95 | 96 | ### How it works and how to help 97 | 98 | The plugin captures portions of the AST, generates Candidate objects and sends 99 | them into the _report function. If a Candidate object's confidence is greater 100 | than 0, it's reported. We nudge the confidence and severity based on criterea: 101 | 102 | 1. Flags (ENTROPY_PATTERNS_TO_FLAG). Any Candidate that matches any regex in this 103 | list is automatically flagged as confidence/severity 3/3. If there's secret 104 | patterns you know conclusively are secrets, add them here. 105 | 2. Discounts (ENTROPY_PATTERNS_TO_DISCOUNT). Any Candidate that matches a regex in 106 | this list is discounted. If the Candidate matches multiple regexes in this 107 | list, it may be discounted further. This discount is used in the confidence 108 | calculation. 109 | 3. Secret hints (LOW_SECRET_HINTS, HIGH_SECRET_HINTS). If any target or caller 110 | matches a regex in these lists then it will be used as a hint that a 111 | Candidate is a secret. This hint is used in the confidence and severity 112 | calculations. LOW_SECRET_HINTS leads to a lower confidence increase and 113 | HIGH_SECRET_HINTS leads to a higher confidence increase. 114 | 4. Safe functions (SAFE_FUNCTION_HINTS). Any Candidate that has a caller that 115 | matches any string in this list will will be discounted. This is used in the 116 | confidence calculation. 117 | 5. Entropy. If a Candidate's confidence level can be more accurately gauged by 118 | a strings level of entropy, we calculate it and if the string has high 119 | entropy its confidence level is increased. This calculation is avoided if 120 | possible, as it's relatively expensive. 121 | 122 | The concept is to eliminate noise while more easily identifying Candidates that 123 | may be secrets. Some help we'd love to have: 124 | 125 | 1. Help with the discount regex list. The regexes in the list often match too 126 | much and there aren't enough that match common python strings. 127 | 2. Help with the safe functions list (and the way we match the safe functions). 128 | There's a lot of python functions that rarely include secrets but often 129 | contain high entropy strings. We currently don't identify these function 130 | calls very well, which leads to higher noise. 131 | 3. Add and improve string captures. We're not currently capturing all available strings 132 | in the AST and for some string captures we aren't capturing them as 133 | efficiently as we could. For instance with dicts, we capture info like: 134 | {'target': 'candidate'}, but don't capture: {'target': 'target': 'candidate'}, 135 | which could lead to better categorization. 136 | 137 | Feel free to submit issues and pull requests for anything else you think would be useful 138 | as well. 139 | -------------------------------------------------------------------------------- /bandit_plugins/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lyft/bandit-high-entropy-string/8f765785ed7d0780bfcd3ee1be4eec2526f41d40/bandit_plugins/__init__.py -------------------------------------------------------------------------------- /bandit_plugins/bandit_high_entropy_string.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | import ast 4 | import sys 5 | 6 | from high_entropy_string import PythonStringData 7 | 8 | import bandit 9 | from bandit.core import test_properties as test 10 | 11 | 12 | def gen_config(name): 13 | """ 14 | Default configuration for available configuration options. 15 | """ 16 | if name == 'patterns_to_ignore' or name == 'entropy_patterns_to_discount': 17 | return [] 18 | 19 | 20 | @test.takes_config 21 | @test.checks('FunctionDef') 22 | @test.test_id('BHES100') 23 | def high_entropy_funcdef(context, config): 24 | # looks for "def function(some_arg='candidate')" 25 | 26 | # this pads the list of default values with "None" if nothing is given 27 | defs = [None] * (len(context.node.args.args) - 28 | len(context.node.args.defaults)) 29 | defs.extend(context.node.args.defaults) 30 | 31 | strings = [] 32 | # go through all (param, value)s and look for candidates 33 | for key, val in zip(context.node.args.args, defs): 34 | if isinstance(key, ast.Name): 35 | target = key.arg if sys.version_info.major > 2 else key.id # Py3 36 | if isinstance(val, ast.Str): 37 | string_data = PythonStringData( 38 | string=val.s, 39 | target=target, 40 | node_type='argument', 41 | patterns_to_ignore=config.get('patterns_to_ignore'), 42 | entropy_patterns_to_discount=config.get( 43 | 'entropy_patterns_to_discount' 44 | ) 45 | ) 46 | strings.append(string_data) 47 | return _report(strings) 48 | 49 | 50 | @test.takes_config 51 | @test.checks('Call') 52 | @test.test_id('BHES101') 53 | def high_entropy_funcarg(context, config): 54 | # looks for "function('candidate', some_arg='candidate')" 55 | node = context.node 56 | strings = [] 57 | try: 58 | caller = context.call_function_name_qual 59 | except AttributeError: 60 | caller = None 61 | for kw in node.keywords: 62 | if isinstance(kw.value, ast.Str): 63 | string_data = PythonStringData( 64 | string=kw.value.s, 65 | target=kw.arg, 66 | caller=caller, 67 | node_type='kwargument', 68 | patterns_to_ignore=config.get('patterns_to_ignore'), 69 | entropy_patterns_to_discount=config.get( 70 | 'entropy_patterns_to_discount' 71 | ) 72 | ) 73 | strings.append(string_data) 74 | if isinstance(node.parent, ast.Assign): 75 | for targ in node.parent.targets: 76 | try: 77 | target = targ.id 78 | except AttributeError: 79 | target = None 80 | for arg in node.args: 81 | if isinstance(arg, ast.Str): 82 | string_data = PythonStringData( 83 | string=arg.s, 84 | caller=caller, 85 | target=target, 86 | node_type='argument', 87 | patterns_to_ignore=config.get('patterns_to_ignore'), 88 | entropy_patterns_to_discount=config.get( 89 | 'entropy_patterns_to_discount' 90 | ) 91 | ) 92 | strings.append(string_data) 93 | else: 94 | for arg in node.args: 95 | if isinstance(arg, ast.Str): 96 | string_data = PythonStringData( 97 | string=arg.s, 98 | caller=caller, 99 | node_type='argument', 100 | patterns_to_ignore=config.get('patterns_to_ignore'), 101 | entropy_patterns_to_discount=config.get( 102 | 'entropy_patterns_to_discount' 103 | ) 104 | ) 105 | strings.append(string_data) 106 | return _report(strings) 107 | 108 | 109 | def _get_assign(node): 110 | if isinstance(node, ast.Assign): 111 | return node 112 | else: 113 | return _get_assign(node.parent) 114 | 115 | 116 | @test.takes_config 117 | @test.checks('Dict') 118 | @test.checks('List') 119 | @test.checks('Tuple') 120 | @test.checks('Set') 121 | @test.test_id('BHES102') 122 | def high_entropy_iter(context, config): 123 | node = context.node 124 | if isinstance(node, ast.Dict): 125 | # looks for "some_string = {'target': 'candidate'}" 126 | _dict = dict(zip(node.keys, node.values)) 127 | strings = [] 128 | for key, val in _dict.iteritems(): 129 | if isinstance(key, ast.Str): 130 | target = key.s 131 | if isinstance(key, ast.Name): 132 | target = key.id 133 | else: 134 | target = None 135 | if not isinstance(val, ast.Str): 136 | continue 137 | string_data = PythonStringData( 138 | string=val.s, 139 | target=target, 140 | node_type='dict', 141 | patterns_to_ignore=config.get('patterns_to_ignore'), 142 | entropy_patterns_to_discount=config.get( 143 | 'entropy_patterns_to_discount' 144 | ) 145 | ) 146 | strings.append(string_data) 147 | return _report(strings) 148 | elif (isinstance(node, ast.List) or 149 | isinstance(node, ast.Tuple) or 150 | isinstance(node, ast.Set)): 151 | # looks for "target = ['candidate', 'candidate']" 152 | # looks for "target = ('candidate', 'candidate')" 153 | # looks for "target = set('candidate', 'candidate')" 154 | strings = [] 155 | for etl in node.elts: 156 | if isinstance(etl, ast.Str): 157 | string = etl.s 158 | else: 159 | continue 160 | try: 161 | assign = _get_assign(node.parent) 162 | for targ in assign.targets: 163 | try: 164 | target = targ.id 165 | except AttributeError: 166 | target = None 167 | string_data = PythonStringData( 168 | string=string, 169 | target=target, 170 | node_type='assignment', 171 | patterns_to_ignore=config.get('patterns_to_ignore'), 172 | entropy_patterns_to_discount=config.get( 173 | 'entropy_patterns_to_discount' 174 | ) 175 | ) 176 | strings.append(string_data) 177 | except AttributeError: 178 | string_data = PythonStringData( 179 | string=string, 180 | node_type='assignment', 181 | patterns_to_ignore=config.get('patterns_to_ignore'), 182 | entropy_patterns_to_discount=config.get( 183 | 'entropy_patterns_to_discount' 184 | ) 185 | ) 186 | strings.append(string_data) 187 | return _report(strings) 188 | 189 | 190 | @test.takes_config 191 | @test.checks('Str') 192 | @test.test_id('BHES103') 193 | def high_entropy_assign(context, config): 194 | node = context.node 195 | if isinstance(node.parent, ast.Assign): 196 | strings = [] 197 | # looks for "some_var='candidate'" 198 | for targ in node.parent.targets: 199 | try: 200 | target = targ.id 201 | except AttributeError: 202 | target = None 203 | string_data = PythonStringData( 204 | string=node.s, 205 | target=target, 206 | node_type='assignment', 207 | patterns_to_ignore=config.get('patterns_to_ignore'), 208 | entropy_patterns_to_discount=config.get( 209 | 'entropy_patterns_to_discount' 210 | ) 211 | ) 212 | strings.append(string_data) 213 | return _report(strings) 214 | elif isinstance(node.parent, ast.Index): 215 | # looks for "dict[target]='candidate'" 216 | # assign -> subscript -> index -> string 217 | assign = node.parent.parent.parent 218 | if isinstance(assign, ast.Assign): 219 | if isinstance(assign.value, ast.Str): 220 | string = assign.value.s 221 | else: 222 | return 223 | string_data = PythonStringData( 224 | string=string, 225 | target=node.s, 226 | node_type='assignment', 227 | patterns_to_ignore=config.get('patterns_to_ignore'), 228 | entropy_patterns_to_discount=config.get( 229 | 'entropy_patterns_to_discount' 230 | ) 231 | ) 232 | return _report([string_data]) 233 | elif isinstance(node.parent, ast.Compare): 234 | # looks for "target == 'candidate'" 235 | comp = node.parent 236 | if isinstance(comp.left, ast.Name): 237 | if isinstance(comp.comparators[0], ast.Str): 238 | string_data = PythonStringData( 239 | string=comp.comparators[0].s, 240 | target=comp.left.id, 241 | node_type='comparison', 242 | patterns_to_ignore=config.get('patterns_to_ignore'), 243 | entropy_patterns_to_discount=config.get( 244 | 'entropy_patterns_to_discount' 245 | ) 246 | ) 247 | return _report([string_data]) 248 | elif isinstance(node.parent, ast.Attribute): 249 | # looks for "target == 'candidate{0}'.format('some_string')" 250 | strings = [] 251 | if isinstance(node.parent.value, ast.Str): 252 | string = node.parent.value.s 253 | else: 254 | return 255 | try: 256 | caller = node.parent.attr 257 | except AttributeError: 258 | caller = None 259 | try: 260 | assign = _get_assign(node.parent) 261 | for targ in assign.targets: 262 | try: 263 | target = targ.id 264 | except AttributeError: 265 | target = None 266 | string_data = PythonStringData( 267 | string=string, 268 | caller=caller, 269 | target=target, 270 | node_type='assignment', 271 | patterns_to_ignore=config.get('patterns_to_ignore'), 272 | entropy_patterns_to_discount=config.get( 273 | 'entropy_patterns_to_discount' 274 | ) 275 | ) 276 | strings.append(string_data) 277 | except AttributeError: 278 | string_data = PythonStringData( 279 | string=string, 280 | caller=caller, 281 | node_type='assignment', 282 | patterns_to_ignore=config.get('patterns_to_ignore'), 283 | entropy_patterns_to_discount=config.get( 284 | 'entropy_patterns_to_discount' 285 | ) 286 | ) 287 | strings.append(string_data) 288 | return _report(strings) 289 | # TODO: Handle BinOp 290 | # TODO: Handle Return 291 | 292 | 293 | def _report(strings): 294 | reports = [] 295 | for string_data in strings: 296 | if string_data.confidence == 1: 297 | confidence = bandit.LOW 298 | elif string_data.confidence == 2: 299 | confidence = bandit.MEDIUM 300 | elif string_data.confidence >= 3: 301 | confidence = bandit.HIGH 302 | if string_data.severity == 1: 303 | severity = bandit.LOW 304 | elif string_data.severity == 2: 305 | severity = bandit.MEDIUM 306 | elif string_data.severity >= 3: 307 | severity = bandit.HIGH 308 | 309 | if type(string_data.string) is not unicode: 310 | string_data.string = string_data.string.decode( 311 | 'utf-8', 312 | errors='replace' 313 | ) 314 | string_data.string = string_data.string.encode( 315 | 'ascii', 316 | errors='replace' 317 | ) 318 | 319 | if len(string_data.string) > 12: 320 | secret_start = string_data.string[:4] 321 | secret_end = string_data.string[-4:] 322 | try: 323 | secret_start = secret_start 324 | secret_end = secret_end 325 | except (UnicodeDecodeError, UnicodeEncodeError): 326 | pass 327 | secret = '\'{0!s}...{1!s}\''.format(secret_start, secret_end) 328 | else: 329 | secret = string_data.string 330 | if string_data.confidence >= 1: 331 | reports.append(secret) 332 | if reports: 333 | return bandit.Issue( 334 | severity=severity, 335 | confidence=confidence, 336 | text=u'Possible hardcoded secret(s) {0}.'.format(', '.join(reports)) 337 | ) 338 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | high-entropy-string>=0.0.0,<1.0.0 2 | -------------------------------------------------------------------------------- /requirements_testing.txt: -------------------------------------------------------------------------------- 1 | # The modular source code checker: pep8, pyflakes and co 2 | # License: MIT 3 | # Upstream url: http://bitbucket.org/tarek/flake8 4 | flake8==2.3.0 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | # The jenkins violations plugin can read the pylint format. 3 | format = pylint 4 | max-line-length = 120 5 | 6 | # .svn,CVS,.bzr,.hg,.git,__pycache__: 7 | # default excludes 8 | # venv/: 9 | # third party libraries are all stored in venv - so we don't want to 10 | # check them for style issues. 11 | exclude = .git,__pycache__,venv,tests/,.ropeproject,examples 12 | 13 | [pep8] 14 | max-line-length = 120 15 | 16 | [metadata] 17 | name = bandit-high-entropy-string 18 | summary = A bandit plugin to check for strings that have high entropy (possible hardcoded secrets). 19 | description-file = README.md 20 | author = Ryan Lane 21 | author-email = rlane@lyft.com 22 | license = Apache-2 23 | 24 | [files] 25 | packages = 26 | bandit_plugins 27 | 28 | [entry_points] 29 | bandit.plugins = 30 | high_entropy_assign = bandit_plugins.bandit_high_entropy_string:high_entropy_assign 31 | high_entropy_funcarg = bandit_plugins.bandit_high_entropy_string:high_entropy_funcarg 32 | high_entropy_funcdef = bandit_plugins.bandit_high_entropy_string:high_entropy_funcdef 33 | high_entropy_iter = bandit_plugins.bandit_high_entropy_string:high_entropy_iter 34 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) 2016 Lyft Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13 | # implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import setuptools 18 | 19 | setuptools.setup( 20 | setup_requires=['pbr'], 21 | pbr=True) 22 | --------------------------------------------------------------------------------