Bandit这款工具可以用来搜索Python代码中常见的安全问题,在检测过程中,Bandit会对每一份Python代码文件进行处理,并构建AST,然后针对每一个AST节点运行相应的检测插件。完成安全扫描之后,Bandit会直接给用户生成检测报告。
Bandit使用PyPI来进行分发,建议广大用户直接使用pip来安装Bandit。
创建虚拟环境(可选):
virtualenv bandit-env
安装Bandit:
pip install bandit# Or if you're working with a Python 3 projectpip3 install bandit
运行Bandit:
bandit -r path/to/your/code
用户还可以使用源码文件直接安装Bandit,先从PyPI下载原tarball,然后运行下列命令:
python setup.py install
节点树使用样例:
bandit -r ~/your_repos/project
examples/目录遍历使用样例,显示三行内容,并只报告高危问题:
bandit examples/*.py -n 3 –lll
Bandit还能够结合配置参数一起运行,运行下列命令即可使用ShellInjection来对examples目录运行安全扫描:
bandit examples/*.py -p ShellInjection
Bandit还支持使用标准输入模式来扫描指定行数的代码:
cat examples/imports.py | bandit –
$bandit -husage:bandit [-h] [-r] [-a {file,vuln}] [-n CONTEXT_LINES] [-c CONFIG_FILE][-p PROFILE] [-t TESTS] [-sSKIPS] [-l] [-i][-f{csv,custom,html,json,screen,txt,xml,yaml}][--msg-template MSG_TEMPLATE] [-o[OUTPUT_FILE]] [-v] [-d] [-q][--ignore-nosec] [-x EXCLUDED_PATHS] [-bBASELINE][--ini INI_PATH] [--version][targets [targets ...]]Bandit- a Python source code security analyzerpositionalarguments:targets source file(s) or directory(s)to be testedoptionalarguments:-h, --help show this help message and exit-r, --recursive find and process files in subdirectories-a {file,vuln}, --aggregate {file,vuln}aggregate output byvulnerability (default) or byfilename-n CONTEXT_LINES, --number CONTEXT_LINESmaximum number of codelines to output for each issue-c CONFIG_FILE, --configfile CONFIG_FILEoptional config file touse for selecting plugins andoverriding defaults-p PROFILE, --profile PROFILEprofile to use(defaults to executing all tests)-t TESTS, --tests TESTScomma-separated list oftest IDs to run-s SKIPS, --skip SKIPScomma-separated list oftest IDs to skip-l, --level report only issues of a givenseverity level or higher(-l for LOW, -ll for MEDIUM, -lll forHIGH)-i, --confidence report only issues of a given confidencelevel orhigher (-i for LOW, -iifor 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_TEMPLATEspecify output messagetemplate (only usable with--format custom), seeCUSTOM FORMAT section for listof available values-o [OUTPUT_FILE], --output [OUTPUT_FILE]write report tofilename-v, --verbose output extra information like excludedand includedfiles-d, --debug turn on debug mode-q, --quiet, --silentonly show output in thecase of an error--ignore-nosec do not skip lines with # nosec comments-x EXCLUDED_PATHS, --exclude EXCLUDED_PATHScomma-separated list ofpaths (glob patterns supported)to exclude from scan(note that these are in additionto the excluded pathsprovided in the config file)-b BASELINE, --baseline BASELINEpath of a baselinereport to compare against (onlyJSON-formatted filesare accepted)--ini INI_PATH path to a .bandit file that suppliescommand linearguments--version show program's version number andexitCUSTOMFORMATTING-----------------Availabletags:{abspath}, {relpath}, {line}, {test_id},{severity}, {msg}, {confidence}, {range}Exampleusage:Default template:bandit -r examples/ --format custom--msg-template \"{abspath}:{line}: {test_id}[bandit]:{severity}: {msg}"Provides same output as:bandit -r examples/ --format customTags 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 moreinformation about formatting style:https://docs.python.org/3.4/library/string.htmlThefollowing tests were discovered and loaded:-----------------------------------------------B101 assert_usedB102 exec_usedB103 set_bad_file_permissionsB104 hardcoded_bind_all_interfacesB105 hardcoded_password_stringB106 hardcoded_password_funcargB107 hardcoded_password_defaultB108 hardcoded_tmp_directoryB110 try_except_passB112 try_except_continueB201 flask_debug_trueB301 pickleB302 marshalB303 md5B304 ciphersB305 cipher_modesB306 mktemp_qB307 evalB308 mark_safeB309 httpsconnectionB310 urllib_urlopenB311 randomB312 telnetlibB313 xml_bad_cElementTreeB314 xml_bad_ElementTreeB315 xml_bad_expatreaderB316 xml_bad_expatbuilderB317 xml_bad_saxB318 xml_bad_minidomB319 xml_bad_pulldomB320 xml_bad_etreeB321 ftplibB322 inputB323 unverified_contextB324 hashlib_new_insecure_functionsB325 tempnamB401 import_telnetlibB402 import_ftplibB403 import_pickleB404 import_subprocessB405 import_xml_etreeB406 import_xml_saxB407 import_xml_expatB408 import_xml_minidomB409 import_xml_pulldomB410 import_lxmlB411 import_xmlrpclibB412 import_httpoxyB413 import_pycryptoB501 request_with_no_cert_validationB502 ssl_with_bad_versionB503 ssl_with_bad_defaultsB504 ssl_with_no_versionB505 weak_cryptographic_keyB506 yaml_loadB507 ssh_no_host_key_verificationB601 paramiko_callsB602 subprocess_popen_with_shell_equals_trueB603 subprocess_without_shell_equals_trueB604 any_other_function_with_shell_equals_trueB605 start_process_with_a_shellB606 start_process_with_no_shellB607 start_process_with_partial_pathB608 hardcoded_sql_expressionsB609 linux_commands_wildcard_injectionB610 django_extra_usedB611 django_rawsql_usedB701 jinja2_autoescape_falseB702 use_of_mako_templatesB703 django_mark_safe
基准线
Bandit允许用户指定需要进行比对的基线报告路径:
bandit -b BASELINE
这样可以帮助大家忽略某些已知问题,或者是那些你不认为是问题的“问题”。大家可以使用下列命令生成基线报告:
bandit -f json -o PATH_TO_OUTPUT_FILE
安装并使用pre-commit,将下列内容添加至代码库的.pre-commit-config.yaml文件中:
repos:- repo: https://github.com/PyCQA/bandit rev: '' # Update me! hooks:- id: bandit
然后运行pre-commit即可。
Bandit允许用户编写和注册扩展以实现自定义检测或格式化(Formatter)功能。Bandit可以从下列两个节点加载插件:
bandit.formattersbandit.plugins
Formatter需要接收下列四种输入参数:
result_store:一个bandit.core.BanditResultStore实例file_list:需要扫描检测的文件列表scores:每个文件的扫描评分excluded_files:列表中不需要扫描的文件
利用bandit.checks来对特定类型的AST节点进行检测扫描:
.checks('Call')defprohibit_unsafe_deserialization(context):if 'unsafe_load' incontext.call_function_name_qual:return bandit.Issue(severity=bandit.HIGH,confidence=bandit.HIGH,text="Unsafe deserializationdetected.")
1、 如果你直接使用了安装工具(setuptools),我们需要在setup调用中添加下列信息:
# Ifyou have an imaginary bson formatter in the bandit_bson module# anda function called `formatter`.entry_points={'bandit.formatters':['bson = bandit_bson:formatter']}# Ora check for using mako templates in bandit_mako thatentry_points={'bandit.plugins':['mako = bandit_mako']}
2、 如果你使用的是pbr,你需要在setup.cfg文件中添加下列信息:
[]bandit.formatters=bson= bandit_bson:formatterbandit.plugins=mako = bandit_mako
参考文档:https://bandit.readthedocs.io/en/latest/
Bandit:https://github.com/PyCQA/bandit
漏洞提交:https://github.com/PyCQA/bandit/issues
本项目遵循Apache开源许可证协议。
*参考来源:bandit,FB小编Alpha_h4ck编译,转载请注明来自FreeBuf.COM
精彩推荐