Communitygithub.com

멀웨어 네트워크 은닉 채널 분석

멀웨어가 사용하는 은밀한 통신 채널을 탐지하고 분석합니다. DNS 터널링, ICMP 터널링, HTTP 은닉 채널 등 다양한 기법을 포함합니다.

멀웨어 네트워크 은닉 채널 분석란 무엇인가요?

이 스킬은 멀웨어가 C2(Command & Control) 통신 및 데이터 유출에 사용하는 네트워크 은닉 채널(Covert Channel)을 탐지하고 분석하는 방법을 제공합니다. DNS 터널링은 DNS 쿼리/응답에 데이터를 인코딩하며, ICMP 터널링은 에코 요청/응답 페이로드에 데이터를 숨깁니다. HTTP 은닉 채널은 헤더, 쿠키, 스테가노그래피 이미지에 C2 데이터를 포함시킵니다. 이 스킬은 Scapy, dpkt, dnslib 같은 Python 라이브러리를 활용하여 PCAP 파일을 분석하고, 엔트로피, 서브도메인 길이, 페이로드 크기 이상값과 같은 지표를 기반으로 의심스러운 패턴을 자동으로 채점합니다. Palo Alto Unit42의 최신 DNS 터널링 캠페인 사례를 참조하며, SOC 분석가나 위협 헌팅 담당자가 체계적인 절차를 따라 은닉 채널을 탐지하고 검증할 수 있도록 설계되었습니다.

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

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

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

문서

멀웨어 네트워크 은닉 채널 분석은(는) 무엇을 하나요?

개요

멀웨어는 은닉 채널을 사용하여 정상적인 네트워크 트래픽처럼 위장한 C2 통신과 데이터 유출을 수행합니다. DNS 터널링은 DNS 쿼리와 응답에 데이터를 인코딩하며(iodine, dnscat2, FrameworkPOS와 같은 멀웨어 계열에서 사용), ICMP 터널링은 에코 요청/응답 페이로드에 데이터를 숨깁니다(icmpsh, ptunnel). HTTP 은닉 채널은 헤더, 쿠키 또는 스테가노그래피 이미지에 C2 데이터를 포함시킵니다. 프로토콜 남용은 허용된 프로토콜을 이용해 방화벽을 우회합니다. DNS 터널링 탐지는 최신 ML 기반 접근 방식으로 99% 이상의 재현율을 달성하지만, 저처리량 유출은 여전히 어려운 과제입니다. Palo Alto Unit42는 2024년까지 TrkCdn, SecShow, Savvy Seahorse라는 세 가지 주요 DNS 터널링 캠페인을 추적하여 해당 기법의 지속적인 확산을 보여주었습니다.

사용 시기

  • 멀웨어의 네트워크 은닉 채널 분석이 필요한 보안 사고를 조사할 때
  • 이 도메인에 대한 탐지 규칙 또는 위협 헌팅 쿼리를 구축할 때
  • SOC 분석가가 이 분석 유형에 대한 구조화된 절차를 필요로 할 때
  • 관련 공격 기법에 대한 보안 모니터링 적용 범위를 검증할 때

사전 요구 사항

  • Python 3.9+ 및 scapy, dpkt, dnslib
  • PCAP 분석을 위한 Wireshark/tshark
  • 네트워크 모니터링을 위한 Zeek (구 Bro)
  • DNS 쿼리 로깅 인프라
  • 패킷 수준의 DNS, ICMP, HTTP 프로토콜 이해

워크플로우

1단계: DNS 터널링 탐지

#!/usr/bin/env python3
"""네트워크 트래픽에서 DNS 터널링 및 은닉 채널을 탐지합니다."""
import sys
import json
import math
from collections import Counter, defaultdict

try:
    from scapy.all import rdpcap, DNS, DNSQR, DNSRR, IP, ICMP
except ImportError:
    print("pip install scapy")
    sys.exit(1)


def entropy(data):
    if not data:
        return 0
    freq = Counter(data)
    length = len(data)
    return -sum((c/length) * math.log2(c/length) for c in freq.values())


