Optimization quality-bandit

Bandit 보안 검사 설정 및 관리 스킬. pyproject.toml에 Bandit 설정을 구성하고 보안 취약점을 탐지한다. OWASP, CWE 기반의 보안 검사 환경을 구축한다.

install
source · Clone the upstream repo
git clone https://github.com/sunLeee/optimization
Claude Code · Install into ~/.claude/skills/
T=$(mktemp -d) && git clone --depth=1 https://github.com/sunLeee/optimization "$T" && mkdir -p ~/.claude/skills && cp -r "$T/.claude/skills/quality/check/quality-bandit" ~/.claude/skills/sunleee-optimization-quality-bandit && rm -rf "$T"
manifest: .claude/skills/quality/check/quality-bandit/SKILL.md
source content

Bandit 보안 검사 관리

Bandit 보안 검사 환경을 구성하고 관리한다.

목적

  • Bandit 보안 검사 환경 설정
  • 프로젝트별 보안 규칙 최적화
  • CWE/OWASP 매핑 관리
  • CI/CD 통합

사용법

/quality-bandit init      # 초기 설정
/quality-bandit scan      # 보안 검사 실행
/quality-bandit report    # 상세 보고서 생성

표준 설정

pyproject.toml

# =============================================================================
# Bandit Configuration
# Documentation: https://bandit.readthedocs.io/en/latest/config.html
# =============================================================================

[tool.bandit]
# 검사 대상
targets = ["src"]

# 제외 디렉토리
exclude_dirs = [
    "tests",
    "docs",
    ".venv",
    "build",
    "dist",
]

# 건너뛸 테스트 ID
skips = [
    "B101",  # assert 사용 (테스트에서 필요)
]

# 심각도 필터 (LOW, MEDIUM, HIGH)
# severity = "MEDIUM"

# 신뢰도 필터 (LOW, MEDIUM, HIGH)
# confidence = "MEDIUM"

테스트 ID 및 CWE 매핑

주요 테스트 ID

ID설명CWE심각도
B101assert 사용CWE-703Low
B102exec 사용CWE-78Medium
B103bad file permissionsCWE-732Medium
B104hardcoded bind addressCWE-605Medium
B105hardcoded passwordCWE-259Low
B106hardcoded password in functionCWE-259Low
B107hardcoded password defaultCWE-259Low
B108hardcoded temp directoryCWE-377Medium
B110try-except-passCWE-703Low
B112try-except-continueCWE-703Low

암호화 관련

ID설명CWE심각도
B303MD5 사용CWE-327Medium
B304DES 사용CWE-327High
B305cipher weak modeCWE-327Medium
B306mktemp 사용CWE-377Medium
B307eval 사용CWE-78Medium
B308mark_safe 사용CWE-79Medium
B311random (보안용 아님)CWE-330Low
B312telnetlib 사용CWE-319High
B313-B320XML 관련 취약점CWE-611Medium

인젝션 관련

ID설명CWE심각도
B601paramiko callCWE-78Medium
B602subprocess_popen_with_shellCWE-78High
B603subprocess_without_shell_equals_trueCWE-78Low
B604any_other_function_with_shellCWE-78Medium
B605start_process_with_a_shellCWE-78High
B606start_process_with_no_shellCWE-78Low
B607start_process_with_partial_pathCWE-78Low
B608hardcoded_sql_expressionsCWE-89Medium
B609linux_commands_wildcard_injectionCWE-78High
B610django_extra_usedCWE-89Medium
B611django_rawsql_usedCWE-89Medium

실행 명령

기본 검사

# 기본 검사
uv run bandit -r src/

# 설정 파일 사용
uv run bandit -c pyproject.toml -r src/

# 특정 테스트만
uv run bandit -r src/ -t B602,B608

# 특정 테스트 제외
uv run bandit -r src/ -s B101

출력 형식

# JSON 출력
uv run bandit -r src/ -f json -o bandit-report.json

# HTML 출력
uv run bandit -r src/ -f html -o bandit-report.html

