SiamCafe.net Blog
Cybersecurity

penetration testing in cyber security

penetration testing in cyber security
penetration testing in cyber security | SiamCafe Blog
2025-10-04· อ. บอม — SiamCafe.net· 1,940 คำ

Penetration Testing in Cyber Security — คู่มือฉบับสมบูรณ์

Penetration Testing (Pentest) คือการทดสอบความปลอดภัยของระบบโดยจำลองการโจมตีจริง เพื่อค้นหา vulnerabilities ก่อนที่ผู้ไม่หวังดีจะพบ เป็นส่วนสำคัญของ cybersecurity strategy ทุกองค์กร Pentester (Ethical Hacker) ใช้เครื่องมือและเทคนิคเดียวกับ hackers แต่ทำภายใต้ขอบเขตที่ได้รับอนุญาต ผลลัพธ์คือ report ที่ระบุ vulnerabilities, risk level และ remediation recommendations บทความนี้อธิบายกระบวนการ pentest ทุกขั้นตอน พร้อม Python tools สำหรับ security testing

Penetration Testing Methodology

# pentest_methodology.py — Pentest phases
import json

class PentestMethodology:
    PHASES = {
        "planning": {
            "name": "1. Planning & Scope",
            "description": "กำหนดขอบเขต เป้าหมาย กฎเกณฑ์ของการทดสอบ",
            "activities": [
                "กำหนด scope: IP ranges, domains, applications ที่จะทดสอบ",
                "ประเภท test: Black box, White box, Gray box",
                "กฎเกณฑ์: Rules of Engagement (RoE)",
                "ลงนาม NDA + Authorization letter",
                "กำหนด timeline + communication channels",
            ],
        },
        "recon": {
            "name": "2. Reconnaissance (Information Gathering)",
            "description": "รวบรวมข้อมูลเป้าหมายให้มากที่สุด",
            "activities": [
                "Passive recon: OSINT, DNS, WHOIS, social media, Google dorking",
                "Active recon: Port scanning (Nmap), service enumeration",
                "Subdomain discovery: Subfinder, Amass, crt.sh",
                "Technology fingerprinting: Wappalyzer, WhatWeb",
            ],
        },
        "scanning": {
            "name": "3. Scanning & Vulnerability Assessment",
            "description": "สแกนหา vulnerabilities ในระบบ",
            "activities": [
                "Vulnerability scanning: Nessus, OpenVAS, Nuclei",
                "Web app scanning: Burp Suite, OWASP ZAP, Nikto",
                "Configuration audit: CIS Benchmarks, Lynis",
                "SSL/TLS testing: testssl.sh, SSL Labs",
            ],
        },
        "exploitation": {
            "name": "4. Exploitation",
            "description": "พยายาม exploit vulnerabilities ที่พบ",
            "activities": [
                "Manual exploitation: custom scripts, known CVEs",
                "Framework: Metasploit, Cobalt Strike",
                "Web attacks: SQLi, XSS, SSRF, RCE",
                "Privilege escalation: local exploits, misconfigurations",
                "Lateral movement: pivoting, pass-the-hash",
            ],
        },
        "post_exploitation": {
            "name": "5. Post-Exploitation",
            "description": "ประเมินผลกระทบหลัง exploit สำเร็จ",
            "activities": [
                "Data exfiltration assessment: sensitive data access",
                "Persistence: ทดสอบว่าสามารถคงอยู่ในระบบได้ไหม",
                "Pivot to other systems: lateral movement",
                "Clean up: ลบ artifacts ที่สร้างไว้",
            ],
        },
        "reporting": {
            "name": "6. Reporting",
            "description": "เขียนรายงานสรุปผลการทดสอบ",
            "activities": [
                "Executive Summary: สรุปสำหรับผู้บริหาร",
                "Technical Details: รายละเอียด vulnerability + proof of concept",
                "Risk Rating: Critical, High, Medium, Low, Informational",
                "Remediation: คำแนะนำแก้ไข + priority",
            ],
        },
    }

    def show_phases(self):
        print("=== Pentest Methodology ===\n")
        for key, phase in self.PHASES.items():
            print(f"[{phase['name']}]")
            print(f"  {phase['description']}")
            for act in phase['activities'][:3]:
                print(f"    • {act}")
            print()

method = PentestMethodology()
method.show_phases()

Python Recon Tools

# recon_tools.py — Python reconnaissance tools
import json

