Communitygithub.com

Ghidra를 활용한 Go 악성코드 리버스 엔지니어링

Ghidra에서 Go로 컴파일된 악성코드를 분석할 때 Go 빌드 정보를 파싱하여 함수 이름과 의존성을 복구합니다.

Ghidra를 활용한 Go 악성코드 리버스 엔지니어링란 무엇인가요?

이 스킬은 보안 분석가가 Ghidra에서 Go(Golang)로 컴파일된 악성코드 바이너리를 분석할 수 있도록 체계적인 워크플로우와 도구를 제공합니다. Go 바이너리는 정적 링킹으로 인해 대형 바이너리와 수천 개의 함수를 가지며, Ghidra는 Go 특유의 널 종료되지 않는 문자열 포맷과 난독화된 함수 이름을 처리하는 데 어려움을 겪습니다. 이 스킬은 pclntab(PC 라인 테이블)을 찾고 파싱하여 함수 이름을 복구하고, GoResolver와 같은 전문 플러그인을 활용하며, Python 스크립트를 통해 악성코드의 의존성과 의심스러운 문자열을 자동으로 추출합니다. 주요 사용 사례는 보안 사고 분석, 탐지 규칙 개발, SOC 분석가의 정형화된 절차 지원 등이며, Ghidra 11.0+와 JDK 17+ 환경에서 동작합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/analyzing-golang-malware-with-ghidra

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Ghidra를 활용한 Go 악성코드 리버스 엔지니어링은(는) 무엇을 하나요?

개요

Go(Golang)는 크로스 컴파일 능력, 정적 링킹으로 인한 독립 실행형 바이너리 생성, 리버스 엔지니어링에 복잡성을 추가하는 특성 때문에 악성코드 작성자 사이에서 인기 있는 언어가 되었습니다. Go 바이너리는 전체 런타임, 표준 라이브러리, 모든 의존성을 정적으로 링크하므로 결과적으로 대형 바이너리(보통 5-15MB)와 수천 개의 함수를 갖게 됩니다. Ghidra는 Go 특유의 문자열 포맷(널 종료되지 않음), 제거된 함수 이름, 고루틴 동시성 패턴을 처리하는 데 어려움을 겪습니다. GoResolver(Volexity, 2025)와 같은 특수 도구는 제어 흐름 그래프 유사성을 사용하여 제거되거나 난독화된 Go 바이너리의 함수 이름을 자동으로 복구합니다.

사용 시기

  • 보안 사고를 조사할 때 Ghidra를 사용한 Go 악성코드 분석이 필요한 경우
  • 이 도메인에 대한 탐지 규칙 또는 위협 헌팅 쿼리를 구축할 때
  • SOC 분석가가 이 분석 유형에 대한 구조화된 절차가 필요할 때
  • 관련 공격 기술에 대한 보안 모니터링 범위를 검증할 때

필수 조건

  • Ghidra 11.0+ 및 JDK 17+
  • GoResolver 플러그인 (함수 이름 복구용)
  • Go 리버스 엔지니어링 툴킷 (go-re.tk)
  • 헬퍼 스크립트용 Python 3.9+
  • Go 런타임 내부 구조 이해 (고루틴, 채널, 인터페이스)
  • Go 바이너리 구조 이해 (pclntab, moduledata, itab)

주요 개념

Go 바이너리 구조

Go 바이너리는 pclntab(프로그램 카운터 라인 테이블) 구조에 프로그램 카운터를 함수 이름, 소스 파일, 줄 번호에 매핑하는 풍부한 메타데이터를 내장합니다. 심볼이 제거된 바이너리도 이 메타데이터를 유지합니다. moduledata 구조는 타입 정보, itab(인터페이스 테이블), pclntab 자체에 대한 포인터를 포함합니다. Go 문자열은 널 종료 C 문자열이 아닌 포인터-길이 쌍으로 저장됩니다.

제거된 바이너리의 함수 복구

심볼 테이블이 제거되었음에도 Go 바이너리는 pclntab 내에 함수 이름을 유지합니다. 그러나 garble과 같은 난독화 도구는 함수 이름을 임의의 문자열로 변경합니다. GoResolver는 난독화된 함수의 제어 흐름 그래프 서명을 계산하고 알려진 Go 표준 라이브러리 및 타사 패키지 함수 데이터베이스와 매칭하여 이 문제를 해결합니다.

크레이트/의존성 추출