# SARIF 출력 (GitHub 통합)
uv run bandit -r src/ -f sarif -o bandit-report.sarif

심각도/신뢰도 필터

# HIGH 심각도만
uv run bandit -r src/ -ll

# MEDIUM 이상
uv run bandit -r src/ -l

# 높은 신뢰도만
uv run bandit -r src/ -ii

프로젝트 유형별 설정

1. 웹 애플리케이션 (Django/FastAPI)

[tool.bandit]
targets = ["src"]
exclude_dirs = ["tests", "migrations"]
skips = ["B101"]

# 특별히 주의할 테스트
# B308: mark_safe (XSS)
# B608: SQL injection
# B610, B611: Django ORM injection

2. CLI 도구

[tool.bandit]
targets = ["src"]
exclude_dirs = ["tests"]
skips = [
    "B101",
    "B603",  # subprocess 사용 필요
    "B607",  # partial path 허용
]

3. Data Science

[tool.bandit]
targets = ["src"]
exclude_dirs = ["tests", "notebooks"]
skips = [
    "B101",
    "B311",  # random 사용 (ML에서 필요)
]

코드 내 억제

라인 수준

subprocess.call(cmd, shell=True)  # nosec B602

블록 수준

# nosec
def legacy_function():
    # 보안 검사 건너뜀
    pass

특정 테스트만 억제

eval(user_input)  # nosec B307

CI/CD 통합

GitHub Actions

# .github/workflows/security.yml
name: Security Check

on:
  pull_request:
  push:
    branches: [main]

jobs:
  bandit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install bandit
        run: pip install bandit[toml]

      - name: Run bandit
        run: bandit -c pyproject.toml -r src/ -f sarif -o bandit.sarif

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: bandit.sarif

Pre-commit

# .pre-commit-config.yaml
- repo: https://github.com/PyCQA/bandit
  rev: 1.8.2
  hooks:
    - id: bandit
      args: ['-c', 'pyproject.toml', '-r', 'src']
      additional_dependencies: ['bandit[toml]']
      stages: [pre-push]

보안 취약점 분류

OWASP Top 10 매핑

OWASPBandit 테스트
A01 Broken Access ControlB103
A02 Cryptographic FailuresB303, B304, B305
A03 InjectionB602, B608, B609
A05 Security MisconfigurationB104, B108
A07 Identification FailuresB105, B106, B107

심각도별 대응

심각도대응
HIGH즉시 수정 필요
MEDIUM릴리스 전 수정
LOW검토 후 결정

일반 취약점 및 수정

1. Hardcoded Password (B105-B107)

문제:

password = "secretpassword"

수정:

import os
password = os.environ.get("PASSWORD")

2. SQL Injection (B608)

문제:

query = f"SELECT * FROM users WHERE id = {user_id}"

수정:

query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))

3. Shell Injection (B602)

문제:

subprocess.call(f"ls {user_input}", shell=True)

수정:

subprocess.call(["ls", user_input], shell=False)

4. Weak Crypto (B303)

문제:

import hashlib
hashlib.md5(password.encode())

수정:

import hashlib
hashlib.sha256(password.encode())

관련 스킬

스킬역할
[@skills/quality-precommit/SKILL.md]Pre-commit hook 설정
[@skills/quality-ruff/SKILL.md]Ruff 린터 설정
[@skills/quality-mypy/SKILL.md]mypy 타입 검사
[@skills/check-python-style/SKILL.md]코드 스타일 검증

Changelog

날짜버전변경 내용
2026-01-211.0.0초기 생성 - Bandit 보안 검사 관리

Gotchas (실패 포인트)

  • False positive 많음 —
    # nosec
    주석은 이유 주석과 함께 사용
  • B104
    (hardcoded bind all interfaces) — 개발환경 0.0.0.0은 의도적일 수 있음
  • B101
    (assert) — pytest에서 assert 사용은 정상,
    tests/
    경로 제외 설정 권장
  • severity/confidence 임계값을 팀 기준으로 통일하지 않으면 CI 결과 불일치