class ReconTools:
    CODE = """
# recon.py — Automated reconnaissance toolkit
import socket
import ssl
import json
import subprocess
from datetime import datetime

class ReconToolkit:
    def __init__(self, target):
        self.target = target
        self.results = {}
    
    def dns_lookup(self):
        '''DNS resolution'''
        try:
            ip = socket.gethostbyname(self.target)
            aliases = socket.getfqdn(self.target)
            
            # Reverse DNS
            try:
                reverse = socket.gethostbyaddr(ip)
            except:
                reverse = None
            
            self.results['dns'] = {
                'ip': ip,
                'fqdn': aliases,
                'reverse_dns': reverse[0] if reverse else None,
            }
        except Exception as e:
            self.results['dns'] = {'error': str(e)}
        return self.results['dns']
    
    def port_scan(self, ports=None):
        '''Basic port scanner'''
        if ports is None:
            ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 445,
                     993, 995, 3306, 3389, 5432, 8080, 8443]
        
        open_ports = []
        for port in ports:
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(2)
                result = sock.connect_ex((self.target, port))
                if result == 0:
                    try:
                        service = socket.getservbyport(port)
                    except:
                        service = 'unknown'
                    open_ports.append({'port': port, 'service': service})
                sock.close()
            except:
                pass
        
        self.results['ports'] = open_ports
        return open_ports
    
    def ssl_info(self):
        '''Get SSL/TLS certificate info'''
        try:
            context = ssl.create_default_context()
            with socket.create_connection((self.target, 443), timeout=10) as sock:
                with context.wrap_socket(sock, server_hostname=self.target) as ssock:
                    cert = ssock.getpeercert()
                    
                    expire = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
                    days_left = (expire - datetime.utcnow()).days
                    
                    self.results['ssl'] = {
                        'version': ssock.version(),
                        'cipher': ssock.cipher()[0],
                        'issuer': dict(x[0] for x in cert['issuer']),
                        'expires': expire.isoformat(),
                        'days_left': days_left,
                        'san': [e[1] for e in cert.get('subjectAltName', [])],
                    }
        except Exception as e:
            self.results['ssl'] = {'error': str(e)}
        return self.results.get('ssl', {})
    
    def http_headers(self):
        '''Check HTTP security headers'''
        import requests
        try:
            resp = requests.get(f"https://{self.target}", timeout=10, verify=True)
            headers = dict(resp.headers)
            
            security_headers = {
                'Strict-Transport-Security': headers.get('Strict-Transport-Security', 'MISSING'),
                'Content-Security-Policy': headers.get('Content-Security-Policy', 'MISSING'),
                'X-Frame-Options': headers.get('X-Frame-Options', 'MISSING'),
                'X-Content-Type-Options': headers.get('X-Content-Type-Options', 'MISSING'),
                'X-XSS-Protection': headers.get('X-XSS-Protection', 'MISSING'),
                'Referrer-Policy': headers.get('Referrer-Policy', 'MISSING'),
            }
            
            missing = [k for k, v in security_headers.items() if v == 'MISSING']
            
            self.results['headers'] = {
                'security_headers': security_headers,
                'missing_count': len(missing),
                'server': headers.get('Server', 'Not disclosed'),
            }
        except Exception as e:
            self.results['headers'] = {'error': str(e)}
        return self.results.get('headers', {})
    
    def full_recon(self):
        '''Run all recon modules'''
        self.dns_lookup()
        self.port_scan()
        self.ssl_info()
        self.http_headers()
        return self.results

# recon = ReconToolkit("example.com")
# results = recon.full_recon()
# print(json.dumps(results, indent=2, default=str))
"""

    def show_code(self):
        print("=== Recon Toolkit ===")
        print(self.CODE[:600])

tools = ReconTools()
tools.show_code()

Web Application Testing

# webapp_test.py — Web application security testing
import json