Go의 의존성 관리는 바이너리에 모듈 경로와 버전 문자열을 내장합니다. 이를 추출하면 악성코드의 타사 의존성(HTTP 라이브러리, 암호화 패키지, C2 프레임워크)이 드러나며, 전체 리버스 엔지니어링 없이도 기능에 대한 통찰력을 제공합니다.

워크플로우

단계 1: 초기 바이너리 분석

#!/usr/bin/env python3
"""악성코드 분석을 위한 Go 바이너리 메타데이터 분석."""
import struct
import sys
import re


def find_go_build_info(data):
    """바이너리에서 Go 빌드 정보 추출."""
    # Go buildinfo 매직: \xff Go buildinf:
    magic = b'\xff Go buildinf:'
    offset = data.find(magic)
    if offset == -1:
        return None

    print(f"[+] Go 빌드 정보 오프셋 0x{offset:x}")

    # 근처에서 Go 버전 문자열 추출
    go_version = re.search(rb'go\d+\.\d+(?:\.\d+)?', data[offset:offset+256])
    if go_version:
        print(f"  Go 버전: {go_version.group().decode()}")

    return offset


def find_pclntab(data):
    """pclntab(PC 라인 테이블) 구조 위치 찾기."""
    # pclntab 매직 바이트는 Go 버전에 따라 다름
    magics = {
        b'\xfb\xff\xff\xff\x00\x00': "Go 1.2-1.15",
        b'\xfa\xff\xff\xff\x00\x00': "Go 1.16-1.17",
        b'\xf1\xff\xff\xff\x00\x00': "Go 1.18-1.19",
        b'\xf0\xff\xff\xff\x00\x00': "Go 1.20+",
    }

    for magic, version in magics.items():
        offset = data.find(magic)
        if offset != -1:
            print(f"[+] pclntab 오프셋 0x{offset:x} ({version})")
            return offset, version

    return None, None


def extract_function_names(data, pclntab_offset):
    """pclntab에서 함수 이름 추출."""
    if pclntab_offset is None:
        return []

    functions = []
    # 함수 이름 문자열은 특정 패턴을 따름
    func_pattern = re.compile(
        rb'(?:main|runtime|fmt|net|os|crypto|encoding|io|sync|'
        rb'syscall|reflect|strings|bytes|path|time|math|sort|'
        rb'github\.com|golang\.org)[/\.][\w/.]+',
    )

    for match in func_pattern.finditer(data):
        name = match.group().decode('utf-8', errors='replace')
        if len(name) > 4 and len(name) < 200:
            functions.append(name)

    return sorted(set(functions))


def extract_go_strings(data):
    """Go 스타일 문자열 추출 (포인터+길이 쌍)."""
    # Go 문자열은 널 종료되지 않음; 읽을 수 있는 시퀀스 추출
    strings = []
    ascii_pattern = re.compile(rb'[\x20-\x7e]{10,}')

    for match in ascii_pattern.finditer(data):
        s = match.group().decode('ascii')
        # 흥미로운 악성코드 문자열 필터링
        interesting = [
            'http', 'https', 'tcp', 'udp', 'dns',
            'cmd', 'shell', 'exec', 'upload', 'download',
            'encrypt', 'decrypt', 'key', 'token', 'password',
            'c2', 'beacon', 'agent', 'implant', 'bot',
            'mutex', 'persist', 'registry', 'scheduled',
        ]
        if any(kw in s.lower() for kw in interesting):
            strings.append(s)

    return strings


def extract_dependencies(data):
    """바이너리에서 Go 모듈 의존성 추출."""
    deps = []
    # 모듈 경로 패턴: github.com/user/repo
    dep_pattern = re.compile(
        rb'((?:github\.com|gitlab\.com|golang\.org|gopkg\.in|'
        rb'go\.etcd\.io|google\.golang\.org)/[^\x00\s]{5,80})'
    )

    for match in dep_pattern.finditer(data):
        dep = match.group().decode('utf-8', errors='replace')
        deps.append(dep)

    unique_deps = sorted(set(deps))
    return unique_deps


