Project Migration to PyCQA

This change rehomes the project to PyCQA[1] as reported to the
openstack-dev mailing list [1]

[0] https://github.com/PyCQA/bandit
[1] http://lists.openstack.org/pipermail/openstack-dev/2018-April/129386.html

Change-Id: I6aad329a60799ea24a3d9bc49e35c3c35ed9dc3b
This commit is contained in:
lhinds 2018-04-26 11:21:32 +01:00
parent 209182c3ee
commit 70f3648f71
261 changed files with 1488 additions and 8942 deletions

View File

@ -1,3 +0,0 @@
[report]
include = bandit/*
omit = bandit/tests/functional/*

19
.gitignore vendored
View File

@ -1,19 +0,0 @@
env*
venv*
*.pyc
.DS_Store
*.egg
*.egg-info
.eggs/
.idea/
.tox
.stestr
build/*
cover/*
.coverage*
doc/build/*
ChangeLog
doc/source/api
.*.sw?
AUTHORS
releasenotes/build

View File

@ -1,4 +0,0 @@
[DEFAULT]
test_path=${OS_TEST_PATH:-./tests/unit}
top_dir=./
group_regex=.*(test_cert_setup)

View File

@ -1,179 +0,0 @@
- job:
name: bandit-integration-barbican
parent: legacy-base
run: playbooks/legacy/bandit-integration-barbican/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/barbican
- openstack/requirements
- job:
name: bandit-integration-glance
parent: legacy-base
run: playbooks/legacy/bandit-integration-glance/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/glance
- openstack/requirements
- job:
name: bandit-integration-glance_store
parent: legacy-base
run: playbooks/legacy/bandit-integration-glance_store/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/glance
- openstack/glance_store
- openstack/requirements
- job:
name: bandit-integration-keystone
parent: legacy-base
run: playbooks/legacy/bandit-integration-keystone/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/keystone
- openstack/requirements
- job:
name: bandit-integration-keystonemiddleware
parent: legacy-base
run: playbooks/legacy/bandit-integration-keystonemiddleware/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/keystone
- openstack/keystonemiddleware
- openstack/requirements
- job:
name: bandit-integration-magnum
parent: legacy-base
run: playbooks/legacy/bandit-integration-magnum/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/magnum
- openstack/requirements
- job:
name: bandit-integration-oslo.config
parent: legacy-base
run: playbooks/legacy/bandit-integration-oslo.config/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/oslo.config
- openstack/requirements
- job:
name: bandit-integration-oslo.log
parent: legacy-base
run: playbooks/legacy/bandit-integration-oslo.log/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/oslo.log
- openstack/requirements
- job:
name: bandit-integration-oslo.service
parent: legacy-base
run: playbooks/legacy/bandit-integration-oslo.service/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/oslo.service
- openstack/requirements
- job:
name: bandit-integration-oslo.utils
parent: legacy-base
run: playbooks/legacy/bandit-integration-oslo.utils/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/oslo.utils
- openstack/requirements
- job:
name: bandit-integration-oslo.vmware
parent: legacy-base
run: playbooks/legacy/bandit-integration-oslo.vmware/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/oslo.vmware
- openstack/requirements
- job:
name: bandit-integration-python-keystoneclient
parent: legacy-base
run: playbooks/legacy/bandit-integration-python-keystoneclient/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/keystone
- openstack/python-keystoneclient
- openstack/requirements
- job:
name: bandit-integration-python-magnumclient
parent: legacy-base
run: playbooks/legacy/bandit-integration-python-magnumclient/run.yaml
timeout: 1800
required-projects:
- openstack/bandit
- openstack/magnum
- openstack/python-magnumclient
- openstack/requirements
- job:
name: bandit-integration-sahara
parent: legacy-base
run: playbooks/legacy/bandit-integration-sahara/run.yaml
timeout: 1800
required-projects:
- openstack/ara
- openstack/bandit
- openstack/requirements
- openstack/sahara
- project:
check:
jobs:
- bandit-integration-barbican
- bandit-integration-glance
- bandit-integration-keystone
- bandit-integration-glance_store
- bandit-integration-keystonemiddleware
- bandit-integration-magnum
- bandit-integration-oslo.config
- bandit-integration-oslo.log
- bandit-integration-oslo.service
- bandit-integration-oslo.utils
- bandit-integration-oslo.vmware
- bandit-integration-python-keystoneclient
- bandit-integration-python-magnumclient
- bandit-integration-sahara
- openstack-tox-lower-constraints
gate:
jobs:
- bandit-integration-barbican
- bandit-integration-glance
- bandit-integration-keystone
- bandit-integration-glance_store
- bandit-integration-keystonemiddleware
- bandit-integration-magnum
- bandit-integration-oslo.config
- bandit-integration-oslo.log
- bandit-integration-oslo.service
- bandit-integration-oslo.utils
- bandit-integration-oslo.vmware
- bandit-integration-python-keystoneclient
- bandit-integration-python-magnumclient
- openstack-tox-lower-constraints

65
AUTHORS Normal file
View File

@ -0,0 +1,65 @@
Andreas Jaeger <aj@suse.com>
Anh Tran <anhtt@vn.fujitsu.com>
Brant Knudson <bknudson@us.ibm.com>
Cao Xuan Hoang <hoangcx@vn.fujitsu.com>
Chandra Ganguly <ganguly@cisco.com>
Charles Neill <charles.neill@rackspace.com>
Christopher J Schaefer <cjschaef@us.ibm.com>
Cyril Roelandt <cyril@redhat.com>
Dave Belcher <dave.belcher@hp.com>
Dave Belcher <ukbelch@gmail.com>
Dave McCowan <dmccowan@cisco.com>
Dave Walker (Daviey) <email@daviey.com>
David Wyde <dwyde@cisco.com>
Deepika Gupta <deepika@cisco.com>
Elizabeth K. Joseph <lyz@princessleia.com>
Eric Brown <browne@vmware.com>
Flavio Percoco <flaper87@gmail.com>
Grant Murphy <grant.murphy@hpe.com>
Henry Yamauchi <henryyamauchi@yahoo.com>
Ian Cordasco <graffatcolmingov@gmail.com>
Ian Cordasco <ian.cordasco@rackspace.com>
Jamie Finnigan <jamie.finnigan@hp.com>
Jelle van der Waa <jelle@vdwaa.nl>
Jeremy Liu <liujiong@gohighsec.com>
Lucas Fisher <lucas.fisher@nebula.com>
Luke Hinds <lukehinds@gmail.com>
M V P Nitesh <m.nitesh@nectechnologies.in>
Matthew Edmonds <edmondsw@us.ibm.com>
Michael McCune <msm@redhat.com>
Nathan Kinder <nkinder@redhat.com>
Nguyen Hung Phuong <phuongnh@vn.fujitsu.com>
Philip Jones <philip.graham.jones@gmail.com>
Rahul Nair <rahulunair@gmail.com>
Rob Fletcher <fletcher@uber.com>
Robert Clark <hyakuhei@gmail.com>
Shuquan Huang <huang.shuquan@99cloud.net>
Stanisław Pitucha <stanislaw.pitucha@hp.com>
Stanisław Pitucha <viraptor@gmail.com>
Tim Kelsey <tim.kelsey@hp.com>
Tim Kelsey <tim.kelsey@hpe.com>
Timothy Kelsey <tim.kelsey@hpe.com>
Timothy Kelsey <timothy.kelsey@uk.ibm.com>
Tom Cocozzello <tjcocozz@us.ibm.com>
Tony Breeds <tony@bakeyournoodle.com>
Travis McPeak <tmcpeak@us.ibm.com>
Travis McPeak <travis.mcpeak@hp.com>
Travis McPeak <travis.mcpeak@hpe.com>
Travis McPeak <travismcpeak@tmcpeak-MBP.local>
ZhiQiang Fan <aji.zqfan@gmail.com>
chair6 <ja.miefinnigan@gmail.com>
chair6 <jamiefinnigan@gmail.com>
gecong1973 <ge.cong@zte.com.cn>
hparekh <hardik.parekh@nectechnologies.in>
lhinds <lukehinds@gmail.com>
lioplhp <hpliu5898@fiberhome.com>
liujiong <liujiong@gohighsec.com>
loooosy <syluo5695@fiberhome.com>
mattvaldes <matthew.valdes@rackspace.com>
pradeepcsekar <pradeech@cisco.com>
qinchunhua <qin.chunhua@zte.com.cn>
sudhir_agarwal <sudhir.agarwal@nectechnologies.in>
tmcpeak <travis_mcpeak@symantec.com>
xiabing.yao <yao.xiabing@99cloud.net>
zhangyanxian <zhang.yanxian@zte.com.cn>
zhangyanxian <zhangyanxianmail@163.com>

679
ChangeLog Normal file
View File

@ -0,0 +1,679 @@
CHANGES
=======
* Updated from global requirements
* Fixed order of arguments in assertEqual
* Updated from global requirements
* Add Apache License Content in index.rst
* Updated from global requirements
* Enable some off-by-default checks
* Updated from global requirements
* Updated from global requirements
* Updated from global requirements
* Optimize the link address
* Replace six.iteritems() with .items()
* Blacklist call of ssl.\_create\_unverified\_context
* Correct the yaml doc example to be actually yaml
* Enable coverage report in console output
* Updated from global requirements
* Updated from global requirements
* Yet Another Formatter (yaml)
* Repair the more info links for two blacklist calls
* Docs for B319 listed twice
* Refactor check\_example to be clearer on error
* Dump bandit config file lists vertically
* Allow config for high and medium severity key sizes
* HTTPSConnection is secure in newer Python
* Updated from global requirements
* Typo fix: targetting => targeting
* Use https for references to openstack.org
* Alter SQL injection plugin to consider .format strings
* Add Cryptodome to blacklist and weak ciphers/hash
* Alter SQL Injection plugin SQL check
1.4.0
-----
* Fixing some UTF8 encoding issues in file names
* Fix up nits in the README and other files
* Drop redundant dict call
* Removing 'stats' from JSON output formatter
* Fixing partial path detection for Windows
* Add Constraints support
* Make Bandit's HTML report pass markup validation
* Remove checking for special characters in shells
* Add functional tests for B308, B321, and B402
* Handle curve keyword arg weak\_cryptographic\_key
* Typo in calls doc for input call
* Fix LOG marker to follow the Python 3 guideline
* Fix pylint too-many-return-statements errors
1.3.0
-----
* Fixing B502 and B503 developer docs
* Fix pylint old-style-class errors
* Add capability to pipe a file into bandit
* Fix for pylint no-self-use error
* Show team and repo badges on README
* Detect binary output file (txt/html)
* Replace 'assertFalse(a in b)' with 'assertNotIn(a, b)'
* Don't include openstack/common in flake8 exclude list
* Trivial fixes based on pylint scan
* Fix typo in test\_set.py
* Replace 'assertTrue(a in b)' with 'assertIn(a, b)'
1.2.0
-----
* Updated from global requirements
* Updated from global requirements
* Fix unit tests for newest GitPython
* Fix blacklist filtering
* Replace 'MagicMock' with 'Mock'
* Use qualname list to avoid false positive on load()
* Enable release notes translation
* Updated from global requirements
* Updated from global requirements
* Updated from global requirements
* Updated from global requirements
* Fix a typo in test\_set.py
* Update flake8 ignore list
* Fix typos in config.py & utils.py
* Adding "input()" to the blacklist calls list
* Small typo fix 'balcklist' in docstring
* Enforce no star-imports since code complies
* Fix remaining object imports and enforce the rule
* Clean imports in code
* Fix order of arguments in assertEqual
* Update defusedxml notification
* Skip key checks where size is not constant
* Show help when arguments are missing
1.1.0
-----
* Fix html escaping
* Fix some errors in utils.py & calls.py
* Fix some typos in the files
* Some spelling error need to be fixed
* Remove white space between print and ()
* Add check for httpoxy vulnerability
* Fixing jenkins failing on coverage reporting
* Fix the typo in the files
* Updated from global requirements
* Remove discover from test-requirements
* Adding more plugin config docs
* Adding missing section to documentation about gen\_config
* Add missing Python 3.5 classifier
* Add a py35 tox venv for upcoming py35 support
* Add reno for release notes management
* Updated from global requirements
* Allow output to default to stdout using argparse
* Updated from global requirements
* Add man page for bandit command line
* Updated from global requirements
* Updated from global requirements
* [Trivial] Remove unnecessary executable privilege
* Updated from global requirements
* Catch general exception on per-file basis
* Updated from global requirements
1.0.1
-----
* Adding accurate docs for new bandit config
* Fixing a bug exposed with try, except, ... tests
* Ensure error exit codes fail integrations
* Calm down try,except,pass and try,except,continue
* Normalizing & editing command-line help text
* Added try\_except\_continue plugin
* Adding test IDs to test doc titles
* Fixing documentation for hardcoded password tests
* Delete the config, we dont need it now and its also invalid
* Improving config handling
* Blacklists now check node types are valid
* Fix OpenStack coverage tool
* Moving test summary to end of screen results
* Adding debug tox testenv for bandit
* Improving config generator script
* Breaking up blacklist import IDs
* The source of include/exclude conditions was incorrectly reported
* Update command line help baseline report
* Fix typos in CLI output
* Trimming Blacklists
* Updated legacy profile support
* Take2: Only use screen when terminal is tty
* Only use screen when terminal is tty
* Fixed missing new lines from Skipped file report
* Adding link to hosted docs in HTML output
* Fixing an encoding error while writing HTML
* Fixing bug when filtering blacklists
* Pass environment variables of proxy to tox
* Adding profile generation to config generator
* Additional baseline candidate test coverage
* Use bdist\_wheel instead of wheel
* Legacy blacklist data is missing some expected fields
* Fixed typo in bandit/formatters/xml.py
* Missing letter in blacklist calls doc
* Removing duplicate Test ID in HTML report
* Making config optional
* Ignore all .coverage files and extensions
* Functional tests for baseline comparisons
* (re)Fixing output of bytes
* Adding docs for new style blacklist imports
* Add bandit to pep8 dependencies
* Adding JSON output for baseline results
* Fixing bug with output chars in formatters
* old blacklist imports refered to 'qualnames' as 'imports'
* Add test to compare help output with readme
* Make pep8 \*the\* linting interface
* Adding docs for new style blacklist calls
* Add blacklist plugins to help output
* Test names are converted to IDs before ever getting this far
* Remove ignore of F403
* Added bandit.core.manager unit tests
* Added config\_generator unit tests
* Added cli.main unit tests
* Moving bandit baseline unit tests
* Old config compatibility
* Add version parameter to the command line
* Improved unit test coverage for bandit.cli.main
* Add PyPi badges
* This permits blacklist data to be filtered by ID
* Additional CLI main module unit tests
* Fixing hang in get\_module\_qualname\_from\_path
* Added unit tests for CLI main module
* Allow certain command line arguments to be passed from file
* Broken link in file jinja2\_templates.py
* Misspelling in file plugins/index.rst
* This fixes the blacklist to look like a plugin so we can filter it
* Misspelling in main developers doc title
* Broken link in file mako\_templates.py
* Fixing a bug and cleaning up in blacklisting code
* Cleaning code
* Adding some test coverage for config\_generator
* Only decode output of subprocess
* Broken link to plugin list in file config.rst
* Support hacking H104
* Misspelling in error message in file screen.py
* Breaking out blacklists
* Bandit baseline unit tests
* Change into the project directory
* Small typo fix on the tests include/exclude
* Pretty up the formatter docs
* Updated from global requirements
* Add test ID to the output
* Add script to test bandit against projects at gate
* Update docs to include references to EC keys
* Add ftplib as a insecure protocol to use
* Added more unit tests for bandit baseline
* Update readme with latest changes
* Add missing automodule doc for yaml\_load
* Allow list of tests to skip to be specified on command line
* Split yaml blacklist check into its own file
* Enable pep8 testing on tests
* Remove unnecessary absolute\_import logic from modules
* Improved unit test coverage for baseline module
* Move cli modules into their own submodule
* Adding a test for test id on test plugins
* Pretty up the plugin documentation
* Changing config generator to display options
* Proper B5xx test numbering
* Remove old docs
* Allow list of tests specified on command line
* Fixed a misspelling of the word "referred"
* Allow precise #nosec placement
* Fix db error when running python34 unit tests
* Putting plugin config in code
* Split lines only once per file
* Faster loc
* Use binary mode when reading files
* use six.moves.builtins in python3
* Replace logger.warn with logger.warning
* Use == for str comparison
* Fix comment about value returned
* Correct code output on python3
* Display nice error when profile is not found
* Fix output encoding in baseline
* Fix detached head baseline
* Ensure XML goes to binary file on py3
* Fix text and html output whitespace
* Changing severity on Bandit Baseline tox target
* Adding linters target to tox.ini
* Adding new screen formatter
* Adding test IDs
* Fix codesec tox env
* Adding Bandit Baseline Tox Target
* Remove show\_progress\_every from Bandit config file
* Add docs for formatters
0.17.0
------
* Use sphinx autodoc to generate docs from docstring
* Move status counter to stderr
* Tweaking logger
* Adding bandit-baseline tool
* Fix multiline string with missing space
* Update README with recent changes
* Config generator: fix a typo
0.16.2
------
* Updated from global requirements
* bandit-config-generator: Add documentation
* Lowering confidence of "any\_other\_function\_with\_shell\_equals\_true"
* Simpler baseline matching
* Cleaning up node visitor
* Removing unused code
* Improving node visitor
* Add a configuration generator for bandit
* Add functional runtime tests
0.16.1
------
* Fixing a simple issue in results count to fix exit code
0.16.0
------
* Adding baseline capabilities to HTML formatter and update report
* Adding Baseline Capability to the Text Formatter
* Changing the way baseline formatters are indicated
* Changing issue candidates in baseline to ordered dict
* os.system et al. all spawn a shell so we should use the same logic
* Fixing bug when encountering tuple params
* Fix simple bug in text formatter excluded files list
* Improving Bandit Baseline Reporting
* blacklist\_calls: add Python3 and six versions of some functions
* Test for bug 1513091
0.15.2
------
* Fixing bug in injection test
0.15.1
------
* Fixing Baseline when a filter is used
* Fixing Traceback with Bad File
* Making score sum totals more sane
* Added missing HTTP verbs to the requests checks
* Remove coverage files after run
0.15.0
------
* Adding missing docs
* Fixing some docs formatting
* Distinguish between formatted and simple commands
* Changing the confidence in the oslo secret plugin
* Adding plugin to output in text formatter
* Adding the plugin name to the HTML report
* Adding metrics and CSS styling to HTML formatter
* This adds baseline filtering to bandit
* Ensure each plugin is linked to appropriate sec guidance doc
* Add missing documentation for start\_process\_with\_a\_shell
* Collecting metrics code in one place
* Don't create files if we did not ask for them
* Add check for weak elliptic curve keys
* Add doc for weak\_cryptographic\_key plugin
0.14.1
------
* Adding command line option to exclude paths
* Tweaks to #nosec (+ ignore flag, - dead constant)
* Add check for Flask app debug=True usage
* Add metrics to text and JSON output formatters
* Add basic metric generation and associated tests
* Include context in debug output
* Tidy up plugin list in 'bandit -h' output
0.14.0
------
* Adding docs for Jinja2 autoescape
* Adding mako template docs
* Check for insecure cipher modes
* Adding docs for subprocess tests
* Adding docs for paramiko calls test
* Adding Linux wildcard docs
* Bad file permission docs
* Python 3 compatibility fix
* Making the /tmp file test more accurate
* Enabling new hardcoded password tests in the config
* Fixing -n behaviour
* Improved tests for hardcoded passwords
* Updated from global requirements
* Adding docs for SSL/TLS version tests
* Adding docs for try, except, pass
* Adding start\_process\_with\_partial\_path docs
* Adding docs for blacklist\_imports test
* Increasing coverage of try-except-pass to 100%
* Fixing bug introduced by manager refactor
* Adding documentation for blacklist calls
* Adding "exec\_used" documentation
* Removing argument printing
* Cleanup the blacklist plugin
* Cache blacklisted functions -> 5% faster
* Test coverage of manager now at 100%
* Fixing swapped parameters for issue severity and confidence
* Fix running when empty config file
* Remove tox envirnoment for pypy
* Add unit tests for bandit.core.issue
* Adding HTML formatter
* Split each formatter into separate modules
* Update .gitignore to exclude docs output
* Ignore vim swap files
* Simplifying Result Store
* Enabling coverage reporting in tox
* Dont read the wordlist file in on every test call, cache it
* Unit testing of meta\_ast.py
* bad\_file\_permissions check: Use correct filename
* Skip '/tests/' by default
* Add known weak ciphers to blacklisted calls
* Adding "hardcoded\_sql\_expressions" documentation
* Adding "hardcoded\_tmp\_directory" documentation
* Adding "hardcoded\_password" documentation
* Adding assert\_used documentation
* Fix manager having no attribute '\_init\_logger'
* Generate module docs
* Add unit tests for the formatters
* Raise exceptions from BanditConfig rather than exit
* Removing class level variables
* Introduce wildcards to blacklist\_calls plugin
* Adding unit tests for bandit.core.context.Context
* Remove redundant quotes in bandit.yaml
* meta-ast is only needed if we are in debug mode
* Adding any\_other\_function\_with\_shell\_equals\_true documentation
* Adding "execute\_with\_run\_as\_root\_equals\_true" documentation
* Adding "hardcoded\_bind\_all\_interfaces" documentation
* Add a new check for weak RSA and DSA key sizes
* Update .gitignore for docs
* Use addCleanup rather than tearDown
* Use testtools rather than unittest
* Adding documentation for test plugins
* Adding documentation for configuration
* Additional unit test coverage for core/utils.py
* Fix typos in bandit.yaml
* Replace incorrect safe\_str
* Trivial fix to beautify bandit.yaml
* Add Bytes AST support
* Variable file not defined in error path
* Adding test tool for check OpenStack projects' Bandit job
* Remove unreachable code in config.py
* Unit tests for bandit.core.config
* Adding a check for key in get\_call\_arg\_at\_position
* Py3 compatibility fix in lines\_with\_context() util
* Remove unused safe\_unicode() utility function
* Adding check for node key in Context
* Remove unused describe\_symbol() utility function
* Better function to count lines in a file
* Adding the key lookup to Context.call\_args\_string
* Remove unused test\_basic.py
* Rename core.test\_config to test\_bandit
* Adding a check for call in call\_args\_count
* Refactoring Unit Test Directories
* Update gitignore for coverage
* Update git clone repo
* Eliminate dir(node) -> 10% faster
0.13.2
------
* Find bandit.yaml when in virtualenv
0.13.1
------
* Add other known weak MD hash modules
* Capture warnings for missing plugins or config in normal logging
* Skip a test if it requires config but none is found
* Clean up test\_config
* Add info: License, Source, Bugs and Docs to README
0.13.0
------
* Actually default to /etc/ rather than just claim
* Build universal wheels for PyPI
* Update README with latest changes
* Convert README to rst
* NIT: Fix missing python 3 in classifier
* Add a confidence filter
* Rewording subprocess without shell finding
* Fixes exit code for filtered results
* Adding report timestamp
* Bug fix for SQL tests
* Adding a more informative help message for "-l"
* Activate pep8 check that \_ is imported
* Add all available plugins to an example profile
* Revised XML tests
* Adding documentation framework
* Register plugins included as entry-points
* Improving SQL Injection detection
* Fixing up random to be less noisy
* Bring the logger up as soon as possible
* Bug fix in secret\_config\_option plugin
* Consider other hardcoded tmp paths
* Install word\_list, raise exception if cannot find
* Modifying Paramiko Injection plugin
* Adding test for Try, Except, Pass
* Add tool for reporting Bandit OpenStack coverage
* Update .gitreview file for project rename
* Don't run with no tests
* Faster Bandit
* Removing statement buffer
* Adding a test for partial paths in exec functions
0.12.0
------
* Address multiline node lineno inaccuracies
* Actually rely on entry-points for formatters
* Add extension entry-points and loading
* Adding paramiko injections check to blacklist functions
* Fix config option fallback if "include" missing
* Update README with missing usage changes
* Adding verbose flag
* Log the version of Python bandit is running under
* Add notes to the README about Bandit on Python 3.4
* Clean up tests and examples for Python 3.4
* Update example files to work on Python 2 & 3
* Add Python 3.4 compatibility to bandit
* Adding documentation for SSL/TLS tests
* Adding docs for temp issues
* Use best logging practices
* Smooth over some differences with six
* Handle exception when invalid config file is specified
* Update bandit to use absolute imports
* Refactor BanditResultStore.report
* Add XML output format support
0.11.0
------
* Update the README file
* Changing config file search paths
* Adding a check for the use of Assert
* Add XML vulnerability checking
* Shift in result types & ranking scales
* Added csv output format
* Update README.rst
* Fixed issue processing files containing invalid python
* Update email to openstack-dev
* Refactored/optimized reporting code
0.10.1
------
* Fixing info output that was breaking JSON format
* fixing bandits config settings
0.10.0
------
* Fixing a bug with files listing when a file was skipped
* Fixed -n flag processing
* Fix a couple of issues with handling multi-line strings
* Fixed severity level filtering
* Fix new output file checking functionality
* Adding util methods to help handle the mix of unicode and string
* Add error checks/handing around output file case
* Fix vulnerability aggregation bug
* Fixed nosec flagging
* Moving lineno into generic visitor
* Make subprocess without \`shell=True\` into a plugin
* Tweaking severity for a few plugins
* Remove Python 2.6 from setup.cfg
* Correct supported Python versions in setup.cfg
* Update the config file, and use yaml.safe\_load()
* Wildcard injection requires a shell
* Fixing uncaught 'InvalidModulePath' exception
* Fix a leftover tuple unpacking in reporting code
* Add tests for subprocesses and deserialization
* Fixes for node\_visitor, sql and hardcoded password tests
* Add mako templating plugin and XSS profile
* Refactored AST processing
* Refactor functional tests to clarify scoring
* Clean up test property decorators after refactor
* Return the full name used in calls
* Add mock to test-requirements
* Add ceilometer to rootwrap check
* Minor cleanup for \_matches\_glob\_list function
* Add check for secret=True on oslo password options
* assertEqual should be (expected, actual)
* Adds line ranges, DRYs code, fixes #nosec
* Add documentation for exec, yaml, jinja2 plugins
* Add list of Python values considered False
* Update jinja2 plugin to be more accurate
* Adding file discovery and directory exclusion
* Adds jinja2 autocomplete=false test
* Adds JSON output functionality
* Add rootwrap checks for neutron and cinder
* Add INFO check for any use of rootwrap
* Further decorator changes and plugin migration
* Removing un-reachable code
* Adds decorator methods for tests
* Removing warning about modules not installed in sys.path
* New constants to support updated results structure
* Adding meaningful exit codes to support use in gate
* Rename README.md to README.rst
* Update test-requirements.txt to match global requirements
* Add \_\_repr\_\_ to the context object
* Minor changes to profile-related debug output
0.9.0
-----
* Remove the check for PROTOCOL\_SSLv23
* Make func, class name definitions fully qualified
* Add unaliased mod name to import\_aliases; Fix tests
* Blacklist urlopen-like functions in urllib, urllib2
* Add yaml.load to blacklist with yaml example file
* Fix a reported bug when bandit encounters "\_\_import\_\_()"
* Hardening bandit in the face of buggy plugins or odd ASTs
* Graceful degradation when failing to full qualify an attr node
* Fixing an oversight when processing none-attr nodes
* Refactoring "checks\_functions" to check function definitions
* Removing TODO (to be tracked in Bandit wiki)
* Updated README file
* Adding a set of functional tests based on the examples folder
* Quantifying bandit test results
* Removing Py26 from the test env list, it's being deprecated
* Adding a basic test for the gate (need at least one to pass)
* Enabling PEP8 tests in tox and re-working source to comply
* Making Bandit into an installable package and adding tox tests
* Removing default '' return for ast\_args\_to\_str()
* Adding a test for use of HTTPSConnection
* Adding a check to bandit for use of 'exec'
* Better checks against blacklisted modules, catch \_\_import\_\_
* Adding SSL/TLS protocol version checks
* Temporarily commenting out hardcoded password test, it's broken
* Add .gitreview file
* Bug fix for hardcoded passwords test
* Updated configuration file
* Adding option to aggregate by vulnerability type and a test for hardcoded /tmp usage
* Adding a test for hardcoded passwords
* PEP 8 fixes
* Renaming plugins, creating import blacklist section, adding check for dup function names
* Updating the random test to include all usages of the random lib
* Updated README
* Updated AUTHORS file
* Adding a test for random.random, use will return an INFO level message
* Adding SQL Injection test, examples, and profile
* Adding capability to check if certain modules have been imported during function calls
* Minor PEP 8 fixes
* Added AUTHORS file
* Updated README file
* Updating command line switches
* Updated TODO file
* Updating the README file to keep parity with recent changes
* Fix bug with permissions matching
* Moving bad names definition to config file; fixed bug with qualname
* Create settings system, moved more fixed values to config, improved readability
* First pass at moving some things to config, begin cleaning up code
* Separate each test into its own file
* Fixed a bug with handling \_ast.Tuple
* Allow creation of test profiles and switch config to yaml
* Test type marked using decorators and tests now automatically discovered from plugins directory
* Test type marked using decorators and tests now automatically discovered from plugins directory
* Adding a property to access the raw AST node from context instance
* Changed to pass Context instance to tests, rather than raw context
* Refactoring to move the AST implementation details out of tests
* Adding example file for utils.execute\* shell=True tests
* Adding more unsafe shell=True usage checks for OS utils library
* Wildcard injection tests crash on non-string args
* Updated README
* Updated README
* Updated TODO
* Test for mark\_safe() calls
* Updated README
* Broader test for calls with shell=True parameter
* Updated README
* First test targeting Str nodes (binding to all interfaces)
* Minor PEP8 fixes
* Add support for Str node types
* Allow individual lines of code to be flagged for exclusion
* Updated TODO
* Updated README
* Rework case where no findings are found
* Modify call\_bad\_names test to use regex and add to blacklist
* Introduce and utilize module-level constants
* Specify UTF-8 coding
* Updated TODO
* Addition of Apache License 2.0
* pep8 fix
* Remove debug prints
* Updated wildcards test to catch Popen(['','','']) case
* Updated README
* Tidy up output format
* Optionally write output to file specified
* pep8 fixes
* pep8 fixes
* pep8 fixes
* Adding wildcard injection test
* pep8 fixes
* pep8 fixes
* Modify manager to only display progress where needed
* Remove unnecessary logger.error call from manager
* Fix 'self' reference in manager
* Add support for skipping files
* Fix relative imports and error handling
* Reposition setting of lineno in visit\_Import and visit\_ImportFrom
* Support dynamic loading of tests
* Refactor the call tests to use the new test context
* Remove unused ast\_args\_to\_str method
* refactor to extract imports tests and build context
* new bad imports example
* starting refactor to extract tests from core
* Move existing call tests into separate methods
* updated readme
* updated readme
* initial commit
* Initial commit

176
LICENSE
View File

@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

View File

@ -1,428 +1,13 @@
Bandit
======
.. image:: https://governance.openstack.org/badges/bandit.svg
:target: https://governance.openstack.org/reference/tags/index.html
:alt: Bandit team and repository tags
This project is no longer maintained in OpenStack.
.. image:: https://img.shields.io/pypi/v/bandit.svg
:target: https://pypi.python.org/pypi/bandit/
:alt: Latest Version
Please visit PyCQA to raise issues or make contributions:
.. image:: https://img.shields.io/pypi/pyversions/bandit.svg
:target: https://pypi.python.org/pypi/bandit/
:alt: Python Versions
https://github.com/PyCQA/bandit
.. image:: https://img.shields.io/pypi/format/bandit.svg
:target: https://pypi.python.org/pypi/bandit/
:alt: Format
.. image:: https://img.shields.io/badge/license-Apache%202-blue.svg
:target: https://git.openstack.org/cgit/openstack/bandit/plain/LICENSE
:alt: License
A security linter from OpenStack Security
* Free software: Apache license
* Documentation: https://wiki.openstack.org/wiki/Security/Projects/Bandit
* Source: https://git.openstack.org/cgit/openstack/bandit
* Bugs: https://bugs.launchpad.net/bandit
Overview
--------
Bandit is a tool designed to find common security issues in Python code. To do
this Bandit processes each file, builds an AST from it, and runs appropriate
plugins against the AST nodes. Once Bandit has finished scanning all the files
it generates a report.
Installation
------------
Bandit is distributed on PyPI. The best way to install it is with pip:
Create a virtual environment (optional)::
virtualenv bandit-env
Install Bandit::
pip install bandit
# Or if you're working with a Python 3.5 project
pip3.5 install bandit
Run Bandit::
bandit -r path/to/your/code
Bandit can also be installed from source. To do so, download the source tarball
from PyPI, then install it::
python setup.py install
Usage
-----
Example usage across a code tree::
bandit -r ~/openstack-repo/keystone
Example usage across the ``examples/`` directory, showing three lines of
context and only reporting on the high-severity issues::
bandit examples/*.py -n 3 -lll
Bandit can be run with profiles. To run Bandit against the examples directory
using only the plugins listed in the ``ShellInjection`` profile::
bandit examples/*.py -p ShellInjection
Bandit also supports passing lines of code to scan using standard input. To
run Bandit with standard input::
cat examples/imports.py | bandit -
Usage::
$ bandit -h
usage: bandit [-h] [-r] [-a {file,vuln}] [-n CONTEXT_LINES] [-c CONFIG_FILE]
[-p PROFILE] [-t TESTS] [-s SKIPS] [-l] [-i]
[-f {csv,custom,html,json,screen,txt,xml,yaml}]
[--msg-template MSG_TEMPLATE] [-o [OUTPUT_FILE]] [-v] [-d]
[--ignore-nosec] [-x EXCLUDED_PATHS] [-b BASELINE]
[--ini INI_PATH] [--version]
[targets [targets ...]]
Bandit - a Python source code security analyzer
positional arguments:
targets source file(s) or directory(s) to be tested
optional arguments:
-h, --help show this help message and exit
-r, --recursive find and process files in subdirectories
-a {file,vuln}, --aggregate {file,vuln}
aggregate output by vulnerability (default) or by
filename
-n CONTEXT_LINES, --number CONTEXT_LINES
maximum number of code lines to output for each issue
-c CONFIG_FILE, --configfile CONFIG_FILE
optional config file to use for selecting plugins and
overriding defaults
-p PROFILE, --profile PROFILE
profile to use (defaults to executing all tests)
-t TESTS, --tests TESTS
comma-separated list of test IDs to run
-s SKIPS, --skip SKIPS
comma-separated list of test IDs to skip
-l, --level report only issues of a given severity level or higher
(-l for LOW, -ll for MEDIUM, -lll for HIGH)
-i, --confidence report only issues of a given confidence level or
higher (-i for LOW, -ii for MEDIUM, -iii for HIGH)
-f {csv,custom,html,json,screen,txt,xml,yaml}, --format {csv,custom,html,json,screen,txt,xml,yaml}
specify output format
--msg-template MSG_TEMPLATE
specify output message template (only usable with
--format custom), see CUSTOM FORMAT section for list
of available values
-o [OUTPUT_FILE], --output [OUTPUT_FILE]
write report to filename
-v, --verbose output extra information like excluded and included
files
-d, --debug turn on debug mode
--ignore-nosec do not skip lines with # nosec comments
-x EXCLUDED_PATHS, --exclude EXCLUDED_PATHS
comma-separated list of paths to exclude from scan
(note that these are in addition to the excluded paths
provided in the config file)
-b BASELINE, --baseline BASELINE
path of a baseline report to compare against (only
JSON-formatted files are accepted)
--ini INI_PATH path to a .bandit file that supplies command line
arguments
--version show program's version number and exit
CUSTOM FORMATTING
-----------------
Available tags:
{abspath}, {relpath}, {line}, {test_id},
{severity}, {msg}, {confidence}, {range}
Example usage:
Default template:
bandit -r examples/ --format custom --msg-template \
"{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}"
Provides same output as:
bandit -r examples/ --format custom
Tags can also be formatted in python string.format() style:
bandit -r examples/ --format custom --msg-template \
"{relpath:20.20s}: {line:03}: {test_id:^8}: DEFECT: {msg:>20}"
See python documentation for more information about formatting style:
https://docs.python.org/3.4/library/string.html
The following tests were discovered and loaded:
-----------------------------------------------
B101 assert_used
B102 exec_used
B103 set_bad_file_permissions
B104 hardcoded_bind_all_interfaces
B105 hardcoded_password_string
B106 hardcoded_password_funcarg
B107 hardcoded_password_default
B108 hardcoded_tmp_directory
B109 password_config_option_not_marked_secret
B110 try_except_pass
B111 execute_with_run_as_root_equals_true
B112 try_except_continue
B201 flask_debug_true
B301 pickle
B302 marshal
B303 md5
B304 ciphers
B305 cipher_modes
B306 mktemp_q
B307 eval
B308 mark_safe
B309 httpsconnection
B310 urllib_urlopen
B311 random
B312 telnetlib
B313 xml_bad_cElementTree
B314 xml_bad_ElementTree
B315 xml_bad_expatreader
B316 xml_bad_expatbuilder
B317 xml_bad_sax
B318 xml_bad_minidom
B319 xml_bad_pulldom
B320 xml_bad_etree
B321 ftplib
B322 input
B323 unverified_context
B324 hashlib_new_insecure_functions
B401 import_telnetlib
B402 import_ftplib
B403 import_pickle
B404 import_subprocess
B405 import_xml_etree
B406 import_xml_sax
B407 import_xml_expat
B408 import_xml_minidom
B409 import_xml_pulldom
B410 import_lxml
B411 import_xmlrpclib
B412 import_httpoxy
B501 request_with_no_cert_validation
B502 ssl_with_bad_version
B503 ssl_with_bad_defaults
B504 ssl_with_no_version
B505 weak_cryptographic_key
B506 yaml_load
B601 paramiko_calls
B602 subprocess_popen_with_shell_equals_true
B603 subprocess_without_shell_equals_true
B604 any_other_function_with_shell_equals_true
B605 start_process_with_a_shell
B606 start_process_with_no_shell
B607 start_process_with_partial_path
B608 hardcoded_sql_expressions
B609 linux_commands_wildcard_injection
B701 jinja2_autoescape_false
B702 use_of_mako_templates
Configuration
-------------
An optional config file may be supplied and may include:
- lists of tests which should or shouldn't be run
- exclude_dirs - sections of the path, that if matched, will be excluded from
scanning
- overridden plugin settings - may provide different settings for some
plugins
Per Project Command Line Args
-----------------------------
Projects may include a `.bandit` file that specifies command line arguments
that should be supplied for that project. The currently supported arguments
are:
- targets: comma separated list of target dirs/files to run bandit on
- exclude: comma separated list of excluded paths
- skips: comma separated list of tests to skip
- tests: comma separated list of tests to run
To use this, put a .bandit file in your project's directory. For example:
::
[bandit]
exclude: /test
::
[bandit]
tests: B101,B102,B301
Exclusions
----------
In the event that a line of code triggers a Bandit issue, but that the line
has been reviewed and the issue is a false positive or acceptable for some
other reason, the line can be marked with a ``# nosec`` and any results
associated with it will not be reported.
For example, although this line may cause Bandit to report a potential
security issue, it will not be reported::
self.process = subprocess.Popen('/bin/echo', shell=True) # nosec
Vulnerability Tests
-------------------
Vulnerability tests or "plugins" are defined in files in the plugins directory.
Tests are written in Python and are autodiscovered from the plugins directory.
Each test can examine one or more type of Python statements. Tests are marked
with the types of Python statements they examine (for example: function call,
string, import, etc).
Tests are executed by the ``BanditNodeVisitor`` object as it visits each node
in the AST.
Test results are maintained in the ``BanditResultStore`` and aggregated for
output at the completion of a test run.
Writing Tests
-------------
To write a test:
- Identify a vulnerability to build a test for, and create a new file in
examples/ that contains one or more cases of that vulnerability.
- Consider the vulnerability you're testing for, mark the function with one
or more of the appropriate decorators:
- @checks('Call')
- @checks('Import', 'ImportFrom')
- @checks('Str')
- Create a new Python source file to contain your test, you can reference
existing tests for examples.
- The function that you create should take a parameter "context" which is
an instance of the context class you can query for information about the
current element being examined. You can also get the raw AST node for
more advanced use cases. Please see the context.py file for more.
- Extend your Bandit configuration file as needed to support your new test.
- Execute Bandit against the test file you defined in examples/ and ensure
that it detects the vulnerability. Consider variations on how this
vulnerability might present itself and extend the example file and the test
function accordingly.
Extending Bandit
----------------
Bandit allows users to write and register extensions for checks and formatters.
Bandit will load plugins from two entry-points:
- `bandit.formatters`
- `bandit.plugins`
Formatters need to accept 4 things:
- `result_store`: An instance of `bandit.core.BanditResultStore`
- `file_list`: The list of files which were inspected in the scope
- `scores`: The scores awarded to each file in the scope
- `excluded_files`: The list of files that were excluded from the scope
Plugins tend to take advantage of the `bandit.checks` decorator which allows
the author to register a check for a particular type of AST node. For example
::
@bandit.checks('Call')
def prohibit_unsafe_deserialization(context):
if 'unsafe_load' in context.call_function_name_qual:
return bandit.Issue(
severity=bandit.HIGH,
confidence=bandit.HIGH,
text="Unsafe deserialization detected."
)
To register your plugin, you have two options:
1. If you're using setuptools directly, add something like the following to
your ``setup`` call::
# If you have an imaginary bson formatter in the bandit_bson module
# and a function called `formatter`.
entry_points={'bandit.formatters': ['bson = bandit_bson:formatter']}
# Or a check for using mako templates in bandit_mako that
entry_points={'bandit.plugins': ['mako = bandit_mako']}
2. If you're using pbr, add something like the following to your `setup.cfg`
file::
[entry_points]
bandit.formatters =
bson = bandit_bson:formatter
bandit.plugins =
mako = bandit_mako
Contributing
------------
Contributions to Bandit are always welcome! We can be found on
#openstack-security on Freenode IRC.
The best way to get started with Bandit is to grab the source::
git clone https://git.openstack.org/openstack/bandit.git
You can test any changes with tox::
pip install tox
tox -e pep8
tox -e py27
tox -e py35
tox -e docs
tox -e cover
Reporting Bugs
--------------
Bugs should be reported on Launchpad. To file a bug against Bandit, visit:
https://bugs.launchpad.net/bandit/+filebug
Under Which Version of Python Should I Install Bandit?
------------------------------------------------------
The answer to this question depends on the project(s) you will be running
Bandit against. If your project is only compatible with Python 2.7, you
should install Bandit to run under Python 2.7. If your project is only
compatible with Python 3.5, then use 3.5 respectively. If your project supports
both, you *could* run Bandit with both versions but you don't have to.
Bandit uses the `ast` module from Python's standard library in order to
analyze your Python code. The `ast` module is only able to parse Python code
that is valid in the version of the interpreter from which it is imported. In
other words, if you try to use Python 2.7's `ast` module to parse code written
for 3.5 that uses, for example, `yield from` with asyncio, then you'll have
syntax errors that will prevent Bandit from working properly. Alternatively,
if you are relying on 2.7's octal notation of `0777` then you'll have a syntax
error if you run Bandit on 3.x.
References
==========
Bandit wiki: https://wiki.openstack.org/wiki/Security/Projects/Bandit
Python AST module documentation: https://docs.python.org/2/library/ast.html
Green Tree Snakes - the missing Python AST docs:
https://greentreesnakes.readthedocs.org/en/latest/
Documentation of the various types of AST nodes that Bandit currently covers
or could be extended to cover:
https://greentreesnakes.readthedocs.org/en/latest/nodes.html
The contents of this repository are still available in the Git
source code management system. To see the contents of this
repository before it reached its end of life, please check out the
previous commit with "git checkout HEAD^1".

419
bandit.egg-info/PKG-INFO Normal file
View File

@ -0,0 +1,419 @@
Metadata-Version: 1.1
Name: bandit
Version: 1.4.1.dev43
Summary: Security oriented static analyser for python code.
Home-page: https://wiki.openstack.org/wiki/Security/Projects/Bandit
Author: OpenStack Security Group
Author-email: openstack-dev@lists.openstack.org
License: UNKNOWN
Description: Bandit
======
.. image:: https://governance.openstack.org/badges/bandit.svg
:target: https://governance.openstack.org/reference/tags/index.html
:alt: Bandit team and repository tags
.. image:: https://img.shields.io/pypi/v/bandit.svg
:target: https://pypi.python.org/pypi/bandit/
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/bandit.svg
:target: https://pypi.python.org/pypi/bandit/
:alt: Python Versions
.. image:: https://img.shields.io/pypi/format/bandit.svg
:target: https://pypi.python.org/pypi/bandit/
:alt: Format
.. image:: https://img.shields.io/badge/license-Apache%202-blue.svg
:target: https://git.openstack.org/cgit/openstack/bandit/plain/LICENSE
:alt: License
A security linter from OpenStack Security
* Free software: Apache license
* Documentation: https://wiki.openstack.org/wiki/Security/Projects/Bandit
* Source: https://git.openstack.org/cgit/openstack/bandit
* Bugs: https://bugs.launchpad.net/bandit
Overview
--------
Bandit is a tool designed to find common security issues in Python code. To do
this Bandit processes each file, builds an AST from it, and runs appropriate
plugins against the AST nodes. Once Bandit has finished scanning all the files
it generates a report.
Installation
------------
Bandit is distributed on PyPI. The best way to install it is with pip:
Create a virtual environment (optional)::
virtualenv bandit-env
Install Bandit::
pip install bandit
# Or if you're working with a Python 3.5 project
pip3.5 install bandit
Run Bandit::
bandit -r path/to/your/code
Bandit can also be installed from source. To do so, download the source tarball
from PyPI, then install it::
python setup.py install
Usage
-----
Example usage across a code tree::
bandit -r ~/openstack-repo/keystone
Example usage across the ``examples/`` directory, showing three lines of
context and only reporting on the high-severity issues::
bandit examples/*.py -n 3 -lll
Bandit can be run with profiles. To run Bandit against the examples directory
using only the plugins listed in the ``ShellInjection`` profile::
bandit examples/*.py -p ShellInjection
Bandit also supports passing lines of code to scan using standard input. To
run Bandit with standard input::
cat examples/imports.py | bandit -
Usage::
$ bandit -h
usage: bandit [-h] [-r] [-a {file,vuln}] [-n CONTEXT_LINES] [-c CONFIG_FILE]
[-p PROFILE] [-t TESTS] [-s SKIPS] [-l] [-i]
[-f {csv,html,json,screen,txt,xml,yaml}] [-o [OUTPUT_FILE]] [-v]
[-d] [--ignore-nosec] [-x EXCLUDED_PATHS] [-b BASELINE]
[--ini INI_PATH] [--version]
targets [targets ...]
Bandit - a Python source code security analyzer
positional arguments:
targets source file(s) or directory(s) to be tested
optional arguments:
-h, --help show this help message and exit
-r, --recursive find and process files in subdirectories
-a {file,vuln}, --aggregate {file,vuln}
aggregate output by vulnerability (default) or by
filename
-n CONTEXT_LINES, --number CONTEXT_LINES
maximum number of code lines to output for each issue
-c CONFIG_FILE, --configfile CONFIG_FILE
optional config file to use for selecting plugins and
overriding defaults
-p PROFILE, --profile PROFILE
profile to use (defaults to executing all tests)
-t TESTS, --tests TESTS
comma-separated list of test IDs to run
-s SKIPS, --skip SKIPS
comma-separated list of test IDs to skip
-l, --level report only issues of a given severity level or higher
(-l for LOW, -ll for MEDIUM, -lll for HIGH)
-i, --confidence report only issues of a given confidence level or
higher (-i for LOW, -ii for MEDIUM, -iii for HIGH)
-f {csv,html,json,screen,txt,xml,yaml}, --format {csv,html,json,screen,txt,xml,yaml}
specify output format
-o [OUTPUT_FILE], --output [OUTPUT_FILE]
write report to filename
-v, --verbose output extra information like excluded and included
files
-d, --debug turn on debug mode
--ignore-nosec do not skip lines with # nosec comments
-x EXCLUDED_PATHS, --exclude EXCLUDED_PATHS
comma-separated list of paths to exclude from scan
(note that these are in addition to the excluded paths
provided in the config file)
-b BASELINE, --baseline BASELINE
path of a baseline report to compare against (only
JSON-formatted files are accepted)
--ini INI_PATH path to a .bandit file that supplies command line
arguments
--version show program's version number and exit
The following tests were discovered and loaded:
B101 assert_used
B102 exec_used
B103 set_bad_file_permissions
B104 hardcoded_bind_all_interfaces
B105 hardcoded_password_string
B106 hardcoded_password_funcarg
B107 hardcoded_password_default
B108 hardcoded_tmp_directory
B109 password_config_option_not_marked_secret
B110 try_except_pass
B111 execute_with_run_as_root_equals_true
B112 try_except_continue
B201 flask_debug_true
B301 pickle
B302 marshal
B303 md5
B304 ciphers
B305 cipher_modes
B306 mktemp_q
B307 eval
B308 mark_safe
B309 httpsconnection
B310 urllib_urlopen
B311 random
B312 telnetlib
B313 xml_bad_cElementTree
B314 xml_bad_ElementTree
B315 xml_bad_expatreader
B316 xml_bad_expatbuilder
B317 xml_bad_sax
B318 xml_bad_minidom
B319 xml_bad_pulldom
B320 xml_bad_etree
B321 ftplib
B322 input
B323 unverified_context
B401 import_telnetlib
B402 import_ftplib
B403 import_pickle
B404 import_subprocess
B405 import_xml_etree
B406 import_xml_sax
B407 import_xml_expat
B408 import_xml_minidom
B409 import_xml_pulldom
B410 import_lxml
B411 import_xmlrpclib
B412 import_httpoxy
B501 request_with_no_cert_validation
B502 ssl_with_bad_version
B503 ssl_with_bad_defaults
B504 ssl_with_no_version
B505 weak_cryptographic_key
B506 yaml_load
B601 paramiko_calls
B602 subprocess_popen_with_shell_equals_true
B603 subprocess_without_shell_equals_true
B604 any_other_function_with_shell_equals_true
B605 start_process_with_a_shell
B606 start_process_with_no_shell
B607 start_process_with_partial_path
B608 hardcoded_sql_expressions
B609 linux_commands_wildcard_injection
B701 jinja2_autoescape_false
B702 use_of_mako_templates
Configuration
-------------
An optional config file may be supplied and may include:
- lists of tests which should or shouldn't be run
- exclude_dirs - sections of the path, that if matched, will be excluded from
scanning
- overridden plugin settings - may provide different settings for some
plugins
Per Project Command Line Args
-----------------------------
Projects may include a `.bandit` file that specifies command line arguments
that should be supplied for that project. The currently supported arguments
are:
- exclude: comma separated list of excluded paths
- skips: comma separated list of tests to skip
- tests: comma separated list of tests to run
To use this, put a .bandit file in your project's directory. For example:
::
[bandit]
exclude: /test
::
[bandit]
tests: B101,B102,B301
Exclusions
----------
In the event that a line of code triggers a Bandit issue, but that the line
has been reviewed and the issue is a false positive or acceptable for some
other reason, the line can be marked with a ``# nosec`` and any results
associated with it will not be reported.
For example, although this line may cause Bandit to report a potential
security issue, it will not be reported::
self.process = subprocess.Popen('/bin/echo', shell=True) # nosec
Vulnerability Tests
-------------------
Vulnerability tests or "plugins" are defined in files in the plugins directory.
Tests are written in Python and are autodiscovered from the plugins directory.
Each test can examine one or more type of Python statements. Tests are marked
with the types of Python statements they examine (for example: function call,
string, import, etc).
Tests are executed by the ``BanditNodeVisitor`` object as it visits each node
in the AST.
Test results are maintained in the ``BanditResultStore`` and aggregated for
output at the completion of a test run.
Writing Tests
-------------
To write a test:
- Identify a vulnerability to build a test for, and create a new file in
examples/ that contains one or more cases of that vulnerability.
- Consider the vulnerability you're testing for, mark the function with one
or more of the appropriate decorators:
- @checks('Call')
- @checks('Import', 'ImportFrom')
- @checks('Str')
- Create a new Python source file to contain your test, you can reference
existing tests for examples.
- The function that you create should take a parameter "context" which is
an instance of the context class you can query for information about the
current element being examined. You can also get the raw AST node for
more advanced use cases. Please see the context.py file for more.
- Extend your Bandit configuration file as needed to support your new test.
- Execute Bandit against the test file you defined in examples/ and ensure
that it detects the vulnerability. Consider variations on how this
vulnerability might present itself and extend the example file and the test
function accordingly.
Extending Bandit
----------------
Bandit allows users to write and register extensions for checks and formatters.
Bandit will load plugins from two entry-points:
- `bandit.formatters`
- `bandit.plugins`
Formatters need to accept 4 things:
- `result_store`: An instance of `bandit.core.BanditResultStore`
- `file_list`: The list of files which were inspected in the scope
- `scores`: The scores awarded to each file in the scope
- `excluded_files`: The list of files that were excluded from the scope
Plugins tend to take advantage of the `bandit.checks` decorator which allows
the author to register a check for a particular type of AST node. For example
::
@bandit.checks('Call')
def prohibit_unsafe_deserialization(context):
if 'unsafe_load' in context.call_function_name_qual:
return bandit.Issue(
severity=bandit.HIGH,
confidence=bandit.HIGH,
text="Unsafe deserialization detected."
)
To register your plugin, you have two options:
1. If you're using setuptools directly, add something like the following to
your ``setup`` call::
# If you have an imaginary bson formatter in the bandit_bson module
# and a function called `formatter`.
entry_points={'bandit.formatters': ['bson = bandit_bson:formatter']}
# Or a check for using mako templates in bandit_mako that
entry_points={'bandit.plugins': ['mako = bandit_mako']}
2. If you're using pbr, add something like the following to your `setup.cfg`
file::
[entry_points]
bandit.formatters =
bson = bandit_bson:formatter
bandit.plugins =
mako = bandit_mako
Contributing
------------
Contributions to Bandit are always welcome! We can be found on
#openstack-security on Freenode IRC.
The best way to get started with Bandit is to grab the source::
git clone https://git.openstack.org/openstack/bandit.git
You can test any changes with tox::
pip install tox
tox -e pep8
tox -e py27
tox -e py35
tox -e docs
tox -e cover
Reporting Bugs
--------------
Bugs should be reported on Launchpad. To file a bug against Bandit, visit:
https://bugs.launchpad.net/bandit/+filebug
Under Which Version of Python Should I Install Bandit?
------------------------------------------------------
The answer to this question depends on the project(s) you will be running
Bandit against. If your project is only compatible with Python 2.7, you
should install Bandit to run under Python 2.7. If your project is only
compatible with Python 3.5, then use 3.5 respectively. If your project supports
both, you *could* run Bandit with both versions but you don't have to.
Bandit uses the `ast` module from Python's standard library in order to
analyze your Python code. The `ast` module is only able to parse Python code
that is valid in the version of the interpreter from which it is imported. In
other words, if you try to use Python 2.7's `ast` module to parse code written
for 3.5 that uses, for example, `yield from` with asyncio, then you'll have
syntax errors that will prevent Bandit from working properly. Alternatively,
if you are relying on 2.7's octal notation of `0777` then you'll have a syntax
error if you run Bandit on 3.x.
References
==========
Bandit wiki: https://wiki.openstack.org/wiki/Security/Projects/Bandit
Python AST module documentation: https://docs.python.org/2/library/ast.html
Green Tree Snakes - the missing Python AST docs:
https://greentreesnakes.readthedocs.org/en/latest/
Documentation of the various types of AST nodes that Bandit currently covers
or could be extended to cover:
https://greentreesnakes.readthedocs.org/en/latest/nodes.html
Platform: UNKNOWN
Classifier: Environment :: OpenStack
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: System Administrators
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.5
Classifier: Topic :: Security

231
bandit.egg-info/SOURCES.txt Normal file
View File

@ -0,0 +1,231 @@
.coveragerc
.testr.conf
AUTHORS
ChangeLog
LICENSE
README.rst
pylintrc
requirements.txt
setup.cfg
setup.py
test-requirements.txt
tox.ini
bandit/__init__.py
bandit.egg-info/PKG-INFO
bandit.egg-info/SOURCES.txt
bandit.egg-info/dependency_links.txt
bandit.egg-info/entry_points.txt
bandit.egg-info/not-zip-safe
bandit.egg-info/pbr.json
bandit.egg-info/requires.txt
bandit.egg-info/top_level.txt
bandit/blacklists/__init__.py
bandit/blacklists/calls.py
bandit/blacklists/imports.py
bandit/blacklists/utils.py
bandit/cli/__init__.py
bandit/cli/baseline.py
bandit/cli/config_generator.py
bandit/cli/main.py
bandit/core/__init__.py
bandit/core/blacklisting.py
bandit/core/config.py
bandit/core/constants.py
bandit/core/context.py
bandit/core/docs_utils.py
bandit/core/extension_loader.py
bandit/core/issue.py
bandit/core/manager.py
bandit/core/meta_ast.py
bandit/core/metrics.py
bandit/core/node_visitor.py
bandit/core/test_properties.py
bandit/core/test_set.py
bandit/core/tester.py
bandit/core/utils.py
bandit/formatters/__init__.py
bandit/formatters/csv.py
bandit/formatters/html.py
bandit/formatters/json.py
bandit/formatters/screen.py
bandit/formatters/text.py
bandit/formatters/utils.py
bandit/formatters/xml.py
bandit/formatters/yaml.py
bandit/plugins/__init__.py
bandit/plugins/app_debug.py
bandit/plugins/asserts.py
bandit/plugins/crypto_request_no_cert_validation.py
bandit/plugins/exec.py
bandit/plugins/exec_as_root.py
bandit/plugins/general_bad_file_permissions.py
bandit/plugins/general_bind_all_interfaces.py
bandit/plugins/general_hardcoded_password.py
bandit/plugins/general_hardcoded_tmp.py
bandit/plugins/injection_paramiko.py
bandit/plugins/injection_shell.py
bandit/plugins/injection_sql.py
bandit/plugins/injection_wildcard.py
bandit/plugins/insecure_ssl_tls.py
bandit/plugins/jinja2_templates.py
bandit/plugins/mako_templates.py
bandit/plugins/secret_config_option.py
bandit/plugins/try_except_continue.py
bandit/plugins/try_except_pass.py
bandit/plugins/weak_cryptographic_key.py
bandit/plugins/yaml_load.py
doc/source/conf.py
doc/source/config.rst
doc/source/index.rst
doc/source/blacklists/blacklist_calls.rst
doc/source/blacklists/blacklist_imports.rst
doc/source/blacklists/index.rst
doc/source/formatters/csv.rst
doc/source/formatters/html.rst
doc/source/formatters/index.rst
doc/source/formatters/json.rst
doc/source/formatters/screen.rst
doc/source/formatters/text.rst
doc/source/formatters/xml.rst
doc/source/formatters/yaml.rst
doc/source/man/bandit.rst
doc/source/plugins/any_other_function_with_shell_equals_true.rst
doc/source/plugins/assert_used.rst
doc/source/plugins/exec_used.rst
doc/source/plugins/execute_with_run_as_root_equals_true.rst
doc/source/plugins/flask_debug_true.rst
doc/source/plugins/hardcoded_bind_all_interfaces.rst
doc/source/plugins/hardcoded_password_funcarg.rst
doc/source/plugins/hardcoded_password_funcdef.rst
doc/source/plugins/hardcoded_password_string.rst
doc/source/plugins/hardcoded_sql_expressions.rst
doc/source/plugins/hardcoded_tmp_directory.rst
doc/source/plugins/index.rst
doc/source/plugins/jinja2_autoescape_false.rst
doc/source/plugins/linux_commands_wildcard_injection.rst
doc/source/plugins/paramiko_calls.rst
doc/source/plugins/password_config_option_not_marked_secret.rst
doc/source/plugins/request_with_no_cert_validation.rst
doc/source/plugins/set_bad_file_permissions.rst
doc/source/plugins/ssl_with_bad_defaults.rst
doc/source/plugins/ssl_with_bad_version.rst
doc/source/plugins/ssl_with_no_version.rst
doc/source/plugins/start_process_with_a_shell.rst
doc/source/plugins/start_process_with_no_shell.rst
doc/source/plugins/start_process_with_partial_path.rst
doc/source/plugins/subprocess_popen_with_shell_equals_true.rst
doc/source/plugins/subprocess_without_shell_equals_true.rst
doc/source/plugins/try_except_continue.rst
doc/source/plugins/try_except_pass.rst
doc/source/plugins/use_of_mako_templates.rst
doc/source/plugins/weak_cryptographic_key.rst
doc/source/plugins/yaml_load.rst
examples/assert.py
examples/binding.py
examples/cipher-modes.py
examples/ciphers.py
examples/crypto-md5.py
examples/eval.py
examples/exec-as-root.py
examples/exec-py2.py
examples/exec-py3.py
examples/flask_debug.py
examples/ftplib.py
examples/hardcoded-passwords.py
examples/hardcoded-tmp.py
examples/httplib_https.py
examples/httpoxy_cgihandler.py
examples/httpoxy_twisted_directory.py
examples/httpoxy_twisted_script.py
examples/imports-aliases.py
examples/imports-from.py
examples/imports-function.py
examples/imports.py
examples/input.py
examples/jinja2_templating.py
examples/mako_templating.py
examples/mark_safe.py
examples/marshal_deserialize.py
examples/mktemp.py
examples/multiline_statement.py
examples/new_candidates-all.py
examples/new_candidates-none.py
examples/new_candidates-nosec.py
examples/new_candidates-some.py
examples/nonsense.py
examples/nonsense2.py
examples/nosec.py
examples/okay.py
examples/os-chmod-py2.py
examples/os-chmod-py3.py
examples/os-exec.py
examples/os-popen.py
examples/os-spawn.py
examples/os-startfile.py
examples/os_system.py
examples/paramiko_injection.py
examples/partial_path_process.py
examples/pickle_deserialize.py
examples/popen_wrappers.py
examples/random_module.py
examples/requests-ssl-verify-disabled.py
examples/secret-config-option.py
examples/skip.py
examples/sql_statements.py
examples/ssl-insecure-version.py
examples/subprocess_shell.py
examples/telnetlib.py
examples/try_except_continue.py
examples/try_except_pass.py
examples/unverified_context.py
examples/urlopen.py
examples/utils-shell.py
examples/weak_cryptographic_key_sizes.py
examples/wildcard-injection.py
examples/xml_etree_celementtree.py
examples/xml_etree_elementtree.py
examples/xml_expatbuilder.py
examples/xml_expatreader.py
examples/xml_lxml.py
examples/xml_minidom.py
examples/xml_pulldom.py
examples/xml_sax.py
examples/xml_xmlrpc.py
examples/yaml_load.py
releasenotes/notes/add_reno-b8585fc3ffe775cb.yaml
releasenotes/source/conf.py
releasenotes/source/index.rst
releasenotes/source/unreleased.rst
releasenotes/source/_static/.placeholder
releasenotes/source/_templates/.placeholder
scripts/integration-test.sh
scripts/main.py
tests/__init__.py
tests/functional/__init__.py
tests/functional/test_baseline.py
tests/functional/test_functional.py
tests/functional/test_runtime.py
tests/unit/__init__.py
tests/unit/cli/__init__.py
tests/unit/cli/test_baseline.py
tests/unit/cli/test_config_generator.py
tests/unit/cli/test_main.py
tests/unit/core/__init__.py
tests/unit/core/test_blacklisting.py
tests/unit/core/test_config.py
tests/unit/core/test_context.py
tests/unit/core/test_issue.py
tests/unit/core/test_manager.py
tests/unit/core/test_meta_ast.py
tests/unit/core/test_test_set.py
tests/unit/core/test_util.py
tests/unit/formatters/__init__.py
tests/unit/formatters/test_csv.py
tests/unit/formatters/test_html.py
tests/unit/formatters/test_json.py
tests/unit/formatters/test_screen.py
tests/unit/formatters/test_text.py
tests/unit/formatters/test_xml.py
tests/unit/formatters/test_yaml.py
tools/openstack_coverage.py
tools/tox_install.sh

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,50 @@
[bandit.blacklists]
calls = bandit.blacklists.calls:gen_blacklist
imports = bandit.blacklists.imports:gen_blacklist
[bandit.formatters]
csv = bandit.formatters.csv:report
html = bandit.formatters.html:report
json = bandit.formatters.json:report
screen = bandit.formatters.screen:report
txt = bandit.formatters.text:report
xml = bandit.formatters.xml:report
yaml = bandit.formatters.yaml:report
[bandit.plugins]
any_other_function_with_shell_equals_true = bandit.plugins.injection_shell:any_other_function_with_shell_equals_true
assert_used = bandit.plugins.asserts:assert_used
exec_used = bandit.plugins.exec:exec_used
execute_with_run_as_root_equals_true = bandit.plugins.exec_as_root:execute_with_run_as_root_equals_true
flask_debug_true = bandit.plugins.app_debug:flask_debug_true
hardcoded_bind_all_interfaces = bandit.plugins.general_bind_all_interfaces:hardcoded_bind_all_interfaces
hardcoded_password_default = bandit.plugins.general_hardcoded_password:hardcoded_password_default
hardcoded_password_funcarg = bandit.plugins.general_hardcoded_password:hardcoded_password_funcarg
hardcoded_password_string = bandit.plugins.general_hardcoded_password:hardcoded_password_string
hardcoded_sql_expressions = bandit.plugins.injection_sql:hardcoded_sql_expressions
hardcoded_tmp_directory = bandit.plugins.general_hardcoded_tmp:hardcoded_tmp_directory
jinja2_autoescape_false = bandit.plugins.jinja2_templates:jinja2_autoescape_false
linux_commands_wildcard_injection = bandit.plugins.injection_wildcard:linux_commands_wildcard_injection
paramiko_calls = bandit.plugins.injection_paramiko:paramiko_calls
password_config_option_not_marked_secret = bandit.plugins.secret_config_option:password_config_option_not_marked_secret
request_with_no_cert_validation = bandit.plugins.crypto_request_no_cert_validation:request_with_no_cert_validation
set_bad_file_permissions = bandit.plugins.general_bad_file_permissions:set_bad_file_permissions
ssl_with_bad_defaults = bandit.plugins.insecure_ssl_tls:ssl_with_bad_defaults
ssl_with_bad_version = bandit.plugins.insecure_ssl_tls:ssl_with_bad_version
ssl_with_no_version = bandit.plugins.insecure_ssl_tls:ssl_with_no_version
start_process_with_a_shell = bandit.plugins.injection_shell:start_process_with_a_shell
start_process_with_no_shell = bandit.plugins.injection_shell:start_process_with_no_shell
start_process_with_partial_path = bandit.plugins.injection_shell:start_process_with_partial_path
subprocess_popen_with_shell_equals_true = bandit.plugins.injection_shell:subprocess_popen_with_shell_equals_true
subprocess_without_shell_equals_true = bandit.plugins.injection_shell:subprocess_without_shell_equals_true
try_except_continue = bandit.plugins.try_except_continue:try_except_continue
try_except_pass = bandit.plugins.try_except_pass:try_except_pass
use_of_mako_templates = bandit.plugins.mako_templates:use_of_mako_templates
weak_cryptographic_key = bandit.plugins.weak_cryptographic_key:weak_cryptographic_key
yaml_load = bandit.plugins.yaml_load:yaml_load
[console_scripts]
bandit = bandit.cli.main:main
bandit-baseline = bandit.cli.baseline:main
bandit-config-generator = bandit.cli.config_generator:main

View File

@ -0,0 +1 @@

1
bandit.egg-info/pbr.json Normal file
View File

@ -0,0 +1 @@
{"git_version": "d54a65f", "is_release": false}

View File

@ -0,0 +1,4 @@
GitPython>=1.0.1
PyYAML>=3.10
six>=1.9.0
stevedore>=1.20.0

View File

@ -0,0 +1 @@
bandit

View File

@ -1,163 +0,0 @@
# Copyright (c) 2017 Hewlett Packard Enterprise
# -*- coding:utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
r"""
================
Custom Formatter
================
This formatter outputs the issues in custom machine-readable format.
default template: {abspath}:{line}: {test_id}[bandit]: {severity}: {msg}
:Example:
/usr/lib/python3.6/site-packages/openlp/core/utils/__init__.py: \
405: B310[bandit]: MEDIUM: Audit url open for permitted schemes. \
Allowing use of file:/ or custom schemes is often unexpected.
"""
import logging
import os
import re
import string
import sys
from bandit.core import test_properties
LOG = logging.getLogger(__name__)
class SafeMapper(dict):
"""Safe mapper to handle format key errors"""
@classmethod # To prevent PEP8 warnings in the test suite
def __missing__(cls, key):
return "{%s}" % key
@test_properties.accepts_baseline
def report(manager, fileobj, sev_level, conf_level, lines=-1, template=None):
"""Prints issues in custom format
:param manager: the bandit manager object
:param fileobj: The output file object, which may be sys.stdout
:param sev_level: Filtering severity level
:param conf_level: Filtering confidence level
:param lines: Number of lines to report, -1 for all
:param template: Output template with non-terminal tags <N>
(default: '{abspath}:{line}:
{test_id}[bandit]: {severity}: {msg}')
"""
machine_output = {'results': [], 'errors': []}
for (fname, reason) in manager.get_skipped():
machine_output['errors'].append({'filename': fname,
'reason': reason})
results = manager.get_issue_list(sev_level=sev_level,
conf_level=conf_level)
msg_template = template
if template is None:
msg_template = "{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}"
# Dictionary of non-terminal tags that will be expanded
tag_mapper = {
'abspath': lambda issue: os.path.abspath(issue.fname),
'relpath': lambda issue: os.path.relpath(issue.fname),
'line': lambda issue: issue.lineno,
'test_id': lambda issue: issue.test_id,
'severity': lambda issue: issue.severity,
'msg': lambda issue: issue.text,
'confidence': lambda issue: issue.confidence,
'range': lambda issue: issue.linerange
}
# Create dictionary with tag sets to speed up search for similar tags
tag_sim_dict = dict(
[(tag, set(tag)) for tag, _ in tag_mapper.items()]
)
# Parse the format_string template and check the validity of tags
try:
parsed_template_orig = list(string.Formatter().parse(msg_template))
# of type (literal_text, field_name, fmt_spec, conversion)
# Check the format validity only, ignore keys
string.Formatter().vformat(msg_template, (), SafeMapper(line=0))
except ValueError as e:
LOG.error("Template is not in valid format: %s", e.args[0])
sys.exit(2)
tag_set = {t[1] for t in parsed_template_orig if t[1] is not None}
if not tag_set:
LOG.error("No tags were found in the template. Are you missing '{}'?")
sys.exit(2)
def get_similar_tag(tag):
similarity_list = [(len(set(tag) & t_set), t)
for t, t_set in tag_sim_dict.items()]
return sorted(similarity_list)[-1][1]
tag_blacklist = []
for tag in tag_set:
# check if the tag is in dictionary
if tag not in tag_mapper:
similar_tag = get_similar_tag(tag)
LOG.warning(
"Tag '%s' was not recognized and will be skipped, "
"did you mean to use '%s'?", tag, similar_tag
)
tag_blacklist += [tag]
# Compose the message template back with the valid values only
msg_parsed_template_list = []
for literal_text, field_name, fmt_spec, conversion in parsed_template_orig:
if literal_text:
# if there is '{' or '}', double it to prevent expansion
literal_text = re.sub('{', '{{', literal_text)
literal_text = re.sub('}', '}}', literal_text)
msg_parsed_template_list.append(literal_text)
if field_name is not None:
if field_name in tag_blacklist:
msg_parsed_template_list.append(field_name)
continue
# Append the fmt_spec part
params = [field_name, fmt_spec, conversion]
markers = ['', ':', '!']
msg_parsed_template_list.append(
['{'] +
["%s" % (m + p) if p else ''
for m, p in zip(markers, params)] +
['}']
)
msg_parsed_template = "".join([item for lst in msg_parsed_template_list
for item in lst]) + "\n"
limit = lines if lines > 0 else None
with fileobj:
for defect in results[:limit]:
evaluated_tags = SafeMapper(
(k, v(defect)) for k, v in tag_mapper.items()
)
output = msg_parsed_template.format(**evaluated_tags)
fileobj.write(output)
if fileobj.name != sys.stdout.name:
LOG.info("Result written to file: %s", fileobj.name)

View File

@ -1,63 +0,0 @@
# -*- coding:utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
r"""
==========================================================================
B324: Test for use of insecure md4 and md5 hash functions in hashlib.new()
==========================================================================
This plugin checks for the usage of the insecure MD4 and MD5 hash functions
in ``hashlib.new`` function. The ``hashlib.new`` function provides the ability
to construct a new hashing object using the named algorithm. This can be used
to create insecure hash functions like MD4 and MD5 if they are passed as
algorithm names to this function.
This is similar to B303 blacklist check, except that this checks for insecure
hash functions created using ``hashlib.new`` function.
:Example:
>> Issue: [B324:hashlib_new] Use of insecure MD4 or MD5 hash function.
Severity: Medium Confidence: High
Location: examples/hashlib_new_insecure_funcs.py:3
2
3 md5_hash = hashlib.new('md5', string='test')
4 print(md5_hash)
.. versionadded:: 1.5.0
"""
import bandit
from bandit.core import test_properties as test
@test.test_id('B324')
@test.checks('Call')
def hashlib_new(context):
if isinstance(context.call_function_name_qual, str):
qualname_list = context.call_function_name_qual.split('.')
func = qualname_list[-1]
if 'hashlib' in qualname_list and func == 'new':
args = context.call_args
keywords = context.call_keywords
name = args[0] if args else keywords['name']
if name.lower() in ('md4', 'md5'):
return bandit.Issue(
severity=bandit.MEDIUM,
confidence=bandit.HIGH,
text="Use of insecure MD4 or MD5 hash function.",
lineno=context.node.lineno,
)

View File

@ -1,2 +0,0 @@
# This is a cross-platform list tracking distribution packages needed by tests;
# see http://docs.openstack.org/infra/bindep/ for additional information.

View File

@ -55,25 +55,20 @@ Deserialization with the marshal module is possibly dangerous.
B303: md5
---------
Use of insecure MD2, MD4, MD5, or SHA1 hash function.
Use of insecure MD2, MD4, or MD5 hash function.
+------+---------------------+------------------------------------+-----------+
| ID | Name | Calls | Severity |
+======+=====================+====================================+===========+
| B303 | md5 | - hashlib.md5 | Medium |
| | | - hashlib.sha1 | |
| | | - Crypto.Hash.MD2.new | |
| | | - Crypto.Hash.MD4.new | |
| | | - Crypto.Hash.MD5.new | |
| | | - Crypto.Hash.SHA.new | |
| | | - Cryptodome.Hash.MD2.new | |
| | | - Cryptodome.Hash.MD4.new | |
| | | - Cryptodome.Hash.MD5.new | |
| | | - Cryptodome.Hash.SHA.new | |
| | | - cryptography.hazmat.primitives | |
| | | .hashes.MD5 | |
| | | - cryptography.hazmat.primitives | |
| | | .hashes.SHA1 | |
+------+---------------------+------------------------------------+-----------+
B304 - B305: ciphers and modes
@ -294,7 +289,7 @@ behavior that does not validate certificates or perform hostname checks.
+------+---------------------+------------------------------------+-----------+
| ID | Name | Calls | Severity |
+======+=====================+====================================+===========+
| B323 | unverified_context | - ssl._create_unverified_context | Medium |
| B322 | unverified_context | - ssl._create_unverified_context | Medium |
+------+---------------------+------------------------------------+-----------+
"""
@ -334,18 +329,14 @@ def gen_blacklist():
sets.append(utils.build_conf_dict(
'md5', 'B303',
['hashlib.md5',
'hashlib.sha1',
'Crypto.Hash.MD2.new',
'Crypto.Hash.MD4.new',
'Crypto.Hash.MD5.new',
'Crypto.Hash.SHA.new',
'Cryptodome.Hash.MD2.new',
'Cryptodome.Hash.MD4.new',
'Cryptodome.Hash.MD5.new',
'Cryptodome.Hash.SHA.new',
'cryptography.hazmat.primitives.hashes.MD5',
'cryptography.hazmat.primitives.hashes.SHA1'],
'Use of insecure MD2, MD4, MD5, or SHA1 hash function.'
'cryptography.hazmat.primitives.hashes.MD5'],
'Use of insecure MD2, MD4, or MD5 hash function.'
))
sets.append(utils.build_conf_dict(

View File

@ -179,26 +179,6 @@ at https://httpoxy.org/.
| | | - twisted.web.twcgi.CGIScript | |
+------+---------------------+------------------------------------+-----------+
B413: import_pycrypto
---------------------
pycrypto library is known to have publicly disclosed buffer overflow
vulnerability https://github.com/dlitz/pycrypto/issues/176. It is no longer
actively maintained and has been deprecated in favor of pyca/cryptography
library.
+------+---------------------+------------------------------------+-----------+
| ID | Name | Imports | Severity |
+======+=====================+====================================+===========+
| B413 | import_pycrypto | - Crypto.Cipher | high |
| | | - Crypto.Hash | |
| | | - Crypto.IO | |
| | | - Crypto.Protocol | |
| | | - Crypto.PublicKey | |
| | | - Crypto.Random | |
| | | - Crypto.Signature | |
| | | - Crypto.Util | |
+------+---------------------+------------------------------------+-----------+
"""
from bandit.blacklists import utils
@ -288,18 +268,4 @@ def gen_blacklist():
'{name} module.', 'HIGH'
))
sets.append(utils.build_conf_dict(
'import_pycrypto', 'B413',
['Crypto.Cipher',
'Crypto.Hash',
'Crypto.IO',
'Crypto.Protocol',
'Crypto.PublicKey',
'Crypto.Random',
'Crypto.Signature',
'Crypto.Util'],
'The pyCrypto library and its module {name} are no longer actively '
'maintained and have been deprecated. '
'Consider using pyca/cryptography library.', 'HIGH'))
return {'Import': sets, 'ImportFrom': sets, 'Call': sets}

View File

@ -18,7 +18,6 @@ import fnmatch
import logging
import os
import sys
import textwrap
import bandit
@ -98,7 +97,7 @@ def _log_option_source(arg_val, ini_val, option_name):
LOG.info("Using command line arg for %s", option_name)
return arg_val
elif ini_val:
LOG.info("Using ini file for %s", option_name)
LOG.info("Using .bandit arg for %s", option_name)
return ini_val
else:
return None
@ -151,7 +150,7 @@ def main():
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'targets', metavar='targets', type=str, nargs='*',
'targets', metavar='targets', type=str, nargs='+',
help='source file(s) or directory(s) to be tested'
)
parser.add_argument(
@ -206,13 +205,6 @@ def main():
default=output_format, help='specify output format',
choices=sorted(extension_mgr.formatter_names)
)
parser.add_argument(
'--msg-template', action='store',
default=None, help='specify output message template'
' (only usable with --format custom),'
' see CUSTOM FORMAT section'
' for list of available values',
)
parser.add_argument(
'-o', '--output', dest='output_file', action='store', nargs='?',
type=argparse.FileType('w'), default=sys.stdout,
@ -261,41 +253,11 @@ def main():
blacklist_info.append('%s\t%s' % (b['id'], b['name']))
plugin_list = '\n\t'.join(sorted(set(plugin_info + blacklist_info)))
dedent_text = textwrap.dedent('''
CUSTOM FORMATTING
-----------------
Available tags:
{abspath}, {relpath}, {line}, {test_id},
{severity}, {msg}, {confidence}, {range}
Example usage:
Default template:
bandit -r examples/ --format custom --msg-template \\
"{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}"
Provides same output as:
bandit -r examples/ --format custom
Tags can also be formatted in python string.format() style:
bandit -r examples/ --format custom --msg-template \\
"{relpath:20.20s}: {line:03}: {test_id:^8}: DEFECT: {msg:>20}"
See python documentation for more information about formatting style:
https://docs.python.org/3.4/library/string.html
The following tests were discovered and loaded:
-----------------------------------------------
''')
parser.epilog = dedent_text + "\t{0}".format(plugin_list)
parser.epilog = ('The following tests were discovered and'
' loaded:\n\t{0}\n'.format(plugin_list))
# setup work - parse arguments, and initialize BanditManager
args = parser.parse_args()
# Check if `--msg-template` is not present without custom formatter
if args.output_format != 'custom' and args.msg_template is not None:
parser.error("--msg-template can only be used with --format=custom")
try:
b_conf = b_config.BanditConfig(config_file=args.config_file)
@ -316,16 +278,8 @@ def main():
args.tests = _log_option_source(args.tests, ini_options.get('tests'),
'selected tests')
ini_targets = ini_options.get('targets')
if ini_targets:
ini_targets = ini_targets.split(',')
args.targets = _log_option_source(args.targets, ini_targets,
'selected targets')
# TODO(tmcpeak): any other useful options to pass from .bandit?
if not args.targets:
LOG.error("No targets found in CLI or ini files, exiting.")
sys.exit(2)
# if the log format string was set in the options, reinitialize
if b_conf.get_option('log_format'):
log_format = b_conf.get_option('log_format')
@ -387,8 +341,7 @@ def main():
sev_level,
conf_level,
args.output_file,
args.output_format,
args.msg_template)
args.output_format)
# return an exit code of 1 if there are results, 0 otherwise
if b_mgr.results_count(sev_filter=sev_level, conf_filter=conf_level) > 0:

View File

@ -53,10 +53,6 @@ def blacklist(context, config):
name = "" # handle '__import__()'
else:
name = context.call_function_name_qual
# In the case the Call is an importlib.import, treat the first
# argument name as an actual import module name.
if name in ["importlib.import_module", "importlib.__import__"]:
name = context.call_args[0]
for check in blacklists[node_type]:
for qn in check['qualnames']:
if fnmatch.fnmatch(name, qn):

View File

@ -49,8 +49,7 @@ class BanditConfig(object):
try:
self._config = yaml.safe_load(f)
self.validate(config_file)
except yaml.YAMLError as err:
LOG.error(err)
except yaml.YAMLError:
raise utils.ConfigError("Error parsing file.", config_file)
# valid config must be a dict

View File

@ -15,7 +15,7 @@
# under the License.
# where our docs are hosted
BASE_URL = 'https://docs.openstack.org/bandit/latest/'
BASE_URL = 'https://docs.openstack.org/developer/bandit/'
def get_url(bid):
@ -24,12 +24,11 @@ def get_url(bid):
# later though.
from bandit.core import extension_loader
info = extension_loader.MANAGER.plugins_by_id.get(bid)
info = extension_loader.MANAGER.plugins_by_id.get(bid, None)
if info is not None:
return '%splugins/%s_%s.html' % (BASE_URL, bid.lower(),
info.plugin.__name__)
return BASE_URL + ('plugins/%s.html' % info.plugin.__name__)
info = extension_loader.MANAGER.blacklist_by_id.get(bid)
info = extension_loader.MANAGER.blacklist_by_id.get(bid, None)
if info is not None:
template = 'blacklists/blacklist_{kind}.html#{id}-{name}'
info['name'] = info['name'].replace('_', '-')

View File

@ -136,7 +136,7 @@ class BanditManager(object):
return len(self.get_issue_list(sev_filter, conf_filter))
def output_results(self, lines, sev_level, conf_level, output_file,
output_format, template=None):
output_format):
'''Outputs results from the result store
:param lines: How many surrounding lines to show per result
@ -144,9 +144,6 @@ class BanditManager(object):
:param conf_level: Which confidence levels to show (LOW, MEDIUM, HIGH)
:param output_file: File to store results
:param output_format: output format plugin name
:param template: Output template with non-terminal tags <N>
(default: {abspath}:{line}:
{test_id}[bandit]: {severity}: {msg})
:return: -
'''
try:
@ -156,13 +153,8 @@ class BanditManager(object):
formatter = formatters_mgr[output_format]
report_func = formatter.plugin
if output_format == 'custom':
report_func(self, fileobj=output_file, sev_level=sev_level,
conf_level=conf_level, lines=lines,
template=template)
else:
report_func(self, fileobj=output_file, sev_level=sev_level,
conf_level=conf_level, lines=lines)
report_func(self, fileobj=output_file, sev_level=sev_level,
conf_level=conf_level, lines=lines)
except Exception as e:
raise RuntimeError("Unable to output report using '%s' formatter: "

View File

@ -151,7 +151,7 @@ def get_module_qualname_from_path(path):
' Missing path or file name' % (path))
qname = [os.path.splitext(tail)[0]]
while head not in ['/', '.', '']:
while head not in ['/', '.']:
if os.path.isfile(os.path.join(head, '__init__.py')):
(head, tail) = os.path.split(head)
qname.insert(0, tail)

View File

@ -125,9 +125,9 @@ This formatter outputs the issues as HTML.
<b>Confidence: </b>HIGH<br>
<b>File: </b><a href="examples/yaml_load.py"
target="_blank">examples/yaml_load.py</a> <br>
<b>More info: </b><a href="https://docs.openstack.org/bandit/latest/
<b>More info: </b><a href="https://docs.openstack.org/developer/bandit/
plugins/yaml_load.html" target="_blank">
https://docs.openstack.org/bandit/latest/plugins/yaml_load.html</a>
https://docs.openstack.org/developer/bandit/plugins/yaml_load.html</a>
<br>
<div class="code">

View File

@ -65,7 +65,6 @@ This formatter outputs the issues in JSON.
"line_range": [
5
],
"more_info": "https://docs.openstack.org/bandit/latest/",
"test_name": "blacklist_calls",
"test_id": "B301"
}
@ -85,7 +84,6 @@ import logging
import operator
import sys
from bandit.core import docs_utils
from bandit.core import test_properties
LOG = logging.getLogger(__name__)
@ -116,15 +114,12 @@ def report(manager, fileobj, sev_level, conf_level, lines=-1):
collector = []
for r in results:
d = r.as_dict()
d['more_info'] = docs_utils.get_url(d['test_id'])
if len(results[r]) > 1:
d['candidates'] = [c.as_dict() for c in results[r]]
collector.append(d)
else:
collector = [r.as_dict() for r in results]
for elem in collector:
elem['more_info'] = docs_utils.get_url(elem['test_id'])
itemgetter = operator.itemgetter
if manager.agg_type == 'vuln':

View File

@ -60,7 +60,6 @@ This formatter outputs the issues in a yaml format.
line_number: 6
line_range:
- 6
more_info: https://docs.openstack.org/bandit/latest/
test_id: B506
test_name: yaml_load
@ -78,8 +77,6 @@ import sys
import yaml
from bandit.core import docs_utils
LOG = logging.getLogger(__name__)
@ -101,8 +98,6 @@ def report(manager, fileobj, sev_level, conf_level, lines=-1):
conf_level=conf_level)
collector = [r.as_dict() for r in results]
for elem in collector:
elem['more_info'] = docs_utils.get_url(elem['test_id'])
itemgetter = operator.itemgetter
if manager.agg_type == 'vuln':

View File

@ -375,7 +375,7 @@ def start_process_with_a_shell(context, config):
invocation is dangerous as it is vulnerable to various shell injection
attacks. Great care should be taken to sanitize all input in order to
mitigate this risk. Calls of this type are identified by the use of certain
commands which are known to use shells. Bandit will report a LOW
commands which are known to use shells. Bandit will report a MEDIUM
severity warning.
See also:
@ -418,7 +418,7 @@ def start_process_with_a_shell(context, config):
.. code-block:: none
>> Issue: Starting a process with a shell: check for injection.
Severity: Low Confidence: Medium
Severity: Medium Confidence: Medium
Location: examples/os_system.py:3
2
3 os.system('/bin/echo hi')

View File

@ -47,16 +47,13 @@ false. A HIGH severity warning is generated in either of these scenarios.
14
>> Issue: By default, jinja2 sets autoescape to False. Consider using
autoescape=True or use the select_autoescape function to mitigate XSS
vulnerabilities.
autoescape=True to mitigate XSS vulnerabilities.
Severity: High Confidence: High
Location: ./examples/jinja2_templating.py:15
14
15 Environment(loader=templateLoader,
16 load=templateLoader)
17
18 Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),
19 loader=templateLoader)
.. seealso::
@ -96,19 +93,13 @@ def jinja2_autoescape_false(context):
confidence=bandit.HIGH,
text="Using jinja2 templates with autoescape="
"False is dangerous and can lead to XSS. "
"Use autoescape=True or use the "
"select_autoescape function to mitigate XSS "
"Use autoescape=True to mitigate XSS "
"vulnerabilities."
)
# found autoescape
if getattr(node, 'arg', None) == 'autoescape':
value = getattr(node, 'value', None)
if (getattr(value, 'id', None) == 'True' or
getattr(value, 'value', None) is True):
return
# Check if select_autoescape function is used.
elif isinstance(value, ast.Call) and getattr(
value.func, 'id', None) == 'select_autoescape':
if (getattr(node.value, 'id', None) == 'True' or
getattr(node.value, 'value', None) is True):
return
else:
return bandit.Issue(
@ -116,9 +107,8 @@ def jinja2_autoescape_false(context):
confidence=bandit.MEDIUM,
text="Using jinja2 templates with autoescape="
"False is dangerous and can lead to XSS. "
"Ensure autoescape=True or use the "
"select_autoescape function to mitigate "
"XSS vulnerabilities."
"Ensure autoescape=True to mitigate XSS "
"vulnerabilities."
)
# We haven't found a keyword named autoescape, indicating default
# behavior
@ -126,6 +116,5 @@ def jinja2_autoescape_false(context):
severity=bandit.HIGH,
confidence=bandit.HIGH,
text="By default, jinja2 sets autoescape to False. Consider "
"using autoescape=True or use the select_autoescape "
"function to mitigate XSS vulnerabilities."
"using autoescape=True to mitigate XSS vulnerabilities."
)

View File

@ -1,7 +0,0 @@
# The order of packages is significant, because pip processes them in the order
# of appearance. Changing the order has an impact on the overall integration
# process, which may cause wedges in the gate later.
openstackdocstheme>=1.18.1 # Apache-2.0
sphinx!=1.6.6,!=1.6.7,>=1.6.2 # BSD
reno>=2.5.0 # Apache-2.0
oslosphinx>=4.7.0 # Apache-2.0

View File

@ -1,5 +0,0 @@
---------------
blacklist_calls
---------------
.. automodule:: bandit.blacklists.calls

View File

@ -1,5 +0,0 @@
-----------------
blacklist_imports
-----------------
.. automodule:: bandit.blacklists.imports

View File

@ -1,69 +0,0 @@
Bandit Blacklist Plugins
========================
Bandit supports built in functionality to implement blacklisting of imports and
function calls, this functionality is provided by built in test 'B001'. This
test may be filtered as per normal plugin filtering rules.
The exact calls and imports that are blacklisted, and the issues reported, are
controlled by plugin methods with the entry point 'bandit.blacklists' and can
be extended by third party plugins if desired. Blacklist plugins will be
discovered by Bandit at startup and called. The returned results are combined
into the final data set, subject to Bandit's normal test include/exclude rules
allowing for fine grained control over blacklisted items. By convention,
blacklisted calls should have IDs in the B3xx range and imports should have IDs
in the B4xx range.
Plugin functions should return a dictionary mapping AST node types to
lists of blacklist data. Currently the following node types are supported:
- Call, used for blacklisting calls.
- Import, used for blacklisting module imports (this also implicitly tests
ImportFrom and Call nodes where the invoked function is Pythons built in
'__import__()' method).
Items in the data lists are Python dictionaries with the following structure:
+-------------+----------------------------------------------------+
| key | data meaning |
+=============+====================================================+
| 'name' | The issue name string. |
+-------------+----------------------------------------------------+
| 'id' | The bandit ID of the check, this must be unique |
| | and is used for filtering blacklist checks. |
+-------------+----------------------------------------------------+
| 'qualnames' | A Python list of fully qualified name strings. |
+-------------+----------------------------------------------------+
| 'message' | The issue message reported, this is a string that |
| | may contain the token '{name}' that will be |
| | substituted with the matched qualname in the final |
| | report. |
+-------------+----------------------------------------------------+
| 'level' | The severity level reported. |
+-------------+----------------------------------------------------+
A utility method bandit.blacklists.utils.build_conf_dict is provided to aid
building these dictionaries.
:Example:
.. code-block:: none
>> Issue: [B317:blacklist] Using xml.sax.parse to parse untrusted XML data
is known to be vulnerable to XML attacks. Replace xml.sax.parse with its
defusedxml equivalent function.
Severity: Medium Confidence: High
Location: ./examples/xml_sax.py:24
23 sax.parseString(xmlString, ExampleContentHandler())
24 sax.parse('notaxmlfilethatexists.xml', ExampleContentHandler)
25
Complete Plugin Listing
-----------------------
.. toctree::
:maxdepth: 1
:glob:
*
.. versionadded:: 0.17.0

View File

@ -1,88 +0,0 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc',
# 'sphinx.ext.intersphinx',
'oslosphinx'
]
# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Bandit'
copyright = u'2016, OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
modindex_common_prefix = ['bandit.']
#-- Options for man page output --------------------------------------------
# Grouping the document tree for man pages.
# List of tuples 'sourcefile', 'target', u'title', u'Authors name', 'manual'
man_pages = [
('man/bandit', 'bandit', u'Python source code security analyzer',
[u'OpenStack Security Group'], 1)
]
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme_path = ["."]
# html_theme = '_theme'
# html_static_path = ['static']
html_theme_options = {}
# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % project
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index',
'%s.tex' % project,
u'%s Documentation' % project,
u'OpenStack Foundation', 'manual'),
]
# Example configuration for intersphinx: refer to the Python standard library.
# intersphinx_mapping = {'http://docs.python.org/': None}

View File

@ -1,82 +0,0 @@
Configuration
=============
Bandit is designed to be configurable and cover a wide range of needs, it may
be used as either a local developer utility or as part of a full CI/CD
pipeline. To provide for these various usage scenarios bandit can be configured
via a `YAML <http://yaml.org/>`_ file. This file is completely optional and in
many cases not needed, it may be specified on the command line by using `-c`.
A bandit configuration file may choose the specific test plugins to run and
override the default configurations of those tests. An example config might
look like the following:
.. code-block:: yaml
### profile may optionally select or skip tests
# (optional) list included tests here:
tests: ['B201', 'B301']
# (optional) list skipped tests here:
skips: ['B101', 'B601']
### override settings - used to set settings for plugins to non-default values
any_other_function_with_shell_equals_true:
no_shell: [os.execl, os.execle, os.execlp, os.execlpe, os.execv, os.execve,
os.execvp, os.execvpe, os.spawnl, os.spawnle, os.spawnlp, os.spawnlpe,
os.spawnv, os.spawnve, os.spawnvp, os.spawnvpe, os.startfile]
shell: [os.system, os.popen, os.popen2, os.popen3, os.popen4,
popen2.popen2, popen2.popen3, popen2.popen4, popen2.Popen3,
popen2.Popen4, commands.getoutput, commands.getstatusoutput]
subprocess: [subprocess.Popen, subprocess.call, subprocess.check_call,
subprocess.check_output,
utils.execute, utils.execute_with_timeout]
If you require several sets of tests for specific tasks, then you should create
several config files and pick from them using `-c`. If you only wish to control
the specific tests that are to be run (and not their parameters) then using
`-s` or `-t` on the command line may be more appropriate.
Skipping Tests
--------------
The bandit config may contain optional lists of test IDs to either include
(`tests`) or exclude (`skips`). These lists are equivalent to using `-t` and
`-s` on the command line. If only `tests` is given then bandit will include
only those tests, effectively excluding all other tests. If only `skips`
is given then bandit will include all tests not in the skips list. If both are
given then bandit will include only tests in `tests` and then remove `skips`
from that set. It is an error to include the same test ID in both `tests` and
`skips`.
Note that command line options `-t`/`-s` can still be used in conjunction with
`tests` and `skips` given in a config. The result is to concatenate `-t` with
`tests` and likewise for `-s` and `skips` before working out the tests to run.
Generating a Config
-------------------
Bandit ships the tool `bandit-config-generator` designed to take the leg work
out of configuration. This tool can generate a configuration file
automatically. The generated configuration will include default config blocks
for all detected test and blacklist plugins. This data can then be deleted or
edited as needed to produce a minimal config as desired. The config generator
supports `-t` and `-s` command line options to specify a list of test IDs that
should be included or excluded respectively. If no options are given then the
generated config will not include `tests` or `skips` sections (but will provide
a complete list of all test IDs for reference when editing).
Configuring Test Plugins
------------------------
Bandit's configuration file is written in `YAML <http://yaml.org/>`_ and options
for each plugin test are provided under a section named to match the test
method. For example, given a test plugin called 'try_except_pass' its
configuration section might look like the following:
.. code-block:: yaml
try_except_pass:
check_typed_exception: True
The specific content of the configuration block is determined by the plugin
test itself. See the `plugin test list <plugins/index.html>`_ for complete
information on configuring each one.

View File

@ -1,5 +0,0 @@
---
csv
---
.. automodule:: bandit.formatters.csv

View File

@ -1,5 +0,0 @@
----
html
----
.. automodule:: bandit.formatters.html

View File

@ -1,42 +0,0 @@
Bandit Report Formatters
========================
Bandit supports many different formatters to output various security issues in
python code. These formatters are created as plugins and new ones can be
created to extend the functionality offered by bandit today.
Example Formatter
-----------------
.. code-block:: python
def report(manager, fileobj, sev_level, conf_level, lines=-1):
result = bson.dumps(issues)
with fileobj:
fileobj.write(result)
To register your plugin, you have two options:
1. If you're using setuptools directly, add something like the following to
your `setup` call::
# If you have an imaginary bson formatter in the bandit_bson module
# and a function called `formatter`.
entry_points={'bandit.formatters': ['bson = bandit_bson:formatter']}
2. If you're using pbr, add something like the following to your `setup.cfg`
file::
[entry_points]
bandit.formatters =
bson = bandit_bson:formatter
Complete Formatter Listing
----------------------------
.. toctree::
:maxdepth: 1
:glob:
*

View File

@ -1,5 +0,0 @@
----
json
----
.. automodule:: bandit.formatters.json

View File

@ -1,5 +0,0 @@
------
screen
------
.. automodule:: bandit.formatters.screen

View File

@ -1,5 +0,0 @@
----
text
----
.. automodule:: bandit.formatters.text

View File

@ -1,5 +0,0 @@
---
xml
---
.. automodule:: bandit.formatters.xml

View File

@ -1,5 +0,0 @@
----
yaml
----
.. automodule:: bandit.formatters.yaml

View File

@ -1,27 +0,0 @@
Welcome to Bandit's developer documentation!
============================================
Bandit is a tool designed to find common security issues in Python code. To do
this, Bandit processes each file, builds an AST from it, and runs appropriate
plugins against the AST nodes. Once Bandit has finished scanning all the files,
it generates a report.
This documentation is generated by the Sphinx toolkit and lives in the source
tree.
Getting Started
===============
.. toctree::
:maxdepth: 1
config
plugins/index
blacklists/index
formatters/index
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -1,128 +0,0 @@
======
bandit
======
SYNOPSIS
========
bandit [-h] [-r] [-a {file,vuln}] [-n CONTEXT_LINES] [-c CONFIG_FILE]
[-p PROFILE] [-t TESTS] [-s SKIPS] [-l] [-i]
[-f {csv,custom,html,json,screen,txt,xml,yaml}]
[--msg-template MSG_TEMPLATE] [-o OUTPUT_FILE] [-v] [-d]
[--ignore-nosec] [-x EXCLUDED_PATHS] [-b BASELINE]
[--ini INI_PATH] [--version]
targets [targets ...]
DESCRIPTION
===========
``bandit`` is a tool designed to find common security issues in Python code. To
do this Bandit processes each file, builds an AST from it, and runs appropriate
plugins against the AST nodes. Once Bandit has finished scanning all the files
it generates a report.
OPTIONS
=======
-h, --help show this help message and exit
-r, --recursive find and process files in subdirectories
-a {file,vuln}, --aggregate {file,vuln}
aggregate output by vulnerability (default) or by
filename
-n CONTEXT_LINES, --number CONTEXT_LINES
maximum number of code lines to output for each issue
-c CONFIG_FILE, --configfile CONFIG_FILE
optional config file to use for selecting plugins and
overriding defaults
-p PROFILE, --profile PROFILE
profile to use (defaults to executing all tests)
-t TESTS, --tests TESTS
comma-separated list of test IDs to run
-s SKIPS, --skip SKIPS
comma-separated list of test IDs to skip
-l, --level report only issues of a given severity level or higher
(-l for LOW, -ll for MEDIUM, -lll for HIGH)
-i, --confidence report only issues of a given confidence level or
higher (-i for LOW, -ii for MEDIUM, -iii for HIGH)
-f {csv,custom,html,json,screen,txt,xml,yaml}, --format {csv,custom,html,json,screen,txt,xml,yaml}
specify output format
--msg-template MSG_TEMPLATE
specify output message template (only usable with
--format custom), see CUSTOM FORMAT section for list
of available values
-o OUTPUT_FILE, --output OUTPUT_FILE
write report to filename
-v, --verbose output extra information like excluded and included
files
-d, --debug turn on debug mode
--ignore-nosec do not skip lines with # nosec comments
-x EXCLUDED_PATHS, --exclude EXCLUDED_PATHS
comma-separated list of paths to exclude from scan
(note that these are in addition to the excluded paths
provided in the config file)
-b BASELINE, --baseline BASELINE
path of a baseline report to compare against (only
JSON-formatted files are accepted)
--ini INI_PATH path to a .bandit file that supplies command line
arguments
--version show program's version number and exit
CUSTOM FORMATTING
-----------------
Available tags:
{abspath}, {relpath}, {line}, {test_id},
{severity}, {msg}, {confidence}, {range}
Example usage:
Default template:
bandit -r examples/ --format custom --msg-template \
"{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}"
Provides same output as:
bandit -r examples/ --format custom
Tags can also be formatted in python string.format() style:
bandit -r examples/ --format custom --msg-template \
"{relpath:20.20s}: {line:03}: {test_id:^8}: DEFECT: {msg:>20}"
See python documentation for more information about formatting style:
https://docs.python.org/3.4/library/string.html
FILES
=====
.bandit
file that supplies command line arguments
/etc/bandit/bandit.yaml
legacy bandit configuration file
EXAMPLES
========
Example usage across a code tree::
bandit -r ~/openstack-repo/keystone
Example usage across the ``examples/`` directory, showing three lines of
context and only reporting on the high-severity issues::
bandit examples/*.py -n 3 -lll
Bandit can be run with profiles. To run Bandit against the examples directory
using only the plugins listed in the ShellInjection profile::
bandit examples/*.py -p ShellInjection
Bandit also supports passing lines of code to scan using standard input. To
run Bandit with standard input::
cat examples/imports.py | bandit -
SEE ALSO
========
pylint(1)

View File

@ -1,5 +0,0 @@
-----------------
B101: assert_used
-----------------
.. automodule:: bandit.plugins.asserts

View File

@ -1,5 +0,0 @@
---------------
B102: exec_used
---------------
.. automodule:: bandit.plugins.exec

View File

@ -1,5 +0,0 @@
------------------------------
B103: set_bad_file_permissions
------------------------------
.. automodule:: bandit.plugins.general_bad_file_permissions

View File

@ -1,5 +0,0 @@
-----------------------------------
B104: hardcoded_bind_all_interfaces
-----------------------------------
.. automodule:: bandit.plugins.general_bind_all_interfaces

View File

@ -1,8 +0,0 @@
-------------------------------
B105: hardcoded_password_string
-------------------------------
.. currentmodule:: bandit.plugins.general_hardcoded_password
.. autofunction:: hardcoded_password_string
:noindex:

View File

@ -1,8 +0,0 @@
--------------------------------
B106: hardcoded_password_funcarg
--------------------------------
.. currentmodule:: bandit.plugins.general_hardcoded_password
.. autofunction:: hardcoded_password_funcarg
:noindex:

View File

@ -1,8 +0,0 @@
--------------------------------
B107: hardcoded_password_default
--------------------------------
.. currentmodule:: bandit.plugins.general_hardcoded_password
.. autofunction:: hardcoded_password_default
:noindex:

View File

@ -1,5 +0,0 @@
-----------------------------
B108: hardcoded_tmp_directory
-----------------------------
.. automodule:: bandit.plugins.general_hardcoded_tmp

View File

@ -1,5 +0,0 @@
----------------------------------------------
B109: password_config_option_not_marked_secret
----------------------------------------------
.. automodule:: bandit.plugins.secret_config_option

Some files were not shown because too many files have changed in this diff Show More