class WebAppTesting:
    OWASP_TOP10 = {
        "A01": {
            "name": "Broken Access Control",
            "description": "ผู้ใช้เข้าถึงข้อมูล/ฟังก์ชันที่ไม่มีสิทธิ์",
            "test": "IDOR, privilege escalation, forced browsing",
        },
        "A02": {
            "name": "Cryptographic Failures",
            "description": "การเข้ารหัสอ่อนแอ — data exposure",
            "test": "Weak TLS, plaintext passwords, weak hashing",
        },
        "A03": {
            "name": "Injection",
            "description": "SQL injection, XSS, command injection",
            "test": "SQLi payloads, XSS vectors, OS command tests",
        },
        "A04": {
            "name": "Insecure Design",
            "description": "ออกแบบระบบไม่ปลอดภัย — ไม่มี threat modeling",
            "test": "Business logic flaws, missing rate limiting",
        },
        "A05": {
            "name": "Security Misconfiguration",
            "description": "ตั้งค่าไม่ถูกต้อง — default credentials, verbose errors",
            "test": "Default configs, unnecessary features, error disclosure",
        },
    }

    SQLI_TEST = """
# sqli_test.py — SQL Injection testing
import requests

class SQLiTester:
    PAYLOADS = [
        "' OR '1'='1",
        "' OR '1'='1'--",
        "1' UNION SELECT NULL--",
        "1' UNION SELECT NULL, NULL--",
        "admin'--",
        "1; DROP TABLE users--",
        "' AND 1=1--",
        "' AND 1=2--",
    ]
    
    def test_sqli(self, url, param):
        '''Test URL parameter for SQL injection'''
        results = []
        baseline = requests.get(url, params={param: "normal"})
        
        for payload in self.PAYLOADS:
            try:
                resp = requests.get(url, params={param: payload}, timeout=10)
                
                suspicious = False
                indicators = []
                
                if resp.status_code != baseline.status_code:
                    suspicious = True
                    indicators.append(f"Status changed: {baseline.status_code} -> {resp.status_code}")
                
                if len(resp.text) != len(baseline.text):
                    diff = abs(len(resp.text) - len(baseline.text))
                    if diff > 100:
                        suspicious = True
                        indicators.append(f"Content length diff: {diff}")
                
                error_keywords = ['sql', 'mysql', 'syntax', 'error', 'query']
                for kw in error_keywords:
                    if kw in resp.text.lower():
                        suspicious = True
                        indicators.append(f"Error keyword: {kw}")
                
                if suspicious:
                    results.append({
                        'payload': payload,
                        'indicators': indicators,
                    })
            except:
                pass
        
        return results

# tester = SQLiTester()
# vulns = tester.test_sqli("http://target.com/search", "q")
"""

    def show_owasp(self):
        print("=== OWASP Top 10 ===\n")
        for code, item in self.OWASP_TOP10.items():
            print(f"[{code}: {item['name']}]")
            print(f"  {item['description']}")
            print(f"  Test: {item['test']}")
            print()

    def show_sqli(self):
        print("=== SQLi Testing ===")
        print(self.SQLI_TEST[:500])

webapp = WebAppTesting()
webapp.show_owasp()
webapp.show_sqli()

Essential Pentest Tools

# tools.py — Essential penetration testing tools
import json

class PentestTools:
    TOOLS = {
        "nmap": {
            "name": "Nmap",
            "category": "Network Scanning",
            "description": "Port scanner + service detection + OS fingerprinting",
            "usage": "nmap -sV -sC -O target.com",
            "license": "Free / Open Source",
        },
        "burp_suite": {
            "name": "Burp Suite",
            "category": "Web Application Testing",
            "description": "HTTP proxy + scanner + repeater + intruder",
            "usage": "GUI — intercept, modify, replay HTTP requests",
            "license": "Community (free) / Professional ($449/yr)",
        },
        "metasploit": {
            "name": "Metasploit Framework",
            "category": "Exploitation",
            "description": "Exploitation framework — exploit modules, payloads, post-exploitation",
            "usage": "msfconsole → search exploit → set options → exploit",
            "license": "Community (free) / Pro (commercial)",
        },
        "nuclei": {
            "name": "Nuclei",
            "category": "Vulnerability Scanning",
            "description": "Template-based vulnerability scanner — fast, customizable",
            "usage": "nuclei -u target.com -t templates/",
            "license": "Free / Open Source",
        },
        "sqlmap": {
            "name": "SQLMap",
            "category": "SQL Injection",
            "description": "Automated SQL injection detection + exploitation",
            "usage": "sqlmap -u 'http://target.com/page?id=1' --dbs",
            "license": "Free / Open Source",
        },
        "john": {
            "name": "John the Ripper",
            "category": "Password Cracking",
            "description": "Password hash cracker — brute force, dictionary, rules",
            "usage": "john --wordlist=rockyou.txt hashes.txt",
            "license": "Free / Open Source",
        },
        "wireshark": {
            "name": "Wireshark",
            "category": "Network Analysis",
            "description": "Packet analyzer — capture + analyze network traffic",
            "usage": "GUI — filter protocols, follow streams, decode packets",
            "license": "Free / Open Source",
        },
    }

    def show_tools(self):
        print("=== Essential Pentest Tools ===\n")
        for key, tool in self.TOOLS.items():
            print(f"[{tool['name']}] ({tool['category']})")
            print(f"  {tool['description']}")
            print(f"  Usage: {tool['usage']}")
            print()

tools = PentestTools()
tools.show_tools()

Reporting & Career Path

# reporting.py — Pentest reporting and career
import json