def analyze_go_binary(filepath):
    """Go 악성코드 바이너리 전체 분석."""
    with open(filepath, 'rb') as f:
        data = f.read()

    print(f"[+] Go 바이너리 분석 중: {filepath}")
    print(f"  파일 크기: {len(data):,} 바이트")
    print("=" * 60)

    # 빌드 정보
    find_go_build_info(data)

    # pclntab
    pclntab_offset, go_version = find_pclntab(data)

    # 함수
    functions = extract_function_names(data, pclntab_offset)
    print(f"\n[+] 복구된 함수 이름: {len(functions)}개")

    # 함수 분류
    categories = {
        "network": [], "crypto": [], "os_exec": [],
        "file_io": [], "main": [], "third_party": [],
    }
    for f in functions:
        if 'net/' in f or 'http' in f.lower():
            categories["network"].append(f)
        elif 'crypto' in f:
            categories["crypto"].append(f)
        elif 'os/exec' in f or 'syscall' in f:
            categories["os_exec"].append(f)
        elif 'os.' in f or 'io/' in f:
            categories["file_io"].append(f)
        elif f.startswith('main.'):
            categories["main"].append(f)
        elif 'github.com' in f or 'golang.org' in f:
            categories["third_party"].append(f)

    for cat, funcs in categories.items():
        if funcs:
            print(f"\n  [{cat}] ({len(funcs)}개 함수):")
            for fn in funcs[:10]:
                print(f"    {fn}")

    # 의존성
    deps = extract_dependencies(data)
    print(f"\n[+] 의존성 ({len(deps)}개):")
    for dep in deps[:20]:
        print(f"    {dep}")

    # 의심스러운 문자열
    sus_strings = extract_go_strings(data)
    print(f"\n[+] 의심스러운 문자열 ({len(sus_strings)}개):")
    for s in sus_strings[:20]:
        print(f"    {s}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"사용법: {sys.argv[0]} <go_binary>")
        sys.exit(1)
    analyze_go_binary(sys.argv[1])

단계 2: Ghidra 분석 스크립트

# Ghidra 스크립트 (Ghidra 스크립트 매니저 내에서 실행)
# Ghidra 스크립트 디렉토리에 AnalyzeGoBinary.py로 저장

# @category MalwareAnalysis
# @description Go 바이너리 구조 분석 및 메타데이터 복구

def analyze_go_binary_ghidra():
    """Go 바이너리 분석용 Ghidra 스크립트."""
    from ghidra.program.model.mem import MemoryAccessException

    program = getCurrentProgram()
    memory = program.getMemory()
    listing = program.getListing()

    print("[+] Go 바이너리 분석 스크립트")
    print(f"  프로그램: {program.getName()}")

    # pclntab 찾기
    pclntab_magics = [
        bytes([0xf0, 0xff, 0xff, 0xff]),  # Go 1.20+
        bytes([0xf1, 0xff, 0xff, 0xff]),  # Go 1.18-1.19
        bytes([0xfa, 0xff, 0xff, 0xff]),  # Go 1.16-1.17
        bytes([0xfb, 0xff, 0xff, 0xff]),  # Go 1.2-1.15
    ]

    for magic in pclntab_magics:
        addr = memory.findBytes(
            program.getMinAddress(), magic, None, True, None
        )
        if addr:
            print(f"[+] pclntab 발견 위치: {addr}")
            # 레이블 생성
            program.getSymbolTable().createLabel(
                addr, "go_pclntab", None,
                ghidra.program.model.symbol.SourceType.ANALYSIS
            )
            break

    # Go 문자열 정의 수정
    # Go 문자열은 ptr+len, 널 종료 아님
    print("[+] Go 문자열 참조 수정 중...")

    # 패키지 경로를 포함하는 함수 이름 검색
    symbol_table = program.getSymbolTable()
    func_count = 0
    for symbol in symbol_table.getAllSymbols(True):
        name = symbol.getName()
        if ('.' in name and
            any(pkg in name for pkg in
                ['main.', 'runtime.', 'net.', 'crypto.', 'os.'])):
            func_count += 1

    print(f"[+] {func_count}개의 Go 함수 심볼 발견")


# 실행
analyze_go_binary_ghidra()

검증 기준

  • 바이너리에서 Go 버전 및 빌드 정보 추출 확인
  • pclntab 위치 식별 및 함수 이름 복구를 위한 파싱
  • 타사 의존성 식별을 통한 악성코드 기능 파악
  • 대상 분석을 위한 main 패키지 함수 열거
  • 네트워크, 암호화, OS 실행 함수 분류
  • Ghidra 분석이 Go 런타임 구조를 올바르게 레이블링

참조 자료

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

관련 스킬