Github: https://github.com/openstack/bandit
強盗
OpenStack Securityのセキュリティリンター
- フリーソフトウェア:Apacheライセンス
- ドキュメント: https : //wiki.openstack.org/wiki/Security/Projects/Bandit
- ソース: https : //git.openstack.org/cgit/openstack/bandit
- バグ: https : //bugs.launchpad.net/bandit
概要
Banditは、Pythonコードで共通のセキュリティ問題を見つけるために設計されたツールです。 これを行うために、Banditは各ファイルを処理し、そこからASTを作成し、ASTノードに対して適切なプラグインを実行します。 Banditはすべてのファイルのスキャンを完了すると、レポートを生成します。
インストール
BanditはPyPI上で配布されます。 それをインストールする最善の方法はpipです:
仮想環境を作成する(オプション):
virtualenv bandit-env
バンディットをインストールする:
pip install bandit # Or if you're working with a Python 3.5 project pip3.5 install bandit
バンディットを実行する:
bandit -r path/to/your/code
Banditはソースからインストールすることもできます。 これを行うには、PyPIからソースtarballをダウンロードし、それをインストールします:
python setup.py install
使用法
コードツリー全体での使用例:
bandit -r ~/openstack-repo/keystone
examples/
ディレクトリ全体の使用examples/
。3行のコンテキストを示し、重大度の高い問題のみを報告します。
bandit examples/*.py -n 3 -lll
強盗は、プロファイルで実行することができます。 ShellInjection
プロファイルにリストされているプラグインのみを使用して、 ShellInjection
ディレクトリに対してBanditを実行するには:
bandit examples/*.py -p ShellInjection
Banditは、標準入力を使用してスキャンするコード行を渡すこともサポートしています。 Banditを標準入力で実行するには:
cat examples/imports.py | bandit -
使用法:
$ 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
構成
- オプションの設定ファイルが提供されてもよく、以下を含んでもよい。
-
- 実行すべきまたは実行すべきでないテストのリスト
- exclude_dirs – 一致した場合、スキャンから除外されるパスのセクション
- オーバーライドされたプラグイン設定 – いくつかのプラグインに対して異なる設定を提供する可能性があります
プロジェクトごとのコマンドライン引数
プロジェクトには、そのプロジェクトに提供するコマンドライン引数を指定する.banditファイルが含まれている場合があります。 現在サポートされている引数は次のとおりです。
- targets:山賊を実行するターゲットディレクトリ/ファイルのカンマ区切りリスト
- exclude:除外されたパスのカンマ区切りリスト
- スキップ:コンマで区切られたテストのリスト
- tests:実行するテストのカンマ区切りリスト
これを使用するには、。banditファイルをプロジェクトのディレクトリに配置します。 例えば:
[bandit] exclude: /test
[bandit] tests: B101,B102,B301
除外
コード行がBanditの問題を引き起こすが、その行がレビューされ、問題が他の理由で偽陽性または許容可能である場合、その行に# nosec
というマークを# nosec
ことができます。報告されない。
たとえば、この行はBanditに潜在的なセキュリティ問題を報告する可能性がありますが、報告されません。
self.process = subprocess.Popen('/bin/echo', shell=True) # nosec
脆弱性テスト
脆弱性テストまたは “プラグイン”は、pluginsディレクトリのファイルに定義されています。
テストはPythonで書かれ、pluginsディレクトリから自動検出されます。 各テストでは、1つ以上のタイプのPython文を調べることができます。 テストには、調べるPython文のタイプ(たとえば、関数呼び出し、文字列、インポートなど)が表示されます。
テストはBanditNodeVisitor
オブジェクトによって実行され、ASTの各ノードを訪問します。
テスト結果はBanditResultStore
保持され、テスト実行の完了時に出力用に集約されます。
テストの作成
- テストを書くには:
-
- サンプルを作成するための脆弱性を特定し、その脆弱性の1つ以上のケースを含むexamples /に新しいファイルを作成します。
- @checks( ‘Call’) – @checks( ‘Import’、 ‘ImportFrom’) – @checks( ‘Str’)あなたがテストしている脆弱性を考慮して、適切なデコレータの1つ以上で関数に印を付けます。
- あなたのテストを含む新しいPythonソースファイルを作成すると、既存のテストの例を参照することができます。
- 作成する関数は、現在の要素の情報を問い合わせることができるコンテキストクラスのインスタンスである “context”パラメータを取る必要があります。 さらに進んだユースケースについては、生のASTノードを取得することもできます。 詳細については、context.pyファイルを参照してください。
- 必要に応じてBandit設定ファイルを拡張して、新しいテストをサポートします。
- examples /で定義したテストファイルに対してBanditを実行し、脆弱性を検出したことを確認します。 この脆弱性がどのように現れる可能性があるかについてのバリエーションを検討し、それに応じてサンプルファイルとテスト関数を拡張してください。
強盗を広げる
Banditは、ユーザーが小切手や書式設定のための内線番号を作成して登録することを可能にします。 Banditは2つのエントリーポイントからプラグインをロードします:
- bandit.formatters
- bandit.plugins
フォーマッタは4つのことを受け入れる必要があります:
- result_store:bandit.core.BanditResultStoreのインスタンス
- file_list:スコープ内で検査されたファイルのリスト
- スコア:スコープ内の各ファイルに付与されたスコア
- excluded_files:スコープから除外されたファイルのリスト
プラグインはbandit.checksデコレータを利用する傾向があります。デコレータは、特定のタイプのASTノードのチェックを登録者に登録させることができます。 例えば
@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." )
プラグインを登録するには、2つの方法があります:
-
setuptoolsを直接使用している場合は、次のようなものを
setup
呼び出しに追加します。# 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']}
-
pbrを使用している場合は、setup.cfgファイルに次のようなものを追加します。
[entry_points] bandit.formatters = bson = bandit_bson:formatter bandit.plugins = mako = bandit_mako
貢献する
強盗への貢献はいつでも歓迎です! Freenode IRCの#openstack-securityにあります。
Banditを使い始める最善の方法は、ソースを取得することです。
git clone https://git.openstack.org/openstack/bandit.git
toxを使って変更をテストすることができます:
pip install tox tox -e pep8 tox -e py27 tox -e py35 tox -e docs tox -e cover
バグの報告
バグはLaunchpadで報告する必要があります。 Banditにバグを報告するには、 https : //bugs.launchpad.net/bandit/+filebugをご覧ください。
BanditをインストールするPythonのバージョン
この質問に対する答えは、あなたがBanditを実行するプロジェクトに依存します。 あなたのプロジェクトがPython 2.7としか互換性がない場合は、Python 2.7で動作するようにBanditをインストールする必要があります。 プロジェクトがPython 3.5のみと互換性がある場合は、それぞれ3.5を使用します。 あなたのプロジェクトが両方をサポートしている場合、両方のバージョンでBanditを実行できますが、そうする必要はありません。
BanditはPythonのコードを解析するために、Pythonの標準ライブラリのastモジュールを使用します。 astモジュールは、それがインポートされたインタープリタのバージョンで有効なPythonコードのみを解析できます。 言い換えれば、Python 2.7のastモジュールを使用して3.5用に書かれたasyncioを使用するコードを解析しようとすると、Banditが正しく動作しないようにする構文エラーが発生します。 また、2.7の8進表記法(0777)に依存している場合、3.xでBanditを実行すると構文エラーが発生します。
参考文献
Bandit wiki: https : //wiki.openstack.org/wiki/Security/Projects/Bandit
Python ASTモジュールのドキュメント: https : //docs.python.org/2/library/ast.html
緑の木の蛇 – 欠けているPython ASTのドキュメント: https : //greentreesnakes.readthedocs.org/en/latest/
Banditが現在カバーしているか、または拡張できるようになっているさまざまなタイプのASTノードのドキュメント: https : //greentreesnakes.readthedocs.org/en/latest/nodes.html