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 런타임 구조를 올바르게 레이블링