首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Bandit Python代码审计漏洞检测工具实战

Bandit Python代码审计漏洞检测工具实战

作者头像
qife122
发布2025-06-16 09:10:52
发布2025-06-16 09:10:52
3990
举报

系统概述

Bandit是一个用于分析Python代码审计安全漏洞的工具,旨在识别常见的安全问题,如硬编码密码、不安全的函数调用、SQL注入等。它通过构建抽象语法树(AST)并对节点运行适当的插件来检测潜在的安全问题。Bandit最初由OpenStack安全项目开发,后来迁移到PyCQA(Python代码质量权威)维护。

系统架构

Bandit的核心架构包括以下几个主要组件:

  1. AST解析器:Bandit通过解析Python代码生成AST,并在AST节点上运行插件来检测安全问题。
  2. 插件系统:Bandit通过插件系统扩展其检测能力,每个插件负责检测特定的安全问题。插件可以通过配置文件进行管理,支持黑名单和白名单机制。
  3. 配置文件:Bandit使用YAML格式的配置文件来定义检测规则、插件设置和输出格式。
  4. 报告生成器:Bandit支持多种输出格式,包括CSV、JSON、HTML、XML等,用户可以根据需求选择合适的格式生成安全报告。

核心技术点

  1. AST解析与节点遍历:Bandit通过Python的ast模块解析代码并生成AST,然后遍历AST节点,调用相应的插件进行检测。
  2. 插件机制:Bandit的插件机制是其核心功能之一,每个插件负责检测特定的安全问题。插件通过@test_properties装饰器注册,并定义检测逻辑。
  3. 黑名单与白名单:Bandit支持通过黑名单和白名单机制来过滤检测结果。黑名单用于标记已知的不安全函数调用或模块导入,白名单则用于排除误报。
  4. 配置文件管理:Bandit使用YAML配置文件来管理检测规则和插件设置,用户可以通过配置文件自定义检测行为。
  5. 多种输出格式:Bandit支持多种输出格式,用户可以根据需求生成不同格式的安全报告,便于集成到CI/CD流程中。

核心代码分析

AST解析与插件调用

代码语言:javascript
复制
from bandit.core import manager
   b_mgr = manager.BanditManager(config, agg_type)
   b_mgr.run_tests()
这段代码展示了Bandit如何通过
BanditManager类管理AST解析和插件调用。

插件定义

代码语言:javascript
复制
@test_properties.checks('Call')
   @test_properties.test_id('B102')
   def exec_used(context):
       if context.call_function_name_qual == 'exec':
           return bandit.Issue(
               severity=bandit.MEDIUM,
               confidence=bandit.HIGH,
               cwe=issue.Cwe.OS_COMMAND_INJECTION,
               text='Use of exec detected.',
           )
这段代码定义了一个检测
exec函数使用的插件,当检测到
exec函数调用时,会返回一个安全问题。

配置文件示例

代码语言:javascript
复制
include:
       - '*.py'
   profiles:
       test:
           include:
               - start_process_with_a_shell
   shell_injection:
       subprocess: []
       shell:
           - os.system
这个配置文件定义了检测规则,指定了需要检测的文件类型和插件。

应用场景

Bandit适用于以下场景:

  1. 代码审查:在代码提交前,使用Bandit进行静态分析,识别潜在的安全漏洞。
  2. CI/CD集成:将Bandit集成到CI/CD流水线中,自动检测代码中的安全问题。
  3. 安全审计:定期对代码库进行安全审计,确保代码符合安全最佳实践。
  4. 开发环境:在开发过程中,实时检测代码中的安全问题,帮助开发者及时修复漏洞。

应用测试

  1. 安装bandit
代码语言:javascript
复制
测试环境 ubuntu 22.04
打开terminal
git clone https://github.com/PyCQA/bandit.git   //下载bandit项目
cd bandit
sudo python setup.py install  //安装bandit
如果安装过程有缺失其他模块,则先安装缺失的模块即可
下载一个带有python安全漏洞分险的项目 这里我用的Vulnerable-Flask-App项目
执行 bandit /home/chendong/bandit/Vulnerable-Flask-App/app/app.py 审计指定的.py源代码文件

2.测试结果如下显示了几个安全问题

代码语言:javascript
复制
	Total issues (by severity):
		Undefined: 0
		Low: 6
		Medium: 2
		High: 1
	Total issues (by confidence):
		Undefined: 0
		Low: 1
		Medium: 4
		High: 4