class PentestCareer:
    REPORT_TEMPLATE = {
        "executive_summary": "สรุป 1-2 หน้า สำหรับผู้บริหาร — overall risk, critical findings",
        "scope": "ขอบเขตการทดสอบ — targets, methodology, timeline",
        "findings": "รายละเอียด vulnerabilities — severity, description, POC, fix",
        "risk_matrix": "Critical/High/Medium/Low/Info — count + breakdown",
        "remediation": "คำแนะนำแก้ไข — priority, effort, timeline",
        "appendix": "Raw data, tool outputs, screenshots",
    }

    CERTIFICATIONS = {
        "ceh": {"name": "CEH (Certified Ethical Hacker)", "level": "Entry", "cost": "~$1,199"},
        "oscp": {"name": "OSCP (Offensive Security Certified Professional)", "level": "Intermediate", "cost": "~$1,599"},
        "oswe": {"name": "OSWE (Offensive Security Web Expert)", "level": "Advanced", "cost": "~$1,599"},
        "gpen": {"name": "GPEN (GIAC Penetration Tester)", "level": "Intermediate", "cost": "~$2,499"},
        "ewpt": {"name": "eWPT (eLearnSecurity Web Application Penetration Tester)", "level": "Intermediate", "cost": "~$400"},
    }

    CAREER_PATH = [
        "Junior Pentester / SOC Analyst — เรียนรู้เครื่องมือ + methodology",
        "Penetration Tester — ทำ pentest projects อิสระ",
        "Senior Pentester — lead engagements, mentor juniors",
        "Red Team Lead — simulate APT attacks, adversary emulation",
        "Security Consultant / CISO — strategy + advisory",
    ]

    def show_report(self):
        print("=== Report Template ===\n")
        for section, desc in self.REPORT_TEMPLATE.items():
            print(f"  [{section}] {desc}")

    def show_certs(self):
        print(f"\n=== Certifications ===")
        for key, cert in self.CERTIFICATIONS.items():
            print(f"  [{cert['name']}] Level: {cert['level']}, Cost: {cert['cost']}")

    def show_career(self):
        print(f"\n=== Career Path ===")
        for step in self.CAREER_PATH:
            print(f"  → {step}")

career = PentestCareer()
career.show_report()
career.show_certs()
career.show_career()

FAQ - คำถามที่พบบ่อย

Q: Pentest กับ Vulnerability Assessment ต่างกันอย่างไร?

A: VA: สแกนหา vulnerabilities อัตโนมัติ — ไม่ exploit, แค่ list ปัญหา Pentest: ทำทั้ง scan + exploit จริง — พิสูจน์ว่า vulnerability สามารถถูกใช้โจมตีได้ VA: เร็ว ถูก ทำบ่อยได้ (quarterly) Pentest: ละเอียด แพงกว่า ทำ 1-2 ครั้ง/ปี ทั้งสองจำเป็น: VA สำหรับ routine checks, Pentest สำหรับ deep assessment

Q: Black Box, White Box, Gray Box ต่างกันอย่างไร?

A: Black Box: pentester ไม่มีข้อมูลระบบ — จำลอง external attacker White Box: pentester มีข้อมูลทั้งหมด (source code, architecture, credentials) — ละเอียดที่สุด Gray Box: pentester มีข้อมูลบางส่วน (user credentials, partial docs) — สมจริง + มีประสิทธิภาพ แนะนำ: Gray Box — balance ระหว่าง realistic + thorough

Q: เรียน Pentest เริ่มจากไหน?

A: ขั้นตอน: 1) เรียน networking + Linux basics 2) เรียน web security (OWASP) 3) ฝึกใน labs: HackTheBox, TryHackMe, PortSwigger Web Security Academy 4) เรียนรู้เครื่องมือ: Nmap, Burp Suite, Metasploit 5) สอบ cert: eJPT → OSCP ภาษา: Python สำหรับ scripting, Bash สำหรับ automation

Q: Pentest ถูกกฎหมายไหม?

A: ถูกกฎหมาย — ถ้าได้รับอนุญาตเป็นลายลักษณ์อักษรจากเจ้าของระบบ ผิดกฎหมาย — ถ้าทดสอบระบบที่ไม่ได้รับอนุญาต (แม้ไม่มีเจตนาร้าย) ต้องมี: Authorization letter, NDA, Rules of Engagement, Scope definition ในไทย: พ. ร. บ. คอมพิวเตอร์ — เข้าระบบโดยไม่ได้รับอนุญาต = ผิดกฎหมาย ฝึก: ใช้ labs ที่ถูกกฎหมาย (HackTheBox, TryHackMe, DVWA)

📖 บทความที่เกี่ยวข้อง

web application hacking and penetration testingอ่านบทความ → penetration testing nycอ่านบทความ → penetration testing servicesอ่านบทความ → vulnerability and penetration testing policyอ่านบทความ → Dynatrace OneAgent Shift Left Securityอ่านบทความ →

📚 ดูบทความทั้งหมด →