OPEN HYPER STEP
← 목록으로 (화이트햇 보안)
SECURITY · 70 / 84
security
CHAPTER 70 / 84
읽기 약 2
FUNCTION

네트워크 응답 분석


핵심 개념

ICMP ping, traceroute, DNS 조회로 호스트와 네트워크 경로를 분석한다.

본문

ICMP Ping — 호스트 살아있는지

PYTHON📋 코드 (38줄)
# ⚠️ 이 코드는 허가된 환경에서만 사용하세요.
import subprocess
import platform
import re

def ping(host: str, count: int = 3, timeout: int = 2) -> dict:
    """크로스플랫폼 ping — subprocess로 시스템 ping 호출."""
    is_windows = platform.system().lower() == 'windows'
    args = ['ping']

    if is_windows:
        args += ['-n', str(count), '-w', str(timeout * 1000), host]
    else:
        args += ['-c', str(count), '-W', str(timeout), host]

    try:
        result = subprocess.run(args, capture_output=True, text=True, timeout=timeout * count + 5)
        output = result.stdout

        # 응답 시간 추출
        rtts = [float(m) for m in re.findall(r'time[=<](\d+\.?\d*)\s*ms', output)]
        loss_match = re.search(r'(\d+)%\s*(?:packet )?loss', output)

        return {
            'host': host,
            'alive': result.returncode == 0,
            'rtt_avg_ms': sum(rtts) / len(rtts) if rtts else None,
            'rtt_min_ms': min(rtts) if rtts else None,
            'rtt_max_ms': max(rtts) if rtts else None,
            'loss_percent': int(loss_match.group(1)) if loss_match else None,
        }
    except subprocess.TimeoutExpired:
        return {'host': host, 'alive': False, 'error': 'timeout'}
    except FileNotFoundError:
        return {'host': host, 'alive': False, 'error': 'ping not found'}

# print(ping('localhost'))
# {'host': 'localhost', 'alive': True, 'rtt_avg_ms': 0.05, 'loss_percent': 0}

Traceroute — 경로 추적

PYTHON📋 코드 (25줄)
# ⚠️ 이 코드는 허가된 환경에서만 사용하세요.
def traceroute(host: str, max_hops: int = 30, timeout: float = 2.0) -> list[dict]:
    """경로상 라우터들 추적."""
    is_windows = platform.system().lower() == 'windows'
    cmd = 'tracert' if is_windows else 'traceroute'
    args = [cmd, '-m', str(max_hops), host]

    if not is_windows:
        args = [cmd, '-w', str(int(timeout)), '-m', str(max_hops), host]

    try:
        result = subprocess.run(args, capture_output=True, text=True, timeout=timeout * max_hops + 10)
        hops = []
        for line in result.stdout.split('\n'):
            # "1  192.168.1.1  0.5 ms"
            m = re.match(r'\s*(\d+)\s+(\S+)\s+(.+)', line)
            if m:
                hops.append({
                    'hop': int(m.group(1)),
                    'host': m.group(2),
                    'detail': m.group(3),
                })
        return hops
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return []

DNS 조회 — dnspython

PYTHON📋 코드 (38줄)
# pip install dnspython
# ⚠️ 이 코드는 허가된 환경에서만 사용하세요.
import dns.resolver

def dns_lookup(domain: str, record_types: list[str] = None) -> dict:
    """도메인의 DNS 레코드 전체 수집."""
    if record_types is None:
        record_types = ['A', 'AAAA', 'MX', 'NS', 'TXT', 'SOA', 'CNAME']

    result = {'domain': domain, 'records': {}}

    for rtype in record_types:
        try:
            answers = dns.resolver.resolve(domain, rtype, lifetime=5)
            result['records'][rtype] = [str(r) for r in answers]
        except dns.resolver.NoAnswer:
            result['records'][rtype] = []
        except dns.resolver.NXDOMAIN:
            result['error'] = '도메인 존재 안 함'
            return result
        except dns.exception.Timeout:
            result['records'][rtype] = ['timeout']

    return result

# print(dns_lookup('github.com'))
"""
{
  'domain': 'github.com',
  'records': {
    'A': ['140.82.121.4'],
    'MX': ['1 aspmx.l.google.com.', ...],
    'NS': ['dns1.p08.nsone.net.', ...],
    'TXT': ['v=spf1 ip4:192.30.252.0/22 ...'],
    ...
  }
}
"""

실습: 도메인 종합 정찰

PYTHON📋 코드 (36줄)
def domain_recon(domain: str) -> dict:
    """DNS + Ping + 서브도메인 추정 종합."""
    result = {'domain': domain}

    # 1. DNS 레코드
    result['dns'] = dns_lookup(domain)

    # 2. A 레코드의 첫 IP에 ping
    a_records = result['dns']['records'].get('A', [])
    if a_records:
        result['ping'] = ping(a_records[0])

    # 3. SPF/DMARC 보안 레코드 점검
    txt = result['dns']['records'].get('TXT', [])
    result['security'] = {
        'spf': any('v=spf1' in t for t in txt),
        'dmarc': False,  # _dmarc.도메인 별도 조회 필요
    }
    try:
        dmarc = dns.resolver.resolve(f'_dmarc.{domain}', 'TXT', lifetime=5)
        result['security']['dmarc'] = any('v=DMARC1' in str(r) for r in dmarc)
    except Exception:
        pass

    # 4. 일반적 서브도메인 추정
    common_subs = ['www', 'mail', 'api', 'admin', 'dev', 'staging', 'blog']
    found_subs = []
    for sub in common_subs:
        try:
            dns.resolver.resolve(f'{sub}.{domain}', 'A', lifetime=2)
            found_subs.append(f'{sub}.{domain}')
        except Exception:
            pass
    result['subdomains'] = found_subs

    return result

⚠️ 윤리적 고려

  • DNS 조회는 공개 정보 — 합법
  • Ping/Traceroute는 수동 정찰 — 일반적으로 합법
  • 단, 너무 빠른 반복 → DoS로 간주될 수 있음
  • 서브도메인 브루트포스(1만+ 단어 사전) → 일부 국가에서 위법

AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude

무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6

내 DNS/ping 코드에서
subprocess 보안·인코딩·예외 처리를 분석하고
안전한 형태로 리팩토링해줘.
ChatGPT

무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro

dnspython으로
SPF/DMARC/DKIM 이메일 보안 레코드
전체 점검 코드를 보여줘.
Gemini

무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro

내 도메인 정찰 결과를 분석해서
DNS·서브도메인·이메일 보안 측면
취약점 종합 리포트를 만들어줘.
Grok

무료: Grok 4.1 / SuperGrok $30/mo

2026년 DNS 보안 트렌드 —
DoH/DoT 채택률과 1인 SaaS의 도메인 보호 우선순위를
솔직히 알려줘.

⭐ 이것만 기억하세요
네트워크 응답 분석 이 3가지만 확실히 잡으세요
1.subprocess + 시스템 ping/tracert로 크로스플랫폼 네트워크 진단을 만들 수 있다
2.dnspython으로 A/MX/TXT/NS/SOA 레코드를 한 번에 수집해 도메인 정찰을 자동화한다
3.다음 챕터에서 서브넷 전체를 스캔하는 ARP 기반 호스트 디스커버리를 배운다


공유하기
진행도 70 / 84