具体安全问题描述如下

代码语言:javascript
复制
Test results:
>> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'secret'
   Severity: Low   Confidence: Medium
   CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/plugins/b105_hardcoded_password_string.html
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:26:11
25	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
26	app.config['SECRET_KEY_HMAC'] = 'secret'
27	app.config['SECRET_KEY_HMAC_2'] = 'am0r3C0mpl3xK3y'

--------------------------------------------------
>> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'am0r3C0mpl3xK3y'
   Severity: Low   Confidence: Medium
   CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/plugins/b105_hardcoded_password_string.html
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:27:11
26	app.config['SECRET_KEY_HMAC'] = 'secret'
27	app.config['SECRET_KEY_HMAC_2'] = 'am0r3C0mpl3xK3y'
28	app.secret_key = 'F12Zr47j\3yX R~X@H!jmM]Lwf/,?KT'

--------------------------------------------------
>> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'F12Zr47jyX R~X@H!jmM]Lwf/,?KT'
   Severity: Low   Confidence: Medium
   CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/plugins/b105_hardcoded_password_string.html
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:28:17
27	app.config['SECRET_KEY_HMAC_2'] = 'am0r3C0mpl3xK3y'
28	app.secret_key = 'F12Zr47j\3yX R~X@H!jmM]Lwf/,?KT'
29	app.config['STATIC_FOLDER'] = None

--------------------------------------------------
>> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'admin123'
   Severity: Low   Confidence: Medium
   CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/plugins/b105_hardcoded_password_string.html
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:63:24
62	        user.username = 'admin'
63	        user.password = 'admin123'
64	        db.session.add(user)

--------------------------------------------------
>> Issue: [B324:hashlib] Use of weak MD5 hash for security. Consider usedforsecurity=False
   Severity: High   Confidence: High
   CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/plugins/b324_hashlib.html
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:141:24
140	            password = content['password']
141	            hash_pass = hashlib.md5(password).hexdigest()
142	            new_user = User(username, hash_pass)

--------------------------------------------------
>> Issue: [B608:hardcoded_sql_expressions] Possible SQL injection vector through string-based query construction.
   Severity: Medium   Confidence: Low
   CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/plugins/b608_hardcoded_sql_expressions.html
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:261:32
260	                    print(search_term)
261	                    str_query = "SELECT first_name, last_name, username FROM customer WHERE username = '%s';" % search_term
262	                    # mycust = Customer.query.filter_by(username = search_term).first()

--------------------------------------------------
>> Issue: [B311:blacklist] Standard pseudo-random generators are not suitable for security/cryptographic purposes.
   Severity: Low   Confidence: High
   CWE: CWE-330 (https://cwe.mitre.org/data/definitions/330.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/blacklists/blacklist_calls.html#b311-random
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:295:15
294	        f = request.files['file']
295	        rand = random.randint(1, 100)
296	        fname = secure_filename(f.filename)

--------------------------------------------------
>> Issue: [B311:blacklist] Standard pseudo-random generators are not suitable for security/cryptographic purposes.
   Severity: Low   Confidence: High
   CWE: CWE-330 (https://cwe.mitre.org/data/definitions/330.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/blacklists/blacklist_calls.html#b311-random
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:319:15
318	        f = request.files['file']
319	        rand = random.randint(1, 100)
320	        fname = secure_filename(f.filename)

--------------------------------------------------
>> Issue: [B506:yaml_load] Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().
   Severity: Medium   Confidence: High
   CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html)
   More Info: https://bandit.readthedocs.io/en/1.8.4.dev9/plugins/b506_yaml_load.html
   Location: /home/chendong/bandit/Vulnerable-Flask-App/app/app.py:329:16
328	
329	        ydata = yaml.load(y)
330	
图片
图片
图片
图片

总结

Bandit是一个功能强大的Python代码安全分析工具,通过AST解析和插件机制,能够有效识别代码中的常见安全问题。其灵活的配置和多种输出格式使其易于集成到现有的开发流程中,帮助开发者和安全团队提高代码的安全性。

github链接地址:https://github.com/PyCQA/bandit.git

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-03-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 网络安全技术点滴分享 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 系统概述
  • 系统架构
  • 核心技术点
  • 核心代码分析
  • 应用场景
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档