def analyze_dns_tunneling(pcap_path):
    """PCAP에서 DNS 터널링 지표를 탐지합니다."""
    packets = rdpcap(pcap_path)
    domain_stats = defaultdict(lambda: {
        "queries": 0, "total_qname_len": 0, "subdomain_lengths": [],
        "query_types": Counter(), "unique_subdomains": set(),
    })

    for pkt in packets:
        if pkt.haslayer(DNS) and pkt.haslayer(DNSQR):
            qname = pkt[DNSQR].qname.decode('utf-8', errors='replace').rstrip('.')
            qtype = pkt[DNSQR].qtype

            parts = qname.split('.')
            if len(parts) >= 3:
                base_domain = '.'.join(parts[-2:])
                subdomain = '.'.join(parts[:-2])

                stats = domain_stats[base_domain]
                stats["queries"] += 1
                stats["total_qname_len"] += len(qname)
                stats["subdomain_lengths"].append(len(subdomain))
                stats["query_types"][qtype] += 1
                stats["unique_subdomains"].add(subdomain)

    # 터널링 지표에 따라 도메인 점수 부여
    suspicious = []
    for domain, stats in domain_stats.items():
        if stats["queries"] < 5:
            continue

        avg_subdomain_len = (sum(stats["subdomain_lengths"]) /
                             len(stats["subdomain_lengths"]))
        unique_ratio = len(stats["unique_subdomains"]) / stats["queries"]

        # 서브도메인 엔트로피 계산
        all_subdomains = ''.join(stats["unique_subdomains"])
        sub_entropy = entropy(all_subdomains)

        score = 0
        reasons = []

        if avg_subdomain_len > 30:
            score += 30
            reasons.append(f"긴 서브도메인 (평균 {avg_subdomain_len:.0f}자)")
        if unique_ratio > 0.9:
            score += 25
            reasons.append(f"높은 고유성 ({unique_ratio:.2%})")
        if sub_entropy > 4.0:
            score += 25
            reasons.append(f"높은 엔트로피 ({sub_entropy:.2f})")
        if stats["query_types"].get(16, 0) > 10:  # TXT 레코드
            score += 20
            reasons.append(f"많은 TXT 쿼리 ({stats['query_types'][16]})")

        if score >= 50:
            suspicious.append({
                "domain": domain,
                "score": score,
                "queries": stats["queries"],
                "avg_subdomain_length": round(avg_subdomain_len, 1),
                "unique_subdomains": len(stats["unique_subdomains"]),
                "subdomain_entropy": round(sub_entropy, 2),
                "reasons": reasons,
            })

    return sorted(suspicious, key=lambda x: -x["score"])


def analyze_icmp_tunneling(pcap_path):
    """PCAP에서 ICMP 터널링을 탐지합니다."""
    packets = rdpcap(pcap_path)
    icmp_stats = defaultdict(lambda: {"count": 0, "payload_sizes": [], "payloads": []})

    for pkt in packets:
        if pkt.haslayer(ICMP) and pkt.haslayer(IP):
            src = pkt[IP].src
            dst = pkt[IP].dst
            key = f"{src}->{dst}"

            payload = bytes(pkt[ICMP].payload)
            icmp_stats[key]["count"] += 1
            icmp_stats[key]["payload_sizes"].append(len(payload))
            if len(payload) > 64:
                icmp_stats[key]["payloads"].append(payload[:100])

    suspicious = []
    for flow, stats in icmp_stats.items():
        if stats["count"] < 5:
            continue
        avg_size = sum(stats["payload_sizes"]) / len(stats["payload_sizes"])
        if avg_size > 64 or stats["count"] > 100:
            suspicious.append({
                "flow": flow,
                "packets": stats["count"],
                "avg_payload_size": round(avg_size, 1),
                "reason": "크거나 빈번한 ICMP 페이로드는 터널링을 암시합니다.",
            })

    return suspicious


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

    print("[+] DNS 터널링 분석")
    dns_results = analyze_dns_tunneling(sys.argv[1])
    for r in dns_results:
        print(f"  {r['domain']} (점수: {r['score']})")
        for reason in r['reasons']:
            print(f"    - {reason}")

    print("\n[+] ICMP 터널링 분석")
    icmp_results = analyze_icmp_tunneling(sys.argv[1])
    for r in icmp_results:
        print(f"  {r['flow']}: {r['reason']}")

검증 기준

  • DNS 터널링은 엔트로피, 서브도메인 길이 및 쿼리 볼륨 분석을 통해 탐지
  • ICMP 은닉 채널은 페이로드 크기 이상값을 통해 식별
  • 터널링 도메인은 합법적인 CDN/클라우드 트래픽과 구분
  • 캡처된 트래픽에서 데이터 유출량 추정
  • C2 통신 패턴 및 비콘 간격 추출

참고 자료

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,

관련 스킬