# โปรโตคอลระดับ Application: การถ่ายโอนไฟล์และการเข้าถึงระยะไกล ## Application Layer Protocols - File Transfer & Remote Access **ผู้จัดทำ:** อรรถพล คงหวาน --- # Outline 1. บทนำ (Introduction) 2. โปรโตคอลการถ่ายโอนไฟล์ (File Transfer Protocols) 3. การเข้าถึงระยะไกลอย่างปลอดภัย (Secure Remote Access) 4. เครื่องมือและการปฏิบัติ (Tools and Practice) 5. สรุป (Summary) --- # 1. บทนำ --- ## 1.1 ความสำคัญของโปรโตคอลระดับ Application - **โปรโตคอลระดับ Application** เป็นชั้นบนสุดในโมเดล OSI และ TCP/IP - ทำหน้าที่เป็นส่วนติดต่อระหว่างผู้ใช้กับระบบเครือข่าย - กำหนดวิธีการสื่อสารระหว่างแอปพลิเคชันต่างๆ ผ่านเครือข่าย --- ## ความสำคัญในบริบทความปลอดภัย - เป็นจุดที่ผู้โจมตีมักใช้ในการเจาะระบบ - การกำหนดค่าที่ไม่ปลอดภัยสามารถเปิดช่องโหว่ได้ - ข้อมูลสำคัญมักถูกส่งผ่านโปรโตคอลเหล่านี้ --- ## 1.2 ภาพรวมของโปรโตคอลที่จะศึกษา ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% graph TB subgraph APP["Application Layer Protocols"] direction TB subgraph FT["File Transfer โปรโตคอลถ่ายโอนไฟล์"] FTP["FTP
Port 21/20"] TFTP["TFTP
Port 69"] SFTP["SFTP
Port 22"] FTPS["FTPS
Port 990"] end subgraph RA["Remote Access การเข้าถึงระยะไกล"] SSH["SSH
Port 22"] SCP["SCP
Port 22"] end end ``` --- ## 1.3 ประวัติและพัฒนาการของโปรโตคอล ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% flowchart LR subgraph ERA1["ยุคเริ่มต้น 1970s-1980s"] A1["1971: FTP RFC 114"] A2["1980: FTP Standard RFC 765"] A3["1981: TFTP RFC 783"] end subgraph ERA2["ยุคพัฒนา 1990s"] B1["1995: SSH-1"] B2["1997: FTPS RFC 2228"] B3["1999: SSH-2"] end subgraph ERA3["ยุคปัจจุบัน 2000s"] C1["2006: SSH-2 RFC 4251-4256"] C2["2006: SFTP"] C3["2012: ED25519"] end ERA1 --> ERA2 --> ERA3 ``` --- # 2. โปรโตคอลการถ่ายโอนไฟล์ --- # Outline: โปรโตคอลการถ่ายโอนไฟล์ 2.1 FTP (File Transfer Protocol) 2.2 TFTP (Trivial File Transfer Protocol) 2.3 SFTP (SSH File Transfer Protocol) 2.4 FTPS (FTP over SSL/TLS) --- ## 2.1 FTP (File Transfer Protocol) ### ความหมายและหลักการทำงาน - **FTP** เป็นโปรโตคอลมาตรฐานสำหรับการถ่ายโอนไฟล์ผ่าน TCP/IP - ถูกกำหนดครั้งแรกใน RFC 959 ใช้งานมาตั้งแต่ปี 1971 - ใช้สถาปัตยกรรม Client-Server - รองรับการยืนยันตัวตนด้วย Username และ Password --- ## คุณสมบัติหลักของ FTP - สามารถถ่ายโอนไฟล์แบบ ASCII และ Binary - รองรับการจัดการไฟล์และไดเรกทอรี (list, delete, rename, mkdir) - ใช้ **สองการเชื่อมต่อแยกกัน** (Dual Connection Architecture) --- ## สถาปัตยกรรมและ Port ที่ใช้ | ประเภทการเชื่อมต่อ | Port | หน้าที่ | |:---|:---:|:---| | Control Connection | 21 | ส่งคำสั่งและรับการตอบกลับ | | Data Connection | 20 (Active) หรือ Dynamic (Passive) | ส่งข้อมูลไฟล์จริง | --- ## กระบวนการทำงานของ FTP ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% sequenceDiagram participant C as Client participant S as Server Note over C,S: Control Connection (Port 21) C->>S: เชื่อมต่อ TCP Port 21 S-->>C: 220 Service Ready C->>S: USER username S-->>C: 331 Password Required C->>S: PASS password S-->>C: 230 User Logged In Note over C,S: Data Connection (Active Mode) C->>S: PORT h1,h2,h3,h4,p1,p2 S-->>C: 200 PORT OK C->>S: RETR filename S->>C: เชื่อมต่อจาก Port 20 S-->>C: ส่งข้อมูลไฟล์ S-->>C: 226 Transfer Complete ``` --- ## โหมด Active vs Passive **Active Mode (โหมดแอคทีฟ):** 1. Client เปิด port สุ่มและแจ้ง Server ผ่านคำสั่ง PORT 2. Server เริ่มการเชื่อมต่อจาก port 20 ไปยัง port ที่ Client กำหนด 3. **ปัญหา:** ไม่ทำงานกับ Firewall/NAT ฝั่ง Client --- ## Passive Mode (โหมดพาสซีฟ) 1. Client ส่งคำสั่ง PASV ไปยัง Server 2. Server เปิด port สุ่มและแจ้ง Client 3. Client เริ่มการเชื่อมต่อไปยัง port ที่ Server กำหนด 4. **เหมาะสำหรับ:** Client ที่อยู่หลัง Firewall/NAT --- ## Active vs Passive Mode Diagram ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% flowchart TB subgraph ACTIVE["Active Mode"] direction LR A1["Client Random Port"] -->|"1 PORT command"| A2["Server Port 21"] A3["Server Port 20"] -->|"2 เริ่มเชื่อมต่อ"| A4["Client Port N"] end subgraph PASSIVE["Passive Mode"] direction LR B1["Client"] -->|"1 PASV command"| B2["Server Port 21"] B2 -->|"2 227 IP,Port"| B1 B1 -->|"3 Data Connection"| B3["Server Port N"] end ``` --- ## จุดอ่อนด้านความปลอดภัยของ FTP - **การส่งข้อมูลแบบ Cleartext**: Username, Password และข้อมูลไฟล์ถูกส่งโดยไม่เข้ารหัส - **ไม่มีการตรวจสอบความถูกต้องของข้อมูล (Integrity)** - **FTP Bounce Attack**: ใช้ FTP server เป็นตัวกลางในการโจมตี - **Brute Force Attack**: ไม่มีการจำกัดจำนวนครั้งในการ login ผิดพลาด --- ## ตัวอย่างการดักจับ FTP Credentials ```python """ ตัวอย่างการดักจับ FTP credentials ด้วย Python (สำหรับการศึกษาเท่านั้น) """ from scapy.all import sniff, TCP, Raw def analyze_ftp_packet(packet): if packet.haslayer(TCP) and packet.haslayer(Raw): if packet[TCP].dport == 21 or packet[TCP].sport == 21: payload = packet[Raw].load.decode('utf-8', errors='ignore') if payload.startswith('USER'): print(f"[!] พบ Username: {payload.split()[1]}") elif payload.startswith('PASS'): print(f"[!] พบ Password: {payload.split()[1]}") ``` --- ## 2.2 TFTP (Trivial File Transfer Protocol) ### ความหมายและหลักการทำงาน - **TFTP** เป็นโปรโตคอลถ่ายโอนไฟล์แบบเรียบง่าย (RFC 1350) - ใช้ **UDP port 69** - **ไม่มีการยืนยันตัวตน** (No Authentication) - รองรับเฉพาะการอ่านและเขียนไฟล์ (Read/Write only) - ขนาดบล็อกข้อมูลคงที่ 512 bytes --- ## การใช้งานที่เหมาะสมของ TFTP **กรณีที่ควรใช้ TFTP:** - การ boot อุปกรณ์เครือข่าย (Network Booting - PXE) - การอัปเดต firmware ของ router/switch - การสำรองข้อมูล configuration ของอุปกรณ์เครือข่าย - ระบบที่มีทรัพยากรจำกัด (Embedded Systems) --- ## กระบวนการทำงานของ TFTP ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% sequenceDiagram participant C as Client participant S as Server Port 69 Note over C,S: TFTP Read Request (RRQ) C->>S: RRQ "filename" octet S-->>C: DATA Block 1 (512 bytes) C->>S: ACK Block 1 S-->>C: DATA Block 2 (512 bytes) C->>S: ACK Block 2 S-->>C: DATA Block 3 (<512 bytes = สิ้นสุด) C->>S: ACK Block 3 Note over C,S: ไฟล์ถูกถ่ายโอนสำเร็จ ``` --- ## ความเสี่ยงด้านความปลอดภัยของ TFTP | ความเสี่ยง | คำอธิบาย | ระดับความรุนแรง | |:---|:---|:---:| | ไม่มี Authentication | ใครก็สามารถดาวน์โหลด/อัปโหลดไฟล์ได้ | สูงมาก | | ไม่มี Encryption | ข้อมูลถูกส่งแบบ plaintext | สูง | | Directory Traversal | อาจเข้าถึงไฟล์นอก root directory ได้ | สูง | | UDP Spoofing | ง่ายต่อการปลอมแปลง source IP | ปานกลาง | --- ## แนวทางการป้องกัน TFTP - จำกัดการเข้าถึงด้วย Firewall (เฉพาะ IP ที่อนุญาต) - ใช้ TFTP เฉพาะใน isolated network - กำหนด root directory ที่จำกัด - ตรวจสอบ log การเข้าถึงอย่างสม่ำเสมอ --- ## 2.3 SFTP (SSH File Transfer Protocol) ### ความหมายและหลักการทำงาน - **SFTP** เป็นโปรโตคอลถ่ายโอนไฟล์ที่ปลอดภัย - ทำงานเป็น **subsystem ของ SSH** - **ไม่เกี่ยวข้องกับ FTP** แบบดั้งเดิมแต่อย่างใด - ใช้ SSH port 22 (single connection) --- ## คุณสมบัติหลักของ SFTP - เข้ารหัสทุกข้อมูลรวมถึง credentials - รองรับการจัดการไฟล์แบบครบวงจร - มีการตรวจสอบความถูกต้องของข้อมูล (Integrity Check) - ใช้ SSH Keys สำหรับ Authentication --- ## สถาปัตยกรรม SFTP ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% flowchart TB subgraph CLIENT["SFTP Client"] C1["User Interface"] C2["SFTP Protocol Handler"] C3["SSH Client"] end subgraph SERVER["SFTP Server"] S1["SSH Server"] S2["SFTP Subsystem"] S3["File System"] end C1 --> C2 C2 --> C3 C3 <-->|"SSH Encrypted Port 22"| S1 S1 --> S2 S2 --> S3 ``` --- ## การคำนวณ Throughput ของ SFTP การเข้ารหัสของ SFTP มี overhead ที่ส่งผลต่อประสิทธิภาพ:
T
effective
=
T
raw
1
+
O
enc
+
O
proto
--- ## คำอธิบายตัวแปร Throughput - **T
effective
** = Throughput ที่ใช้งานได้จริง (Mbps) - **T
raw
** = Bandwidth ดิบของเครือข่าย (Mbps) - **O
enc
** = Overhead จากการเข้ารหัส (ประมาณ 0.05-0.15) - **O
proto
** = Overhead จากโปรโตคอล (ประมาณ 0.02-0.05) --- ## โปรแกรมคำนวณ SFTP Throughput ```python def calculate_sftp_throughput(raw_bandwidth_mbps: float, encryption_overhead: float = 0.10, protocol_overhead: float = 0.03) -> dict: total_overhead = 1 + encryption_overhead + protocol_overhead effective_throughput = raw_bandwidth_mbps / total_overhead file_size_mb = 1024 * 8 # 1 GB = 8192 Mb transfer_time_seconds = file_size_mb / effective_throughput return { 'effective_throughput_mbps': round(effective_throughput, 2), 'efficiency': f"{(effective_throughput/raw_bandwidth_mbps) * 100:.1f}%", 'time_for_1gb_minutes': round(transfer_time_seconds / 60, 2) } ``` --- ## ตัวอย่างผลการคำนวณ SFTP Throughput | Bandwidth ดิบ | Throughput จริง | ประสิทธิภาพ | เวลาถ่ายโอน 1 GB | |:---:|:---:|:---:|:---:| | 100 Mbps | 88.5 Mbps | 88.5% | 1.54 นาที | | 1000 Mbps | 884.96 Mbps | 88.5% | 0.15 นาที | | 10000 Mbps | 8849.56 Mbps | 88.5% | 0.02 นาที | --- ## 2.4 FTPS (FTP over SSL/TLS) ### ความหมายและหลักการทำงาน - **FTPS** คือ FTP ที่เพิ่มชั้นความปลอดภัยด้วย SSL/TLS - ถูกกำหนดใน RFC 4217 - ยังคงใช้โครงสร้าง **dual-connection** เหมือน FTP - เพิ่มการเข้ารหัสข้อมูล --- ## รูปแบบของ FTPS | รูปแบบ | คำอธิบาย | Port | |:---|:---|:---:| | **Implicit FTPS** | เข้ารหัสทันทีที่เชื่อมต่อ | 990 (Control), 989 (Data) | | **Explicit FTPS** | เริ่มด้วย FTP ธรรมดา แล้วอัปเกรดด้วย AUTH TLS | 21 | --- ## กระบวนการ FTPS Handshake ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% sequenceDiagram participant C as Client participant S as Server Note over C,S: Explicit FTPS Handshake C->>S: เชื่อมต่อ TCP Port 21 S-->>C: 220 FTP Server Ready C->>S: AUTH TLS S-->>C: 234 Using TLS Note over C,S: TLS Handshake C->>S: ClientHello S-->>C: ServerHello + Certificate C->>S: Key Exchange S-->>C: Finished Note over C,S: Encrypted Session C->>S: USER username (encrypted) S-->>C: 230 Login Successful ``` --- ## เปรียบเทียบ FTPS กับ SFTP | คุณสมบัติ | FTPS | SFTP | |:---|:---|:---| | **พื้นฐาน** | FTP + SSL/TLS | SSH Subsystem | | **Port** | 21, 990 + Data Port | 22 เท่านั้น | | **การเชื่อมต่อ** | Multiple | Single | | **Firewall** | ซับซ้อน (หลาย port) | ง่าย (port เดียว) | | **Certificate** | ต้องใช้ X.509 | ใช้ SSH Keys | | **มาตรฐาน** | RFC 4217 | IETF Draft | --- ## ตัวอย่างการเชื่อมต่อ FTPS ```python from ftplib import FTP_TLS import ssl def connect_ftps_explicit(host: str, username: str, password: str): ftps = FTP_TLS() context = ssl.create_default_context() context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED ftps.connect(host, 21) ftps.auth() # อัปเกรดเป็น TLS ftps.login(username, password) ftps.prot_p() # เปิด Protected data connection return ftps ``` --- # 3. การเข้าถึงระยะไกลอย่างปลอดภัย --- # Outline: การเข้าถึงระยะไกล 3.1 SSH (Secure Shell) 3.2 SCP (Secure Copy) 3.3 SSHFS (SSH Filesystem) --- ## 3.1 SSH (Secure Shell) ### ความหมายและหลักการทำงาน - **SSH** เป็นโปรโตคอลเครือข่ายสำหรับการสื่อสารที่ปลอดภัย - พัฒนาโดย **Tatu Ylönen** ในปี 1995 - ทดแทน Telnet, rlogin และ rsh ที่ไม่ปลอดภัย --- ## คุณสมบัติหลักของ SSH - การเข้ารหัสข้อมูลทั้งหมดที่ส่งผ่านเครือข่าย - การยืนยันตัวตนที่แข็งแกร่ง (Password, Public Key, Certificate) - การตรวจสอบความถูกต้องของข้อมูล (Integrity) - การป้องกัน Man-in-the-Middle Attack - รองรับ Port Forwarding และ Tunneling --- ## สถาปัตยกรรม SSH - 3 ส่วนหลัก ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% flowchart TB subgraph SSH["SSH Protocol Stack"] direction TB subgraph CONN["SSH Connection Layer"] C1["Session Channel"] C2["X11 Forwarding"] C3["Port Forwarding"] C4["SFTP Subsystem"] end subgraph AUTH["SSH User Authentication"] A1["Password"] A2["Public Key"] A3["Keyboard-Interactive"] end subgraph TRANS["SSH Transport Layer"] T1["Key Exchange"] T2["Server Authentication"] T3["Encryption"] T4["Integrity"] end TCP["TCP Port 22"] end CONN --> AUTH --> TRANS --> TCP ``` --- ## กระบวนการยืนยันตัวตนด้วย Public Key ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% sequenceDiagram participant C as Client participant S as Server Note over C,S: Transport Layer Setup C->>S: TCP Connection (Port 22) C->>S: SSH_MSG_KEXINIT S-->>C: SSH_MSG_KEXINIT Note over C,S: Key Exchange (ECDH) C->>S: SSH_MSG_KEX_ECDH_INIT S-->>C: SSH_MSG_KEX_ECDH_REPLY C->>S: SSH_MSG_NEWKEYS S-->>C: SSH_MSG_NEWKEYS Note over C,S: User Authentication C->>S: SSH_MSG_USERAUTH_REQUEST (publickey) S-->>C: SSH_MSG_USERAUTH_PK_OK C->>S: Signature with private key S-->>C: SSH_MSG_USERAUTH_SUCCESS ``` --- ## อัลกอริทึมการเข้ารหัสที่รองรับ | ประเภท | แนะนำ | ควรหลีกเลี่ยง | |:---|:---|:---| | **Key Exchange** | curve25519-sha256, ecdh-sha2-nistp256 | diffie-hellman-group1-sha1 | | **Host Key** | ssh-ed25519, rsa-sha2-512 | ssh-dss, ssh-rsa (SHA-1) | | **Cipher** | chacha20-poly1305, aes256-gcm | 3des-cbc, arcfour | | **MAC** | hmac-sha2-512-etm, umac-128-etm | hmac-md5, hmac-sha1 | --- ## การจัดการ SSH Keys - สร้าง Key ```python class SSHKeyManager: def generate_key(self, key_type: str = "ed25519", key_name: str = "id_ed25519", comment: str = ""): cmd = [ "ssh-keygen", "-t", key_type, "-f", str(self.ssh_dir / key_name), "-N", "", # passphrase ] if comment: cmd.extend(["-C", comment]) if key_type == "rsa": cmd.extend(["-b", "4096"]) # RSA 4096 bits subprocess.run(cmd, capture_output=True) ``` --- ## การจัดการ SSH Keys - Fingerprint ```python def get_key_fingerprint(self, key_path: Path) -> str: """ดึง fingerprint ของ SSH key""" cmd = ["ssh-keygen", "-l", "-f", str(key_path)] result = subprocess.run(cmd, capture_output=True, text=True) return result.stdout.strip() def add_to_authorized_keys(self, public_key_path: Path): """เพิ่ม public key ไปยัง authorized_keys""" auth_keys_path = self.ssh_dir / "authorized_keys" with open(public_key_path, 'r') as pub_key: key_content = pub_key.read().strip() with open(auth_keys_path, 'a') as auth_keys: auth_keys.write(f"{key_content}\n") auth_keys_path.chmod(0o600) ``` --- ## การตั้งค่า SSH Server ที่ปลอดภัย - พื้นฐาน ```bash # /etc/ssh/sshd_config - การตั้งค่าพื้นฐาน Port 22 Protocol 2 PermitRootLogin no PubkeyAuthentication yes PasswordAuthentication no PermitEmptyPasswords no MaxAuthTries 3 MaxSessions 10 LoginGraceTime 60 ``` --- ## การตั้งค่า SSH Server - อัลกอริทึม ```bash # /etc/ssh/sshd_config - อัลกอริทึมที่แนะนำ KexAlgorithms curve25519-sha256,ecdh-sha2-nistp256, diffie-hellman-group-exchange-sha256 HostKeyAlgorithms ssh-ed25519,rsa-sha2-512,rsa-sha2-256 Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com, aes128-gcm@openssh.com MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com ``` --- ## การตั้งค่า SSH Server - ความปลอดภัยเพิ่มเติม ```bash # /etc/ssh/sshd_config - ความปลอดภัย X11Forwarding no AllowTcpForwarding no AllowAgentForwarding no PermitTunnel no StrictModes yes SyslogFacility AUTH LogLevel VERBOSE ClientAliveInterval 300 ClientAliveCountMax 2 # จำกัดผู้ใช้ AllowUsers admin developer ``` --- ## 3.2 SCP (Secure Copy) ### ความหมายและหลักการทำงาน - **SCP** เป็นโปรโตคอลสำหรับคัดลอกไฟล์ผ่าน SSH - ใช้ SSH เป็น transport layer - เข้ารหัสข้อมูลทั้งหมดระหว่างการถ่ายโอน - รองรับการคัดลอกไฟล์และไดเรกทอรี - ไวยากรณ์คล้าย `cp` command --- ## รูปแบบการใช้งาน SCP ```bash # รูปแบบพื้นฐาน scp [options] source destination # คัดลอกไฟล์จากเครื่องไปยัง remote scp local_file.txt user@remote:/path/to/destination/ # คัดลอกไฟล์จาก remote มายังเครื่อง scp user@remote:/path/to/file.txt ./local_directory/ # คัดลอกไดเรกทอรีทั้งหมด (recursive) scp -r local_directory/ user@remote:/path/to/destination/ # ใช้ port อื่น scp -P 2222 file.txt user@remote:/path/ ``` --- ## เปรียบเทียบ SCP กับ SFTP | คุณสมบัติ | SCP | SFTP | |:---|:---|:---| | **การใช้งาน** | Non-interactive, command-line | Interactive หรือ automated | | **การทำงาน** | คัดลอกไฟล์เท่านั้น | จัดการไฟล์ครบวงจร | | **Resume transfer** | ไม่รองรับ | รองรับ | | **Protocol** | RCP over SSH | SSH Subsystem | | **ความเร็ว** | เร็วกว่าเล็กน้อย | ช้ากว่าเล็กน้อย | --- ## โปรแกรมถ่ายโอนไฟล์ด้วย SCP/SFTP ```python import paramiko from scp import SCPClient class SecureFileTransfer: def __init__(self, hostname, username, private_key_path): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) key = paramiko.Ed25519Key.from_private_key_file(private_key_path) self.ssh.connect(hostname=hostname, username=username, pkey=key) def scp_upload(self, local_path, remote_path): with SCPClient(self.ssh.get_transport()) as scp: scp.put(local_path, remote_path) ``` --- ## SCP/SFTP - ดาวน์โหลดและจัดการไฟล์ ```python def sftp_download(self, remote_path, local_path): """ดาวน์โหลดไฟล์ด้วย SFTP""" sftp = self.ssh.open_sftp() try: sftp.get(remote_path, local_path) finally: sftp.close() def sftp_list_directory(self, remote_path='.'): """แสดงรายการไฟล์ใน remote directory""" sftp = self.ssh.open_sftp() items = [] for entry in sftp.listdir_attr(remote_path): items.append({ 'name': entry.filename, 'size': entry.st_size, 'is_dir': entry.st_mode & 0o40000 != 0 }) return items ``` --- ## 3.3 SSHFS (SSH Filesystem) ### ความหมายและหลักการทำงาน - **SSHFS** เป็นระบบไฟล์แบบ client-based - mount ไดเรกทอรีจาก remote server มาใช้งานบนเครื่อง local - ใช้ SSH เป็น transport layer - ทำงานบน **FUSE** (Filesystem in Userspace) - ไม่ต้องใช้สิทธิ์ root ในการ mount --- ## คุณสมบัติหลักของ SSHFS - ใช้ SFTP subsystem ของ SSH ในการถ่ายโอนข้อมูล - เข้ารหัสข้อมูลทั้งหมดผ่าน SSH tunnel - ใช้งานง่าย ไม่ต้องตั้งค่า server เพิ่มเติม - รองรับการเข้าถึงไฟล์แบบ random access --- ## สถาปัตยกรรม SSHFS ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% flowchart TB subgraph CLIENT["Local Machine"] APP["Application"] VFS["VFS"] FUSE["FUSE Module"] SSHFS["SSHFS Client"] SSHC["SSH Client"] end subgraph SERVER["Remote Server"] SSHS["SSH Server"] SFTP["SFTP Subsystem"] FS["File System"] end APP -->|"read/write"| VFS VFS -->|"FUSE calls"| FUSE FUSE -->|"SFTP requests"| SSHFS SSHFS --> SSHC SSHC <-->|"SSH Encrypted Port 22"| SSHS SSHS --> SFTP SFTP --> FS ``` --- ## การติดตั้ง SSHFS ```bash # Ubuntu/Debian sudo apt update sudo apt install sshfs # Fedora/RHEL/CentOS sudo dnf install fuse-sshfs # Arch Linux sudo pacman -S sshfs # macOS (ต้องติดตั้ง macFUSE ก่อน) brew install macfuse brew install sshfs # ตรวจสอบการติดตั้ง sshfs --version ``` --- ## คำสั่งพื้นฐาน SSHFS ```bash # รูปแบบพื้นฐาน sshfs [user@]host:[remote_path] mountpoint [options] # Mount home directory ของ remote user sshfs user@192.168.1.100: ~/mnt/remote # Mount directory ที่ระบุ sshfs user@server:/var/www ~/mnt/webserver # Mount ด้วย port ที่กำหนด sshfs -p 2222 user@server:/data ~/mnt/data # Unmount fusermount -u ~/mnt/remote ``` --- ## SSHFS Options ที่สำคัญ ```bash # Options สำหรับการใช้งานจริง sshfs user@server:/data ~/mnt/data \ -o IdentityFile=~/.ssh/id_ed25519 \ -o reconnect \ -o ServerAliveInterval=15 \ -o ServerAliveCountMax=3 \ -o cache=yes \ -o kernel_cache \ -o auto_cache \ -o uid=$(id -u) \ -o gid=$(id -g) ``` --- ## SSHFS - การตั้งค่า Auto-Mount ```bash # เพิ่มใน /etc/fstab # user@server:/remote/path /local/mountpoint fuse.sshfs options 0 0 # ตัวอย่าง: admin@192.168.1.100:/var/www /mnt/webserver fuse.sshfs \ IdentityFile=/home/user/.ssh/id_ed25519,\ allow_other,\ reconnect,\ ServerAliveInterval=15,\ _netdev,\ users,\ idmap=user 0 0 # Mount ทุก entry ใน fstab sudo mount -a ``` --- ## ปัจจัยที่ส่งผลต่อประสิทธิภาพ SSHFS | ปัจจัย | ผลกระทบ | แนวทางแก้ไข | |:---|:---|:---| | Latency | ช้าลงมากสำหรับ small files | ใช้ caching, batch operations | | Encryption overhead | CPU usage สูงขึ้น | เลือก cipher ที่เร็ว | | No local caching | อ่านซ้ำไฟล์เดิมช้า | เปิด cache options | | Small read-ahead | Sequential read ช้า | เพิ่ม read-ahead buffer | --- ## การคำนวณ Performance ของ SSHFS
T
transfer
=
S
B
effective
+
N
×
RTT
- **T
transfer
** = เวลาในการถ่ายโอนทั้งหมด (วินาที) - **S** = ขนาดไฟล์ (bytes) - **B
effective
** = Bandwidth ที่ใช้งานได้จริง (bytes/sec) - **N** = จำนวน round-trips ที่ต้องการ - **RTT** = Round-Trip Time (วินาที) --- ## โปรแกรมคำนวณ SSHFS Performance ```python def calculate_transfer_time(file_size_mb, bandwidth_mbps, latency_ms, overhead_percent=15): file_size_bytes = file_size_mb * 1024 * 1024 bandwidth_bps = (bandwidth_mbps * 1_000_000) / 8 rtt_seconds = (latency_ms * 2) / 1000 effective_bandwidth = bandwidth_bps * (1 - overhead_percent/100) transfer_time = file_size_bytes / effective_bandwidth # ประมาณ latency overhead (1 RTT ต่อ 10 blocks) block_size = 64 * 1024 num_blocks = file_size_bytes / block_size latency_time = (num_blocks / 10) * rtt_seconds total_time = transfer_time + latency_time return {'total_time_sec': round(total_time, 2)} ``` --- ## ผลการคำนวณ SSHFS Performance (100 MB) | สถานการณ์ | Bandwidth | Latency | เวลาถ่ายโอน | ประสิทธิภาพ | |:---|:---:|:---:|:---:|:---:| | LAN (Gigabit) | 1000 Mbps | 0.5 ms | ~1 วินาที | ~85% | | WAN (100Mbps) | 100 Mbps | 20 ms | ~10 วินาที | ~80% | | VPN (50Mbps) | 50 Mbps | 50 ms | ~20 วินาที | ~75% | | International | 25 Mbps | 150 ms | ~45 วินาที | ~65% | --- ## การแก้ไขปัญหา SSHFS ที่พบบ่อย | ปัญหา | สาเหตุ | วิธีแก้ไข | |:---|:---|:---| | "Transport endpoint not connected" | การเชื่อมต่อขาด | `fusermount -uz` แล้ว mount ใหม่ | | "Permission denied" | SSH key ไม่ถูกต้อง | ตรวจสอบ key และ authorized_keys | | "Host key verification failed" | Host key เปลี่ยน | ลบ entry ใน known_hosts | | Mount ช้ามาก | Latency สูง | เพิ่ม cache options | | "fuse: device not found" | FUSE module ไม่ถูก load | `sudo modprobe fuse` | --- ## เปรียบเทียบ SSHFS กับทางเลือกอื่น | คุณสมบัติ | SSHFS | NFS | SMB/CIFS | SyncThing | |:---|:---|:---|:---|:---| | **การเข้ารหัส** | ✅ | ❌ | ✅ (SMB3) | ✅ | | **ติดตั้งง่าย** | ✅ | ปานกลาง | ปานกลาง | ✅ | | **ไม่ต้อง root** | ✅ | ❌ | ❌ | ✅ | | **ทำงานผ่าน Internet** | ✅ | ❌ | ⚠️ | ✅ | | **ประสิทธิภาพ** | ปานกลาง | สูงมาก | สูง | - | | **Real-time** | ✅ | ✅ | ✅ | ❌ | --- # 4. เครื่องมือและการปฏิบัติ --- ## 4.1 คำสั่ง SSH พื้นฐาน - การเชื่อมต่อ ```bash # เชื่อมต่อ SSH ปกติ ssh user@hostname # ระบุ port ssh -p 2222 user@hostname # ใช้ private key ที่ระบุ ssh -i ~/.ssh/id_ed25519 user@hostname # เปิด verbose mode เพื่อ debug ssh -v user@hostname # -v, -vv, -vvv # รันคำสั่งบน remote ssh user@hostname "ls -la /var/log" ``` --- ## คำสั่ง SSH - การจัดการ Keys ```bash # สร้าง ED25519 key (แนะนำ) ssh-keygen -t ed25519 -C "comment" # สร้าง RSA 4096-bit key ssh-keygen -t rsa -b 4096 -C "comment" # ดู fingerprint ของ key ssh-keygen -l -f ~/.ssh/id_ed25519.pub # คัดลอก public key ไป remote server ssh-copy-id user@hostname ``` --- ## คำสั่ง SSH - Agent ```bash # เริ่ม ssh-agent eval $(ssh-agent -s) # เพิ่ม key เข้า agent ssh-add ~/.ssh/id_ed25519 # แสดง keys ใน agent ssh-add -l # ลบ keys ออกจาก agent ssh-add -D ``` --- ## คำสั่ง SSH - Port Forwarding ```bash # Local port forwarding # เข้าถึง remote:3306 ผ่าน localhost:13306 ssh -L 13306:localhost:3306 user@hostname # Remote port forwarding # เปิด port 8080 บน remote ให้เข้าถึง localhost:80 ssh -R 8080:localhost:80 user@hostname # Dynamic port forwarding (SOCKS proxy) ssh -D 1080 user@hostname # ProxyJump (เข้าผ่าน bastion host) ssh -J jump@bastion user@internal ``` --- ## คำสั่ง SCP พื้นฐาน ```bash # อัปโหลดไฟล์ scp local.txt user@host:/path/ # ดาวน์โหลดไฟล์ scp user@host:/path/remote.txt ./ # คัดลอก directory (recursive) scp -r local_dir/ user@host:/path/ # ใช้ compression scp -C large_file.tar user@host:/path/ # จำกัด bandwidth (KB/s) scp -l 1024 file.txt user@host:/path/ ``` --- ## คำสั่ง SFTP พื้นฐาน ```bash # เชื่อมต่อ SFTP sftp user@hostname # คำสั่งใน SFTP session sftp> pwd # แสดง remote directory sftp> lpwd # แสดง local directory sftp> ls # list remote sftp> lls # list local sftp> cd /path # change remote dir sftp> lcd /path # change local dir sftp> get file.txt # download sftp> put file.txt # upload sftp> mkdir dir # create directory sftp> bye # disconnect ``` --- ## 4.2 การป้องกัน Brute Force ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% flowchart TB subgraph DEFENSE["การป้องกัน Brute Force"] D1["Fail2ban - บล็อก IP"] D2["Rate Limiting - MaxAuthTries=3"] D3["Key-only Auth - ปิด Password"] D4["Port Knocking - ซ่อน Port"] D5["2FA/MFA"] end A["Attacker"] -->|"Brute Force"| B["SSH Server"] B --> DEFENSE ``` --- ## Checklist ความปลอดภัย - SSH Server **สำหรับ SSH Server:** - ✅ ใช้เฉพาะ SSH Protocol 2 - ✅ ปิด root login - ✅ ใช้ public key authentication เท่านั้น - ✅ กำหนด AllowUsers หรือ AllowGroups - ✅ จำกัด MaxAuthTries - ✅ ใช้ strong encryption algorithms เท่านั้น - ✅ ตั้งค่า idle timeout - ✅ ติดตั้ง Fail2ban --- ## Checklist ความปลอดภัย - SSH Client **สำหรับ SSH Client:** - ✅ ใช้ ED25519 หรือ RSA 4096-bit keys - ✅ ปกป้อง private key ด้วย passphrase - ✅ ตรวจสอบ host key fingerprint - ✅ ใช้ ssh-agent แทนการเก็บ key ไว้เปิด - ✅ หลีกเลี่ยง StrictHostKeyChecking=no ใน production --- ## Checklist ความปลอดภัย - File Transfer **สำหรับ File Transfer:** - ✅ ใช้ SFTP หรือ SCP แทน FTP - ✅ หลีกเลี่ยง TFTP นอกจาก isolated network - ✅ ตรวจสอบ integrity ของไฟล์หลังการถ่ายโอน - ✅ ใช้ encryption สำหรับข้อมูลสำคัญ --- # 5. สรุป --- ## 5.1 สรุปเนื้อหาหลัก - File Transfer **โปรโตคอลการถ่ายโอนไฟล์:** - **FTP**: โปรโตคอลดั้งเดิมที่ไม่ปลอดภัย ส่งข้อมูลแบบ cleartext - **TFTP**: โปรโตคอลแบบเรียบง่ายสำหรับ network booting ไม่มี authentication - **SFTP**: โปรโตคอลถ่ายโอนไฟล์ที่ปลอดภัยบน SSH - **FTPS**: FTP ที่เพิ่ม SSL/TLS มีความซับซ้อนในการตั้งค่า --- ## 5.1 สรุปเนื้อหาหลัก - Remote Access **การเข้าถึงระยะไกล:** - **SSH**: โปรโตคอลมาตรฐานสำหรับการเข้าถึงระยะไกลที่ปลอดภัย - **SCP**: การคัดลอกไฟล์ผ่าน SSH เหมาะสำหรับ non-interactive - **SSHFS**: การ mount remote filesystem ผ่าน SSH --- ## 5.2 ตารางเปรียบเทียบโปรโตคอล | โปรโตคอล | Port | เข้ารหัส | Authentication | การใช้งานที่แนะนำ | |:---|:---:|:---:|:---|:---| | FTP | 21/20 | ❌ | Username/Password | ไม่แนะนำ | | TFTP | 69 | ❌ | ไม่มี | Network boot เท่านั้น | | SFTP | 22 | ✅ | SSH Keys/Password | ถ่ายโอนไฟล์ทั่วไป | | FTPS | 990/21 | ✅ | Certificate/Password | Legacy systems | | SSH | 22 | ✅ | Keys/Password/MFA | Remote access | | SCP | 22 | ✅ | SSH Keys/Password | Quick file copy | | SSHFS | 22 | ✅ | SSH Keys/Password | Mount remote FS | --- ## 5.3 แนวทางการเลือกใช้ ```mermaid %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#3c3836', 'primaryTextColor': '#ebdbb2', 'primaryBorderColor': '#ebdbb2', 'lineColor': '#ebdbb2', 'secondaryColor': '#504945', 'tertiaryColor': '#282828'}}}%% flowchart TB START["ต้องการถ่ายโอนไฟล์/เข้าถึงระยะไกล"] --> Q1{"ต้องการความปลอดภัย?"} Q1 -->|"ใช่"| Q2{"ลักษณะการใช้งาน?"} Q1 -->|"ไม่"| Q3{"Network Boot?"} Q2 -->|"จัดการไฟล์ Interactive"| SFTP["ใช้ SFTP"] Q2 -->|"คัดลอกไฟล์ครั้งเดียว"| SCP["ใช้ SCP"] Q2 -->|"เข้าถึงไฟล์ต่อเนื่อง"| SSHFS["ใช้ SSHFS"] Q2 -->|"Remote shell"| SSH["ใช้ SSH"] Q3 -->|"ใช่"| TFTP["ใช้ TFTP (จำกัดเครือข่าย)"] Q3 -->|"ไม่"| SFTP ``` --- ## เอกสารอ้างอิง - RFC และมาตรฐาน - **RFC 959** - File Transfer Protocol (FTP) - **RFC 1350** - The TFTP Protocol (Revision 2) - **RFC 4217** - Securing FTP with TLS - **RFC 4251-4254** - The Secure Shell (SSH) Protocol - **draft-ietf-secsh-filexfer** - SSH File Transfer Protocol --- ## เอกสารอ้างอิง - เอกสารและเครื่องมือ **เอกสารและคู่มือ:** - OpenSSH Manual Pages: https://www.openssh.com/manual.html - Mozilla SSH Guidelines: https://infosec.mozilla.org/guidelines/openssh **เครื่องมือและซอฟต์แวร์:** - OpenSSH: https://www.openssh.com/ - Paramiko (Python): https://www.paramiko.org/ - Fail2ban: https://www.fail2ban.org/ --- # คำถาม - ข้อสงสัย