Automated security testing using bandit and flake8.

Overview

flake8-bandit

Build Status

Automated security testing built right into your workflow!

You already use flake8 to lint all your code for errors, ensure docstrings are formatted correctly, sort your imports correctly, and much more... so why not ensure you are writing secure code while you're at it? If you already have flake8 installed all it takes is pip install flake8-bandit.

Configuration

To include or exclude tests, use the standard .bandit configuration file. An example valid .bandit config file:

[bandit]
exclude = /frontend,/scripts,/tests,/venv
tests: B101

In this case, we've specified to ignore a number of paths, and to only test for B101.

Note: flake8-bugbear uses bandit default prefix 'B' so this plugin replaces the 'B' with an 'S' for Security. For more information, see https://github.com/PyCQA/flake8-bugbear/issues/37

How's it work?

We use the bandit package from PyCQA for all the security testing.

Comments
  • Bandit 1.7.3 addition of new positional argument ``fdata`` causes ``TypeError``

    Bandit 1.7.3 addition of new positional argument ``fdata`` causes ``TypeError``

    I've been using the flake8-bandit plugin. But recently, a new positional argument fdata was recently added to the BanditNodeVisitor function in version 1.7.3, causing a TypeError as follows

    multiprocessing.pool.RemoteTraceback: 
    """
    Traceback (most recent call last):
      File "/mnt/home/liurenmi/software/anaconda3/envs/geneplexus/lib/python3.8/multiprocessing/pool.py", line 125, in worker
        result = (True, func(*args, **kwds))
      File "/mnt/ufs18/home-026/liurenmi/repo/GeneplexusPublic/.tox/flake8/lib/python3.8/site-packages/flake8/checker.py", line 687, in _run_checks
        return checker.run_checks()
      File "/mnt/ufs18/home-026/liurenmi/repo/GeneplexusPublic/.tox/flake8/lib/python3.8/site-packages/flake8/checker.py", line 597, in run_checks
        self.run_ast_checks()
      File "/mnt/ufs18/home-026/liurenmi/repo/GeneplexusPublic/.tox/flake8/lib/python3.8/site-packages/flake8/checker.py", line 500, in run_ast_checks
        for (line_number, offset, text, _) in runner:
      File "/mnt/ufs18/home-026/liurenmi/repo/GeneplexusPublic/.tox/flake8/lib/python3.8/site-packages/flake8_bandit.py", line 85, in run
        for warn in self._check_source():
      File "/mnt/ufs18/home-026/liurenmi/repo/GeneplexusPublic/.tox/flake8/lib/python3.8/site-packages/flake8_bandit.py", line 59, in _check_source
        bnv = BanditNodeVisitor(
    TypeError: __init__() missing 1 required positional argument: 'metrics'
    """
    

    Would it be possible to make a patch for this?

    opened by RemyLau 21
  • ConfigFileFinder is removed from flake8

    ConfigFileFinder is removed from flake8

    https://github.com/tylerwince/flake8-bandit/blob/4043bc51fcb2327da4b0ae82cab3b7a4a8bdbe87/flake8_bandit.py#L10

    This flake8 commit removed it.

    There are a few things from flake8's head that I need, but I'd also like to use flake8-bandit, so this is a bit of a pickle for me

    opened by wyuenho 7
  • "'ExceptHandler' object has no attribute 'depth'"

    With Python 3.7 on Ubuntu 16.04, flake8-bandit will fail on the following test script:

    def test():
        try:
            a = A()
            a = A()
        except A:
            pass
    

    with the following output:

    "pyflakes" failed during execution due to "'ExceptHandler' object has no attribute 'depth'"
    Run flake8 with greater verbosity to see more details
    

    Verbose doesn't help with finding out any additional info: https://hastebin.com/suxebuxebo.txt

    This issue only occurs with flake8-bandit installed, and occurs with all versions after 1.0.2. Pinning to 1.0.2 does not cause the same issue, but this isn't a great resolution.

    I have tried reproducing the issue on an arch based environment without luck, as it only seems to occur on Ubuntu 16.04.

    opened by scragly 7
  • fix: refactor from ConfigFileFinder to load_config

    fix: refactor from ConfigFileFinder to load_config

    Attempt at fixing https://github.com/tylerwince/flake8-bandit/issues/33 by refactoring from flake8<5.0.0's ConfigFileFinder to flake8>=5.0.0,<6.0.0's load_config.

    opened by lsorber 6
  • Incorrect choice of encoding Cyrillic characters resulting in UnicodeDecodeError

    Incorrect choice of encoding Cyrillic characters resulting in UnicodeDecodeError

    Description

    I have:

    • Windows 10
    • Clean conda Python 3.6 env

    I ran pip install flake8-bandit

    and got Successfully installed GitPython-2.1.11 PyYAML-3.13 bandit-1.5.1 flake8-3.5.0 flake8-bandit-1.0.2 flake8-polyfill-1.0.2 gitdb2-2.0.4 mccabe-0.6.1 pbr-4.3.0 pycodestyle-2.3.1 pyflakes-1.6.0 six-1.11.0 smmap2-2.0.4 stevedore-1.29.0

    I have a Python module with the following contents:

    # -*- coding: UTF-8 -*-
    """Module docstring."""
    print('hello') # э
    

    I run flake8 C:\Development\Flake8PluginDev\foo.py

    an error is produced.

    (BanditDebug) C:\Users\user>flake8 C:\Development\Flake8PluginDev\foo.py
    Traceback (most recent call last):
      File "c:\anaconda3\envs\banditdebug\lib\runpy.py", line 193, in _run_module_as_main
        "__main__", mod_spec)
      File "c:\anaconda3\envs\banditdebug\lib\runpy.py", line 85, in _run_code
        exec(code, run_globals)
      File "C:\Anaconda3\envs\BanditDebug\Scripts\flake8.exe\__main__.py", line 9, in <module>
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\main\cli.py", line 16, in main
        app.run(argv)
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\main\application.py", line 396, in run
        self._run(argv)
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\main\application.py", line 384, in _run
        self.run_checks()
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\main\application.py", line 310, in run_checks
        self.file_checker_manager.run()
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\checker.py", line 321, in run
        self.run_serial()
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\checker.py", line 305, in run_serial
        checker.run_checks()
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\checker.py", line 579, in run_checks
        self.run_ast_checks()
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\checker.py", line 486, in run_ast_checks
        checker = self.run_check(plugin, tree=ast)
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8\checker.py", line 435, in run_check
        return plugin['plugin'](**arguments)
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8_bandit.py", line 35, in __init__
        self._load_source()
      File "c:\anaconda3\envs\banditdebug\lib\site-packages\flake8_bandit.py", line 73, in _load_source
        self.source = f.read()
      File "c:\anaconda3\envs\banditdebug\lib\encodings\cp1252.py", line 23, in decode
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 68: character maps to <undefined>
    

    To Reproduce

    If I have

    # -*- coding: UTF-8 -*-
    """Module docstring."""
    print('hello') # й
    

    I run flake8 C:\Development\Flake8PluginDev\foo.py

    and get C:\Development\Flake8PluginDev\foo.py:3:15: E261 at least two spaces before inline comment

    It works fine.

    Now if we change the Cyrillic # й comment into either the # э, # я, or # с (with all three characters typed with Russian keyboard layout, mind Russian C) and run flake8 C:\Development\Flake8PluginDev\foo.py

    an error is produced.

    It seems as bandit has problems with only three Russian letters эяс because when running the flake8 with the comment containing all Russian letters except эяс, it works fine:

    # -*- coding: UTF-8 -*-
    """Module docstring."""
    print('hello') # йцукенгшщзхъфывапролджё
    

    Expected behavior Bandit should handle all Cyrillic characters without throwing UnicodeDecodeError error.

    Bandit version

    (BanditDebug) C:\Users\user>bandit --version
    bandit 1.5.1
      python version = 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 11:21:07) [MSC v.1900 32 bit (Intel)]
    
    flake8          3.5.0
    flake8-bandit   1.0.2
    
    opened by AlexArcPy 6
  • support all options in .bandit

    support all options in .bandit

    • Updated flake8-bandit to support all .bandit config options including targets and excludes
    • cache config parsing so it can be re-used as needed

    Breaking change:

    • python >= 3.6 required

    I'm using a number of more modern python features, could of course rewrite with older methods but wanted to write the simple way first unless there are objections; for most projects I've worked on and other frequently used tools, it seems like python 3.6 is a reasonable minimum version (black, pydantic, etc).

    Implements additional features as discussed in #3

    opened by shapiromatron 5
  • Clean up config file for Travis.

    Clean up config file for Travis.

    • remove obsolete "sudo" keyword
    • remove old dev versions
    • remove matrix

    modified: .travis.yml

    P.S.: As I never used the "allow_failures" directive before, I am not sure whether I used the correct syntax (outside matrix). If not, I'll update the pr.

    opened by jugmac00 4
  • [Request] Would it be possible to make a new release to PyPI?

    [Request] Would it be possible to make a new release to PyPI?

    I have noticed that the project currently says it is on version 4.1.0, and there is a tag and GitHub release with the same name, but there hasn't been a release on PyPI since 3.0.0.

    There seems to be a release CI setup, but it hasnt really worked from a quick look at the past runs. I will try to see the following days anything needs to be done to fix it (if its even broken).

    Making this quick issue to bring it to your attention :)

    opened by davfsa 3
  • Make flake8-bandit work with latest bandit 1.7.3 too

    Make flake8-bandit work with latest bandit 1.7.3 too

    Fixes: #21

    flake8-bandit 1.7.3 (PyCQA/bandit#496) introduced an fdata argument and this just passes a None to make things work with the latest version of bandit.

    opened by sathieu 3
  • This plugin fails to parse files with unicode on windows

    This plugin fails to parse files with unicode on windows

    Reproduction steps:

    1. Use windows
    2. Install flake8-bandit
    3. Create a python file with print('Привет, бандиты!') unicode contents
    4. Try to run flake8 your_file.py

    It will fail with something like this:

    c:\users\appveyor\appdata\local\pypoetry\cache\virtualenvs\wemake-python-styleguide-py3.6\lib\site-packages\flake8\checker.py:451: in run_check
        return plugin["plugin"](**arguments)
    c:\users\appveyor\appdata\local\pypoetry\cache\virtualenvs\wemake-python-styleguide-py3.6\lib\site-packages\flake8_bandit.py:35: in __init__
        self._load_source()
    c:\users\appveyor\appdata\local\pypoetry\cache\virtualenvs\wemake-python-styleguide-py3.6\lib\site-packages\flake8_bandit.py:73: in _load_source
        self.source = f.read()
    C:\Python36\lib\encodings\cp1252.py:23: in decode
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    E   UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 14170: character maps to <undefined>
    

    Original issue: https://github.com/wemake-services/wemake-python-styleguide/issues/337 Log: https://ci.appveyor.com/project/wemake-services/wemake-python-styleguide/build/job/185lp386ce91jtsy

    help wanted 
    opened by sobolevn 3
  • Change plugin prefix to not conflict with Bugbear

    Change plugin prefix to not conflict with Bugbear

    Bugbear is an official PyCQA plugin for flake8 that's been around for several years.

    Your new plugin shadows the letter B and in fact deregisters Bugbear if used in the same configuration.

    Please choose a new non-conflicting prefix for your plugin.

    For reference, see: https://github.com/PyCQA/flake8-bugbear/issues/37

    opened by ambv 3
  • flake8 5 breaks plugin no attribute ConfigFileFinder

    flake8 5 breaks plugin no attribute ConfigFileFinder

    File "/home/runner/work/renault-api/renault-api/.nox/pre-commit/lib/python3.10/site-packages/flake8_bandit.py", line 10, in <module>
        from flake8.options.config import ConfigFileFinder
    
    opened by epenet 1
  • Different results in different Python versions (S303 vs. S324)

    Different results in different Python versions (S303 vs. S324)

    Hello,

    the following code leads to different error codes, depending on the Python version:

    import hashlib
    
    h = hashlib.md5()
    

    Python 3.8:

    example.py:3:1: S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.
    

    Python 3.9:

    example.py:3:1: S324 Use of weak MD4, MD5, or SHA1 hash for security. Consider usedforsecurity=False
    

    Python 3.10:

    example.py:3:1: S324 Use of weak MD4, MD5, or SHA1 hash for security. Consider usedforsecurity=False
    

    The installed package versions seems to be equal:

    $ python --version
    Python 3.8.10
    
    $ flake8 --version
    4.0.1 (flake8-bandit: 3.0.0, mccabe: 0.6.1, pycodestyle: 2.8.0, pyflakes: 2.4.0) CPython 3.8.10 on Linux
    
    $ pip list
    Package         Version
    --------------- -------
    bandit          1.7.4
    flake8          4.0.1
    flake8-bandit   3.0.0
    flake8-polyfill 1.0.2
    gitdb           4.0.9
    GitPython       3.1.27
    mccabe          0.6.1
    pbr             5.9.0
    pip             22.1
    pkg_resources   0.0.0
    pycodestyle     2.8.0
    pyflakes        2.4.0
    PyYAML          6.0
    setuptools      62.3.0
    smmap           5.0.0
    stevedore       3.5.0
    
    $ python --version
    Python 3.9.1
    
    $ flake8 --version
    4.0.1 (flake8-bandit: 3.0.0, mccabe: 0.6.1, pycodestyle: 2.8.0, pyflakes: 2.4.0) CPython 3.9.1 on Linux
    
    $ pip list
    Package         Version
    --------------- -------
    bandit          1.7.4
    flake8          4.0.1
    flake8-bandit   3.0.0
    flake8-polyfill 1.0.2
    gitdb           4.0.9
    GitPython       3.1.27
    mccabe          0.6.1
    pbr             5.9.0
    pip             22.1
    pycodestyle     2.8.0
    pyflakes        2.4.0
    PyYAML          6.0
    setuptools      62.3.0
    smmap           5.0.0
    stevedore       3.5.0
    
    $ python --version           
    Python 3.10.2
    
    $ flake8 --version
    4.0.1 (flake8-bandit: 3.0.0, mccabe: 0.6.1, pycodestyle: 2.8.0, pyflakes: 2.4.0) CPython 3.10.2 on Linux
    
    $ pip list
    Package         Version
    --------------- -------
    bandit          1.7.4
    flake8          4.0.1
    flake8-bandit   3.0.0
    flake8-polyfill 1.0.2
    gitdb           4.0.9
    GitPython       3.1.27
    mccabe          0.6.1
    pbr             5.9.0
    pip             22.1
    pycodestyle     2.8.0
    pyflakes        2.4.0
    PyYAML          6.0
    setuptools      62.3.0
    smmap           5.0.0
    stevedore       3.5.0
    

    Any idea what's going on here? Is it a flake8-bandit issue or a bandit one?

    Thanks a lot!

    fin swimmer

    opened by finswimmer 1
  • Unable to find qualified name for module: file.py

    Unable to find qualified name for module: file.py

    Hi,

    since version 3.0.0, I get a the error Unable to find qualified name for module: file.py. when I run flake8.

    How to reproduce

    • Directory Structure:
    test/
    └── file.py
    

    file.py:

    import numpy as np
    
    print("Oh no!")
    
    • Expected Result:
    > flake8 .
    ./file.py:1:1: F401 'numpy as np' imported but unused
    

    running flake8 . actually works:

    • Actual Result:
    > flake8 file.py
    Unable to find qualified name for module: file.py
    file.py:1:1: F401 'numpy as np' imported but unuse
    

    Running flake8 file.py does not work. As you can see, flake8 throws Unable to find qualified name for module: file.py.

    • Additional Informations:
      • when I remove flake8-bandit from my environment, the error disappears
      • I'm using flake8 4.0.1 and flake8-bandit 3.0.0.

    I'm looking forward to your reply.

    C

    opened by cgahr 1
  • Support `nosec` comments

    Support `nosec` comments

    Currently if one wants to skip a bandit message for "raw" bandit checks (using the bandit executable) in addition to ones done via flake8-bandit, both the noqa and nosec comments need to be used. For example:

    assert True  # noqa: S101 # nosec: B101
    

    The noqa: S101 is required for flake8 to not flag the use of assert, but that's not enough for "raw" bandit. For that the nosec: B101 is needed. But that has no effect on flake8-bandit, so both are needed.

    Would be good if the nosec comment was enough for both, maybe flake8-bandit can do something about it?

    opened by scop 0
Owner
Tyler Wince
SVP Product @myndshft
Tyler Wince
Utilities for pycharm code formatting (flake8 and black)

Pycharm External Tools Extentions to Pycharm code formatting tools. Currently supported are flake8 and black on a selected code block. Usage Flake8 [P

Haim Daniel 13 Nov 3, 2022
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 2.6k Jan 3, 2023
❄️ A flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Adam Johnson 398 Dec 23, 2022
Flake8 plugin that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

Python Code Quality Authority 270 Nov 24, 2022
Flake8 extension for checking quotes in python

Flake8 Extension to lint for quotes. Major update in 2.0.0 We automatically encourage avoiding escaping quotes as per PEP 8. To disable this, use --no

Zachary Heller 157 Dec 13, 2022
flake8 plugin that integrates isort

Flake8 meet isort Use isort to check if the imports on your python files are sorted the way you expect. Add an .isort.cfg to define how you want your

Gil Forcada Codinachs 139 Nov 8, 2022
Flake8 plugin to find commented out or dead code

flake8-eradicate flake8 plugin to find commented out (or so called "dead") code. This is quite important for the project in a long run. Based on eradi

wemake.services 277 Dec 27, 2022
Flake8 wrapper to make it nice, legacy-friendly, configurable.

THE PROJECT IS ARCHIVED Forks: https://github.com/orsinium/forks It's a Flake8 wrapper to make it cool. Lint md, rst, ipynb, and more. Shareable and r

Life4 232 Dec 16, 2022
flake8 plugin to run black for checking Python coding style

flake8-black Introduction This is an MIT licensed flake8 plugin for validating Python code style with the command line code formatting tool black. It

Peter Cock 146 Dec 15, 2022
A plugin for flake8 integrating Mypy.

flake8-mypy NOTE: THIS PROJECT IS DEAD It was created in early 2017 when Mypy performance was often insufficient for in-editor linting. The Flake8 plu

Łukasz Langa 103 Jun 23, 2022
A plugin for Flake8 that checks pandas code

pandas-vet pandas-vet is a plugin for flake8 that provides opinionated linting for pandas code. It began as a project during the PyCascades 2019 sprin

Jacob Deppen 146 Dec 28, 2022
Flake8 extension for enforcing trailing commas in python

Flake8 Extension to enforce better comma placement. Usage If you are using flake8 it's as easy as: pip install flake8-commas Now you can avoid those a

Python Code Quality Authority 127 Sep 3, 2022
Tool to automatically fix some issues reported by flake8 (forked from autoflake).

autoflake8 Introduction autoflake8 removes unused imports and unused variables from Python code. It makes use of pyflakes to do this. autoflake8 also

francisco souza 27 Sep 8, 2022
flake8 plugin to catch useless `assert` statements

flake8-useless-assert flake8 plugin to catch useless assert statements Download or install on the PyPI page Violations Code Description Example ULA001

null 1 Feb 12, 2022
Flake8 extension to provide force-check option

flake8-force Flake8 extension to provide force-check option. When this option is enabled, flake8 performs all checks even if the target file cannot be

Kenichi Maehashi 9 Oct 29, 2022
Pylint plugin for improving code analysis for when using Django

pylint-django About pylint-django is a Pylint plugin for improving code analysis when analysing code using Django. It is also used by the Prospector t

Python Code Quality Authority 544 Jan 6, 2023
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 14.4k Jan 8, 2023
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 2.1k Jan 1, 2023
coala provides a unified command-line interface for linting and fixing all your code, regardless of the programming languages you use.

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." ― John F. Woods coala provides a

coala development group 3.4k Dec 29, 2022