Bandit 파이썬 보안 Linter Cheat Sheet
제품정보
Bandit는 Python 코드에서 일반적인 보안 문제를 찾는 보안 linter입니다. Python 소스 코드를 분석하고 알려진 패턴과 반대로 패턴을 스캔하여 잠재적 인 보안 취약점을 식별합니다. Bandit는 DevSecOps 파이프라인에서 널리 이용되며 개발 과정에서 보안 문제를 조기에 잡기 위해 Python 개발을 위한 필수적인 도구입니다.
· Note: Bandit는 잠재적인 보안 문제를 식별하고 종합적인 보안 테스트 전략의 일부로 사용되어야 합니다. 그것은 거짓 긍정을 생성하고 다른 보안 테스트 방법과 결합되어야 할 수 있습니다.
설치하기
pip 사용
카지노사이트
conda 사용
카지노사이트
패키지 관리자 사용
카지노사이트
Docker 설치
카지노사이트
기본 사용
간단한 스캔
카지노사이트
산출 체재
카지노사이트
Severity 및 Confidence 필터링
카지노사이트
제품 설명
구성 파일 (.bandit)
카지노사이트
프로젝트 제품 설명
카지노사이트
명령 줄 구성
카지노사이트
고급 사용
주문 시험 선택
ο 회원 관리
기본 및 진행성 검사
카지노사이트
Git와 통합
# Pre-commit hook script
#!/bin/bash
# .git/hooks/pre-commit
bandit -r . -ll -ii
if [ $? -ne 0 ]; then
echo "Bandit found security issues. Commit aborted."
exit 1
fi
# Make executable
chmod +x .git/hooks/pre-commit
# Git hook with specific files
#!/bin/bash
# Check only modified Python files
git diff --cached --name-only --diff-filter=ACM|grep '\.py
## CI/CD Integration
### GitHub Actions
```yaml의 경우
# .github/workflows/security.yml에 관하여
이름: 안전 검사
에: [push, pull_request]
작업:
악대:
실행에: ubuntu-latest
단계:
- 용도: 행동/checkout@v3
- 이름: Python 설정
용도: 동작/설정-python@v4
이름:
python 버전: "3.9"
- 이름: Bandit 설치
실행: pip install Bandit[toml]
- 이름: 뛰기 Bandit
실행: bandit -r . -f json -o bandit-report.json
- 이름: 업로드 결과
용도: 작업/업로드-artifact@v3
이름:
이름: 붕대 항구
경로: bandit-report.json
- 이름: Bandit 보고
용도: tj-actions/bandit@v5.1
이름:
옵션: "-r. -f json"
exit_zero: 사실
GitLab CI
```yaml의 경우
프로젝트
단계: - 계정 관리
악대: 단계: 보안 이미지: python:3.9 앞에_script: - pip는 Bandit[toml]를 설치 스크립트: - bandit -r . -f json -o bandit-report.json artifacts: 보고서 : 스트레이트: bandit-report.json 경로: - 붕대-report.json 만료됨: 1 주일 allow_failure: 진실
### Jenkins Pipeline
```groovy의 경우
// 젠킨스파일
파이프라인 \\ 이름 *
모든 제품
단계 \\ 이름 *
단계('보안 검사') \\ 이름 *
단계 \\{
스크립트 \\{
sh 'pip install 붕대[toml] 이름 *
sh 'bandit -r . -f json -o bandit-report.json 이름 *
이름 *
이름 *
게시물 \\ 이름 *
항상 \\ 이름 *
archiveArtifacts artifacts: 'bandit-report.json', 지문: true
HTML 버전
지원하다 미스: 거짓,
AlwaysLinkToLastBuild: 사실,
keepAll: 진실한,
이름 * Dir: '.',
보고서파일: 'bandit-report.html',
reportName: 'Bandit 보안 보고서 이름 *
])
이름 *
이름 *
이름 *
이름 *
이름 *
Azure DevOps
```yaml의 경우
azure 파이프 라인.yml
트리거: - 이름 *
수영장: vmImage : 'ubuntu-latest 이름 *
단계: - 작업: UsePythonVersion@0 입력 : 이름 * 사양: '3.9'
-
스크립트:| pip는 Bandit[toml]를 설치 Bandit -r . -f json -o $ (Agent.TempDirectory) /bandit-report.json displayName: 'Run Bandit 보안 검사 이름 *
-
작업: PublishTestResults@2 입력 : testResultsFiles: '$(Agent.TempDirectory)/bandit-report.json' 이름 * 제품정보 RunTitle: 'Bandit 보안 검사 이름 *
## Common Vulnerability Patterns
### Hardcoded Passwords (B105, B106, B107)
```피스톤
# BAD: 암호로 고쳐진 암호
암호 = "secret123"
api_key = "abc123def456"
# 좋은: 환경 변수
수입 os
비밀번호 = os.environ.get('PASSWORD')
api_key = os.environ.get('API_KEY')
# 좋은: 구성 파일
가져오기 configparser
구성 = configparser.ConfigParser()
설정.read('config.ini')
비밀번호 = config.get('database', 'password')
SQL Injection (B608)
# BAD: 문자열 포맷
쿼리 = "SELECT * 사용자 WHERE ID = %s"% user_id
query = f"SELECT * 사용자 WHERE id = \\{user_id\}"에서
# 좋은: 모수화된 쿼리
cursor.execute("SELECT * 사용자 WHERE id = %s", (user_id,))
cursor.execute("사용자 WHERE id = ?", (user_id,))
Command Injection (B602, B605, B606, B607)
# BAD: 포탄 주입
수입 os
os.system(f"ls \\{user_input\\\}") 의 경우
os.popen(f"grep \\{pattern\\\} \\{filename\\\\}") 를 호출합니다.
# 좋은: 명부를 가진 Subprocess
수입 subprocess
subprocess.run ('ls', user_input])을 실행합니다.
subprocess.run ('grep', 패턴, 파일명])
Insecure Random (B311)
# BAD: 예측 가능한 무작위
무작위 이미지
토큰 = random.randint(1000, 9999)
# 좋은: Cryptographically 안전
비밀번호
토큰 = secrets.randbelow(9999)
secure_token = 비밀.token_hex(16)
Unsafe YAML Loading (B506)
# BAD: 안전 YAML 선적
수입 yaml
데이터 = yaml.load (user_input)
# 좋은: 안전한 YAML 선적
데이터 = yaml.safe_load (user_input)
데이터 = yaml.load(user_input, Loader=yaml.SafeLoader)
Custom Rules and Plugins
Creating Custom Tests
# 사용자 정의_bandit_test.py
비밀번호
Bandit에서. 핵심 수입 test_properties
@test_properties.test_id('B999')
@test_properties.checks('커')
def custom_security_check(콘텍스트):
"""주문 보안 패턴을 확인""
만약 context.call_function_name_qual == 'dangerous_function':
반환 bandit. 문제(
severity=밴드. 높은,
신뢰=bandit. 높은,
text="safe_function detected의 사용",
lineno=context.node.lineno,
Plugin Development
# Bandit_plugin.py에
Bandit에서. 코어 가져오기 extension_loader
def load_tests():
"""로드 사용자 정의 테스트"""
반환 [custom_security_check]
# 플러그인
extension_loader.MANAGER.register_plugin('custom_tests', load_tests)
Using Custom Tests
```bash의 경우
짐 관례 시험
--테스트 사용자 정의_bandit_test.py
플러그인
팟캐스트 -r. --플러그인 bandit_plugin.py
## Automation and Scripting
### Automated Scanning Script
```피스톤
#!/usr/bin/env python3
# Bandit_scanner.py에 대 한
수입 subprocess
수입 json
수입 sys
수입 argparse
pathlib 가져오기 오시는 길
클래스 BanditScanner :
def __init__(self, project_path, config_file=None):
self.project_path = 경로 (project_path)
아파치 모듈 mod_file = config_file
장바구니에 담기
def run_scan(self, output_format='json', severity='MEDIUM', trust='MEDIUM'):
"""Run Bandit는 지정된 매개 변수로 스캔"""
₢ 킹
'bandit', '-r', str(self.project_path),
'-f', output_format,
f'-l\{self._severity_to_flag(severity)\\}',
₢ 킹 이름 *
·
self.config_file이 있다면:
cmd.extend ('-configfile', self.config_file])
태그 :
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
output_format == 'json'의 경우:
자기.results = json.loads(result.stdout) 결과. 다른 \\{\\}
다른 것:
각자.results = result.stdout
반환 result.returncode == 0 댓글
subprocess를 제외하고. 비밀번호 e로 오류:
print(f"Error 실행 Bandit: \\{e\}")
반환 False
json을 제외하고. JSON디코딩 e로 오류:
print(f"Error 파싱 JSON 출력: \\{e\}")
반환 False
def _severity_to_flag (자신, 심각성):
""" Bandit flag"에 대한 상호 작용""
mapping = \\{'LOW': '', 'MEDIUM': 'l', 'HIGH': 'll'\}
반환 맵핑. get(severity.upper(), 'l'),
def _confidence_to_flag(자신, 신뢰):
""" Bandit 플래그에 대한 신뢰를 변환"""
mapping = \\{'LOW': 'ii', 'MEDIUM': 'i', 'HIGH': ''\\}
mapping.get(confidence.upper(), 'i'를 반환합니다.
def get_summary(자):
""" 스캔 요약"""
if not isinstance(self.results, dict):
반환 "결과 없음"
metrics = self.results.get('metrics', \\{\})
반환 \\{
'total_lines': metrics.get('_total', \\{\\}).get('loc', 0),
'total_issues': len(self.results.get('results', [])),
'high_severity': len [r for r in self.results.get('results', [])
if r.get('issue_severity') == 'HIGH']),
'medium_severity': len [r for r in self.results.get('results', [])
if r.get('issue_severity') == 'MEDIUM']),
'low_severity': len [r for r in self.results.get('results', [])
만약 r.get('issue_severity') == 'LOW')
이름 *
def get_issues_by_severity(self, severity='HIGH'):
"""문제가 심각성""""
if not isinstance(self.results, dict):
반환 []
반환 [self.results.get에 대한 문제 ('results', [])
if issue.get('issue_severity') == severity.upper()]
def generate_report(self, output_file='bandit_report.html'):
""Generate HTML 보고서""
₢ 킹
'bandit', '-r', str(self.project_path),
'-f', 'html', '-o', output_file
·
self.config_file이 있다면:
cmd.extend ('-configfile', self.config_file])
태그 :
subprocess.run (cmd, check=True)
진정한
subprocess를 제외하고. 비밀번호 오류:
반환 False
def save_results(self, output_file='bandit_results.json'):
"""파일에 결과를 저장""
if isinstance(self.results, dict):
open(output_file, 'w') 으로 f:
json.dump(self.results, f, indent=2)
다른 것:
open(output_file, 'w') 으로 f:
f.write(str(self.results))를 호출합니다.
방어 주요 ():
파서 = argparse. ArgumentParser(description='자동 Bandit 스캐너)
parser.add_argument('project_path', help='Path to project to scan')
parser.add_argument('-config', help='Bandit 구성 파일')
parser.add_argument('--severity', default='MEDIUM',
select=['LOW', 'MEDIUM', 'HIGH'],
help='Minimum severity 레벨')
parser.add_argument('-confidence', default='MEDIUM',
select=['LOW', 'MEDIUM', 'HIGH'],
help='Minimum 신뢰 수준')
parser.add_argument('-output', help=' 결과를 위한 출력 파일')
parser.add_argument('--report', help='Generate HTML 보고서')
args = 파서.parse_args()
스캐너 = BanditScanner (args.project_path, args.config)
인쇄(f"Scanning \\{args.project_path\\}...")
성공 = Scanner.run_scan(severity=args.severity, trust=args.confidence)
성공 사례:
요약 = Scanner.get_summary()
print(f"Scan 완료되었습니다!")
print(f"코드의 총 줄: \\{summary['total_lines']\\}")
print(f" 총 문제 발견: \\{summary['total_issue']\\}")
인쇄 (f"높은 엄격: \\{summary['high_severity']\}")
인쇄(f"Medium severity: \\{summary['medium_severity']\}")
인쇄(f"Low severity: \\{summary['low_severity']\}")
만약 args. 산출:
스캐너.save_results(args.output)
print(f"결과는 \\{args.output\\}")에 저장됩니다.
args.report 경우:
만약 Scanner.generate_report(args.report):
print(f"HTML 보고서 생성: \\{args.report\}")
다른 것:
print("HTML 보고서 생성에 실패")
# Exit with error code if high severity issues found
요약['high_severity'] >```0
print("높은 severity 문제 발견!")
소프트웨어 (1)
다른 것:
print("Scan 실패!")
소프트웨어 (1)
if __name__ == (으)로 '__main__':
주요 ()
Batch Processing Script
#!/bin/bash
# 일괄 처리_bandit_scan.sh
# 제품 설명
프로젝트_DIR="/path/to/projects"
REPORTS_DIR="/path/to/reports"에 관하여
DATE=$(일) +%Y%m%d_%H%M%S)
# 연락처
mkdir -p "$REPORTS_DIR"의
# 프로젝트 스캔
엠에디터 매크로 참조:Scan_project()\{
Local project_path="$1" - 한국어
Local project_name=$(기본값 "$project_path")
로컬 보고서_file="$REPORTS_DIR/$\{project_name\}_$\{DATE\}.json"
로컬 HTML_report="$ REPORTS_DIR/$\{project_name\}_$\{DATE\}.html" 를 선택합니다.
echo "Scanning $project_name..."
# Run Bandit scan
bandit -r "$project_path" -f json -o "$report_file" -ll -ii
Bandit -r "$project_path" -f HTML -o "$html_report" -ll -ii
# Check for high severity issues
| high_issues=$(jq '.results | map(select(.issue_severity == "HIGH")) | length' "$report_file") |
if [ "$high_issues" -gt 0 ]; 다음
echo "WARNING: $project_name에는 $high_issues 높은 심각성 문제가 있습니다!"
echo "$project_name" >> "$REPORTS_DIR/high_severity_projects.txt"
·
echo “Scan 완료 $project_name”
이름 *
# 모든 Python 프로젝트를 스캔
"$PROJECTS_DIR" -name "*.py" -type f|while read -r 파일; 할
project_dir=$(자명 "$file")
if [ ! -f "$project_dir/.bandit_scanned" ]; 다음
프로젝트 "$project_dir"
터치 "$project_dir/.bandit_scanned"
·
이름 *
echo "배치 스캔 완료. $REPORTS_DIR에 저장 된 보고서
Integration with IDEs
VS Code Integration
// .vscode/settings.json의 경우
이름 * 이름 *
"python.linting.banditEnabled": true,
"python.linting.banditArgs": [
"---severity-level", "중간",
"--confidence-level", "중간"
],
"python.linting.enabled": 사실
이름 *
PyCharm Integration
# 외부 공구 윤곽
# 프로그램: Bandit
# 정렬 : -r $ FileDir $ -f json
# 작업 디렉토리: $ProjectFileDir$
Vim/Neovim Integration
" .vimrc 또는 init.vim
" ALE과 Bandit 통합
let g:ale_linters = \{
\ 'python': ['bandit', 'flake8', 'pylint'],
이름 *
let g:ale_python_bandit_options = '-ll -ii 이름 *
Best Practices
Configuration Management
# .bandit - 종합 구성
'B101', 'B102', 'B103', 'B104', 'B105', 'B106', 'B107', 'B108', 'B110', 'B112', 'B201', 'B301', 'B302', 'B303', 'B304', 'B305', 'B306', 'B308', 'B309', 'B310', 'B310', 'B303', 'B303', 'B303', 'B303', 'B303', 'B303', 'B303', 'B303'
건너뛰기: ['B101'] # Skip assert_used in test files
exclude_dirs를 제외한다: [
'*/tests/*',
'*/test/*',
'*/.venv/*',
'*/venv/*',
'*/.env/*',
'*/env/*',
'*/migrations/*',
'*/node_modules/*',
'*/.git/*''에 대해
·
# 심각성: LOW, MEDIUM, 높은
공급 능력: 의료용
# 구성: LOW, MEDIUM, 높은
신뢰: 의료용
False Positive Management
# 경고를 억제하는 인라인 의견
암호 = "기본" # nosec B105
# Suppress 특정 시험
수입 subprocess
subprocess.call (shell_command, shell=True) # nosec B602
# 여러 검사
eval(user_input)의 경우 # 노 SEC B307, B102
Team Workflow Integration
# Pre-commit 구성 (.pre-commit-config.yaml)
자료:
- repo : https://github.com/PyCQA/bandit
수정: '1.7.5'
걸이:
- id: 붕대
args: ['-ll', '-ii']
제외: ^tests/
# 파일 통합
· PHONY: 보안 수
보안 사기:
bandit -r . -ll -ii -f json -o 보안 -report.json
@echo "보안 검사 완료. security-report.json 의 결과를 확인 합니다.
· PHONY: 보안 검사
보안 검사:
밴드 -r. -ll -ii
@if [ $? -ne 0 ]; 다음 \
echo "보안 문제 발견. 검토 및 수정하십시오."; 이름 *
출구 1; \
·
Troubleshooting
Common Issues
# 문제: Bandit를 실행할 때 ImportError
# 해결책: 적당한 Python 환경을 지킵니다
python -m pip 설치 - 고급 붕대
# 문제: 구성은 읽지 않습니다
# 솔루션: 구성 파일 위치 및 구문 확인
팟캐스트 --help-config 설정
# 문제: 너무 많은 거짓 긍정적
# 해결책: Tune 구성 및 사용 억제
팟캐스트 --스키프 B101,B601 -ll -ii
# 문제: 큰 codebases를 가진 성과 문제점
# 솔루션: 불필요한 감독 제외
bandit -r. -- 제외 "*/venv/*,*/node_modules/*,*/.git/*"
# 문제: CI/CD와 통합 실패
# 해결책: 적절한 출구 코드 및 오류 처리 사용
| 밴드 -r. -ll -ii | | true # 오류 계속 |
Performance Optimization
# 병렬 처리 (사용 가능한 경우)
밴드 -r. --공정 4
# 큰 감독 제외
bandit -r . -- 제외 "*/venv/*,*/env/*,*/node_modules/*,*/.git/*,*/migrations/*"
# 특정한 시험만 사용
밴드 -r. - 테스트 B201, B301, B401, B501
# 제한 반복 깊이
| . -이름 "*.py" -not -path "*/venv/*" | 머리 -100 | xargs bandit |
Debugging
# Verbose 산출
밴드 -v -r.
# Debug 모드
밴드 -d -r.
# 건너뛰기 파일
밴드 -r. --버블로스
# 모든 세부 사항으로 특정 파일을 테스트
붕대 -v -ll -iii specific_file.py
카지노사이트
## CI/CD 통합
### GitHub 작업
카지노사이트
### 프로젝트
카지노사이트
### Jenkins 파이프 라인
카지노사이트
### Azure DevOps를
카지노사이트
## 일반 취약점 패턴
### 암호 (B105, B106, B107)
카지노사이트
### SQL 주입 (B608)
카지노사이트
### 명령 주입 (B602, B605, B606, B607)
오프화이트
### Insecure 랜덤 (B311)
카지노사이트
### 안전한 YAML 적재 (B506)
오프화이트
## 사용자 정의 규칙 및 플러그인
### 사용자 정의 테스트 만들기
카지노사이트
### 플러그인 개발
카지노사이트
### Custom Test 사용
카지노사이트
## 자동화 및 스크립트
### 자동화된 스캐닝 스크립트
카지노사이트
### 일괄 처리 스크립트
카지노사이트
## IDE와 통합
### VS 코드 통합
카지노사이트
### PyCharm 통합
Vim/Neovim Integration
### Vim/Neovim 통합
Best Practices
Configuration Management
## 최고의 연습
### 구성 관리
False Positive Management
### False 긍정적인 관리
Team Workflow Integration
### 팀 Workflow 통합
Troubleshooting
Common Issues
## 문제 해결
### 일반적인 문제
카지노사이트
### 성능 최적화
카지노사이트
### 관련 링크
카지노사이트
## 지원하다
- [Bandit 공식 문서](__LINK_6__)
- [Bandit GitHub 저장소](__LINK_6__)
- [Python Security 모범 사례](__LINK_6__)
- [OWASP 파이썬 보안](__LINK_6__)
- [PyCQA 도구](__LINK_6__)
--- ---
*이 속임수 시트는 Python 코드에서 보안 취약성을 식별하기 위해 Bandit을 사용하는 포괄적 인지도를 제공합니다. 항상 포괄적인 적용을 위한 다른 안전 테스트 방법을 가진 정체되는 분석. *필수