Lesson 9

Shell Commands from Tool Input

เขียน print_receipt ที่ต่อคำสั่ง shell จากชื่อลูกค้ากับชื่อไฟล์ ใส่ชื่อลูกค้าที่มีคำสั่ง touch แทรกอยู่แล้วดู shell รันตาม จากนั้นเปลี่ยนเป็น subprocess แบบ list กับ allowlist ของชื่อไฟล์ พร้อม pytest ที่ Fail เมื่อถอดการป้องกันออก

ชื่อลูกค้าในบท Untrusted Text in Resources ไปถึง AI ครบทุกตัวอักษร บทนี้ชื่อเดียวกันไปถึง shell ครับ เราจะเพิ่ม tool print_receipt ที่บันทึกใบเสร็จด้วยคำสั่ง shell แล้วดูว่าชื่อลูกค้าที่มีคำสั่งแทรกอยู่ทำอะไรได้บ้าง

คำสั่งที่แทรกเข้าไปคือ touch pwned.txt ซึ่งแค่สร้างไฟล์ว่างในโฟลเดอร์โปรเจกต์ try_injection.py ที่จะเขียนเรียก server ใน process เดียวกัน ไม่ต้องใช้ tokens.env หรือ HTTP server

What Is Command Injection

ถ้าเราเอา input ไปต่อเป็นคำสั่ง shell ตัว shell จะอ่าน input นั้นเป็นส่วนหนึ่งของคำสั่ง ตัวอักษรอย่าง ;, |, &&, $() หรือเครื่องหมายคำพูดที่ปิดก่อนเวลา เปลี่ยนข้อมูลให้กลายเป็นคำสั่งที่สอง OWASP นับเป็น MCP05 Command Injection & Execution

ที่ MCP ต่างจากเว็บคือคนที่ส่งค่าให้ tool เป็น AI ไม่ใช่ผู้โจมตีโดยตรง AI เลือก argument จากข้อความที่อ่านมา ไม่ว่าจะเป็นคำสั่งของผู้ใช้ ชื่อลูกค้าในออร์เดอร์ หรือไฟล์ที่เปิดอ่าน

InputComes FromGoes To
ชื่อลูกค้าลูกค้าพิมพ์ แล้ว AI ส่งผ่าน create_order ที่รับข้อความไม่ว่างทุกแบบDatabase แล้วต่อเข้าคำสั่ง shell
ชื่อไฟล์AI เลือกเองตอนเรียก toolต่อท้าย path ในคำสั่ง shell

server เลยต้องถือค่าจาก AI เหมือนค่าจากฟอร์มบนเว็บ

Write the Code

  • receipt_vulnerable.py server แยกที่มี print_receipt แบบมีช่องโหว่
  • try_injection.py ส่งสามคำขอเข้า server ที่เลือก

cafe_server.py ไม่ต้องแก้ ส่วน tee (คำสั่งที่เขียนข้อความจาก stdin ลงไฟล์) ในบทนี้เป็นตัวแทนของโปรแกรมภายนอก เช่น CLI ของเครื่องพิมพ์ใบเสร็จ (ถ้า Python เขียนไฟล์เองได้ก็ไม่ต้องเรียกโปรแกรมเลย)

1. receipt_vulnerable.py

receipt_vulnerable.py
# DEMO VULNERABLE SERVER: builds a shell command from order data. Do not copy this pattern.
import subprocess
from pathlib import Path

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

from cafe_server import load_order

RECEIPTS_DIR = Path(__file__).parent / "receipts"

mcp = MCPServer("receipts-vulnerable")


@mcp.tool()
def print_receipt(order_id: int, filename: str) -> str:
    """Print the receipt of an order to a text file in the receipts folder."""
    order = load_order(order_id)
    if order is None:
        raise ToolError(f"Order {order_id} not found.")
    RECEIPTS_DIR.mkdir(exist_ok=True)
    command = f'echo "Receipt #{order["id"]} for {order["customer"]}: {order["total_thb"]} THB" | tee receipts/{filename}'
    subprocess.run(command, shell=True, cwd=RECEIPTS_DIR.parent, capture_output=True, check=True)
    return f"Receipt saved to receipts/{filename}"


if __name__ == "__main__":
    mcp.run()
  • command วางชื่อลูกค้าไว้ในเครื่องหมายคำพูดคู่ และวาง filename ต่อท้าย receipts/ ตรง ๆ
  • shell=True ส่งทั้ง string ให้ /bin/sh อ่าน ตัวอักษรพิเศษทุกตัวเลยมีความหมายกับ shell
  • cwd=RECEIPTS_DIR.parent ให้คำสั่งรันในโฟลเดอร์โปรเจกต์ ไม่ว่าจะเรียก script จากที่ไหน
  • load_order อ่านชื่อลูกค้าจาก cafe.db ตัวเดียวกับที่ resource ใช้

2. try_injection.py

try_injection.py
# DEMO: three requests against the receipts server given as the first argument (vulnerable or fixed).
import asyncio
import importlib
import sys

from mcp import Client

from cafe_server import mcp as cafe

SERVERS = {"vulnerable": "receipt_vulnerable", "fixed": "receipt_fixed"}
LATTE = [{"menu": "latte", "size": "M", "quantity": 1}]
REQUESTS = [
    ("normal name", "Somchai", "receipt-{id}.txt"),
    ("injected name", 'Malee"; touch pwned.txt; echo "', "receipt-{id}.txt"),
    ("traversal filename", "Preecha", "../escaped.txt"),
]


async def main(which: str) -> None:
    receipts_server = importlib.import_module(SERVERS[which]).mcp
    async with Client(cafe) as orders, Client(receipts_server) as receipts:
        for label, customer, filename in REQUESTS:
            created = await orders.call_tool("create_order", {"items": LATTE, "customer_name": customer})
            order_id = created.structured_content["id"]
            result = await receipts.call_tool("print_receipt", {"order_id": order_id, "filename": filename.format(id=order_id)})
            print(f"{label}: order {order_id}, is_error={result.is_error}, {result.content[0].text}")


asyncio.run(main(sys.argv[1]))
  • importlib.import_module โหลดเฉพาะ server ที่เลือก ตอนนี้ยังไม่มี receipt_fixed.py script ก็รันโหมด vulnerable ได้
  • ทุกคำขอสร้างออร์เดอร์ด้วย create_order ก่อน ชื่อลูกค้าเลยผ่าน Database แล้วค่อยถึง shell
  • ชื่อที่สอง Malee"; touch pwned.txt; echo " ปิดเครื่องหมายคำพูดของ echo ต่อคำสั่ง touch แล้วเปิดเครื่องหมายคำพูดใหม่ให้ : 60 THB" ที่ตามมาปิด
  • ชื่อไฟล์ที่สาม ../escaped.txt ไม่มีตัวอักษรพิเศษของ shell เลย แต่พา path ออกนอก receipts
  • script ทำหน้าที่แทน AI ส่วนในการใช้งานจริง AI เป็นคนเลือกชื่อไฟล์ และส่งเลขออร์เดอร์ที่มีชื่อแบบนี้มาเอง

Run the Attack

bash
ls pwned.txt escaped.txt
ผลลัพธ์จาก ls pwned.txt escaped.txt
ls: escaped.txt: No such file or directory
ls: pwned.txt: No such file or directory

ยังไม่มีทั้งสองไฟล์ ส่งสามคำขอเข้า server ที่มีช่องโหว่

bash
uv run python try_injection.py vulnerable
ผลลัพธ์จาก uv run python try_injection.py vulnerable
normal name: order 3, is_error=False, Receipt saved to receipts/receipt-3.txt
injected name: order 4, is_error=False, Receipt saved to receipts/receipt-4.txt
traversal filename: order 5, is_error=False, Receipt saved to receipts/../escaped.txt

ทั้งสามคำขอได้ is_error=False (เลขออร์เดอร์ขึ้นกับ cafe.db ของแต่ละเครื่อง) แต่ไฟล์ที่เกิดขึ้นบอกอีกเรื่อง

bash
ls pwned.txt escaped.txt
ผลลัพธ์จาก ls pwned.txt escaped.txt
escaped.txt
pwned.txt
bash
head receipts/* escaped.txt
ผลลัพธ์จาก head receipts/* escaped.txt
==> receipts/receipt-3.txt <==
Receipt #3 for Somchai: 60 THB

==> receipts/receipt-4.txt <==
: 60 THB

==> escaped.txt <==
Receipt #5 for Preecha: 60 THB

Injected Name

หลังแทนชื่อลูกค้า คำสั่งที่ shell ได้รับคือ

echo "Receipt #4 for Malee"; touch pwned.txt; echo ": 60 THB" | tee receipts/receipt-4.txt

; แบ่งเป็นสามคำสั่ง touch pwned.txt สร้างไฟล์ และ tee ได้แค่ : 60 THB ไปเขียนลงใบเสร็จ tool ยังตอบสำเร็จเพราะคำสั่งสุดท้ายจบด้วย exit code 0 ร่องรอยเดียวคือใบเสร็จที่เสีย

คำสั่งไหนที่เรารันได้ ชื่อลูกค้าก็รันได้ เพราะ stdio server ทำงานด้วยสิทธิ์ของเรา

Traversal Filename

escaped.txt ไปอยู่ในโฟลเดอร์โปรเจกต์แทน receipts เพราะ receipts/../escaped.txt ขึ้นไปหนึ่งชั้น ช่องนี้ไม่ใช่ shell injection (ไม่มีตัวอักษรพิเศษของ shell เลย) เป็น path traversal ที่ OWASP ใส่ไว้ใน MCP05 เหมือนกัน ใส่ .. มากขึ้นก็ขึ้นไปได้ไกลเท่าที่สิทธิ์ของ process อนุญาต

Fix It

  • receipt_fixed.py ไม่ผ่าน shell และตรวจชื่อไฟล์ก่อนทำอะไร
  • tests/test_receipt_fixed.py 11 ตัว

1. receipt_fixed.py

receipt_fixed.py
import re
import subprocess
from pathlib import Path

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

from cafe_server import load_order

RECEIPTS_DIR = Path(__file__).parent / "receipts"
FILENAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,39}\.txt")

mcp = MCPServer("receipts")


@mcp.tool()
def print_receipt(order_id: int, filename: str) -> str:
    """Print the receipt of an order to a text file in the receipts folder. The filename is letters, digits, - and _ followed by .txt."""
    if not FILENAME.fullmatch(filename):
        raise ToolError("filename must be letters, digits, - or _ (up to 40) followed by .txt")
    order = load_order(order_id)
    if order is None:
        raise ToolError(f"Order {order_id} not found.")
    RECEIPTS_DIR.mkdir(exist_ok=True)
    text = f"Receipt #{order['id']} for {order['customer']}: {order['total_thb']} THB\n"
    subprocess.run(["tee", str(RECEIPTS_DIR / filename)], input=text, encoding="utf-8", capture_output=True, check=True)
    return f"Receipt saved to receipts/{filename}"


if __name__ == "__main__":
    mcp.run()
  • subprocess.run รับ list และไม่มี shell=True แต่ละตัวใน list เป็น argument ของโปรแกรมตรง ๆ ไม่มี shell มาอ่านตัวอักษรพิเศษ
  • ข้อความใบเสร็จส่งทาง input= เข้า stdin ของ tee ชื่อลูกค้าเลยเป็นข้อมูลที่โปรแกรมอ่าน ไม่ได้เป็น argument
  • FILENAME เป็น allowlist (รายการที่อนุญาต) ตัวแรกเป็นตัวอักษรหรือตัวเลข ตามด้วยตัวอักษร ตัวเลข - หรือ _ ไม่เกิน 40 ตัว แล้วลงท้าย .txt ไม่มี /, .., ; หรือช่องว่างผ่านได้ ชื่อไฟล์เลยออกจาก receipts ไม่ได้
  • ใช้ fullmatch เพราะ re.match กับ $ ยอมให้ newline ต่อท้ายผ่าน
  • docstring บอก AI ว่าชื่อไฟล์ต้องเป็นแบบไหน AI ก็ส่งค่าที่ถูกได้บ่อยขึ้น แต่ server ยังตรวจเองทุกครั้ง
  • ชื่อลูกค้าไม่ได้ถูกกรองที่ create_order เพราะชื่อคนมี ' หรือ " ได้ การป้องกันอยู่ที่โค้ดที่เอาชื่อไปใช้ ซึ่งในที่นี้คือการไม่ส่งชื่อเข้า shell

2. Tests

tests/test_receipt_fixed.py
import pytest
from mcp import Client

import receipt_fixed
from cafe_server import mcp as cafe

INJECTED_NAME = 'Malee"; touch pwned.txt; echo "'


@pytest.fixture(autouse=True)
def receipts_folder(tmp_path, monkeypatch):
    monkeypatch.setattr(receipt_fixed, "RECEIPTS_DIR", tmp_path / "receipts")
    monkeypatch.chdir(tmp_path)
    return tmp_path / "receipts"


async def create_order(customer: str) -> int:
    items = [{"menu": "latte", "size": "M", "quantity": 1}]
    async with Client(cafe) as client:
        result = await client.call_tool("create_order", {"items": items, "customer_name": customer})
    return result.structured_content["id"]


async def print_receipt(order_id: int, filename: str):
    async with Client(receipt_fixed.mcp) as client:
        return await client.call_tool("print_receipt", {"order_id": order_id, "filename": filename})


async def test_injected_customer_name_is_printed_literally(tmp_path, receipts_folder):
    order_id = await create_order(INJECTED_NAME)
    result = await print_receipt(order_id, "receipt.txt")
    assert not result.is_error
    assert not (tmp_path / "pwned.txt").exists()
    assert (receipts_folder / "receipt.txt").read_text() == f"Receipt #{order_id} for {INJECTED_NAME}: 60 THB\n"


@pytest.mark.parametrize(
    "filename",
    ["../escaped.txt", "sub/receipt.txt", "/tmp/receipt.txt", "receipt.txt; touch pwned.txt", "-rf.txt", "receipt.sh", "", "a" * 41 + ".txt", "receipt.txt\n"],
    ids=["parent", "subfolder", "absolute", "semicolon", "leading-dash", "extension", "empty", "too-long", "trailing-newline"],
)
async def test_unsafe_filename_is_refused_before_anything_is_written(tmp_path, receipts_folder, filename):
    order_id = await create_order("Somchai")
    result = await print_receipt(order_id, filename)
    assert result.is_error
    assert [path.name for path in tmp_path.iterdir()] == ["cafe.db"]


async def test_unknown_order_is_refused(tmp_path):
    result = await print_receipt(999, "receipt.txt")
    assert result.is_error
    assert [path.name for path in tmp_path.iterdir()] == ["cafe.db"]
  • fixture ย้าย RECEIPTS_DIR ไปโฟลเดอร์ชั่วคราวของ pytest แล้ว chdir ไปที่นั่น ถ้าคำสั่งแทรกหลุดไปถึง shell ไฟล์จะเกิดในโฟลเดอร์ชั่วคราว ไม่ใช่ในโปรเจกต์ (conftest ย้าย cafe.db มาไว้ที่เดียวกันอยู่แล้ว)
  • เทสต์แรกใช้ชื่อที่แทรกคำสั่ง ต้องไม่มี pwned.txt และใบเสร็จต้องมีชื่อนั้นครบทุกตัวอักษร
  • เทสต์ที่สองลองชื่อไฟล์ 9 แบบ ทุกแบบต้องได้ error และโฟลเดอร์ชั่วคราวต้องเหลือแค่ cafe.db

Re-run the Attack

ลบไฟล์จากรอบก่อน แล้วรัน script เดิมกับ receipt_fixed.py (2>/dev/null ซ่อน log ที่ SDK พิมพ์ตอน tool ปฏิเสธ)

bash
rm -r receipts pwned.txt escaped.txt
bash
uv run python try_injection.py fixed 2>/dev/null
ผลลัพธ์จาก uv run python try_injection.py fixed 2>/dev/null
normal name: order 6, is_error=False, Receipt saved to receipts/receipt-6.txt
injected name: order 7, is_error=False, Receipt saved to receipts/receipt-7.txt
traversal filename: order 8, is_error=True, Error executing tool print_receipt: filename must be letters, digits, - or _ (up to 40) followed by .txt
bash
ls pwned.txt escaped.txt
ผลลัพธ์จาก ls pwned.txt escaped.txt
ls: escaped.txt: No such file or directory
ls: pwned.txt: No such file or directory
bash
head receipts/*
ผลลัพธ์จาก head receipts/*
==> receipts/receipt-6.txt <==
Receipt #6 for Somchai: 60 THB

==> receipts/receipt-7.txt <==
Receipt #7 for Malee"; touch pwned.txt; echo ": 60 THB

ชื่อที่แทรกคำสั่งไว้ถูกพิมพ์ลงใบเสร็จเป็นข้อความธรรมดา

RequestVulnerableFixed
ชื่อ Somchaiบันทึกใบเสร็จบันทึกใบเสร็จ
ชื่อ Malee"; touch pwned.txt; echo "สร้าง pwned.txt ใบเสร็จเหลือ : 60 THBไม่มี pwned.txt ใบเสร็จมีชื่อครบ
ชื่อไฟล์ ../escaped.txtสร้าง escaped.txt นอก receiptsis_error=True ไม่มีไฟล์

Run the Tests

  • ชุดทดสอบของบทนี้
  • เปลี่ยน receipt_fixed.py กลับไปต่อ string แล้วดูเทสต์ Fail
  • ลบการตรวจชื่อไฟล์แล้วดูเทสต์ Fail
bash
uv run pytest tests/test_receipt_fixed.py -q
ผลลัพธ์จาก uv run pytest tests/test_receipt_fixed.py -q
...........                                                              [100%]
11 passed in 0.11s

ใน receipt_fixed.py แทนสองบรรทัดสุดท้ายก่อน return ด้วยโค้ดแบบ receipt_vulnerable.py

python
    command = f'echo "Receipt #{order["id"]} for {order["customer"]}: {order["total_thb"]} THB" | tee receipts/{filename}'
    subprocess.run(command, shell=True, cwd=RECEIPTS_DIR.parent, capture_output=True, check=True)
bash
uv run pytest tests/test_receipt_fixed.py -q | grep -E '^E +AssertionError|^FAILED|passed|failed'
ผลลัพธ์จาก uv run pytest tests/test_receipt_fixed.py -q | grep -E '^E +AssertionError|^FAILED|passed|failed'
E       AssertionError: assert not True
FAILED tests/test_receipt_fixed.py::test_injected_customer_name_is_printed_literally
1 failed, 10 passed in 0.13s

touch รันในโฟลเดอร์ชั่วคราว pwned.txt เลยมีอยู่จริง ส่วนอีก 10 ตัวไม่แตะ shell ก็ยัง pass

คืนโค้ดเดิม แล้วลบสองบรรทัดที่เริ่มด้วย if not FILENAME.fullmatch(filename): รันเฉพาะสองชื่อไฟล์ที่ไม่เขียนออกนอกโฟลเดอร์ชั่วคราว (/tmp/receipt.txt ไม่รันรอบนี้ เพราะพอไม่มีการตรวจ มันจะเขียนลง /tmp จริง)

bash
uv run pytest tests/test_receipt_fixed.py -q -k 'parent or subfolder' | grep -E '^E +AssertionError|^FAILED|passed|failed'
ผลลัพธ์จาก uv run pytest tests/test_receipt_fixed.py -q -k 'parent or subfolder' | grep -E '^E +AssertionError|^FAILED|passed|failed'
E       AssertionError: assert False
E       AssertionError: assert ['receipts', 'cafe.db'] == ['cafe.db']
FAILED tests/test_receipt_fixed.py::test_unsafe_filename_is_refused_before_anything_is_written[parent]
FAILED tests/test_receipt_fixed.py::test_unsafe_filename_is_refused_before_anything_is_written[subfolder]
2 failed, 9 deselected in 0.25s

parent เขียนไฟล์สำเร็จทั้งที่ควรได้ error ส่วน subfolder สร้างโฟลเดอร์ receipts ทิ้งไว้ก่อน tee จะ Fail คืนโค้ดเดิมแล้วรันทั้งชุด

bash
uv run pytest -q
ผลลัพธ์จาก uv run pytest -q
............................................                             [100%]
44 passed in 0.25s

33 ตัวจากบท Defend the HTTP Server บวก 11 ตัวของบทนี้

Pitfalls

  • list ปิดช่องของ shell ได้ แต่โปรแกรมปลายทางยังอ่าน argument ของมันเอง ชื่อไฟล์ที่ขึ้นต้นด้วย - จะถูกอ่านเป็น option receipt_fixed.py เลยส่ง path เต็มที่ขึ้นต้นด้วย / และ allowlist ห้าม - เป็นตัวแรกอีกชั้น
  • กรองที่ create_order อย่างเดียวไม่พอ เพราะ tool อื่นที่อ่านชื่อจาก Database ไม่ได้ผ่านจุดนั้น ต้องป้องกันที่โค้ดที่เอาค่าไปใช้ (SQL ก็หลักเดียวกัน คอร์สแรกใช้ ? placeholder)
  • sandbox ของบท Defend Against Tool Attacks ลดความเสียหายได้ แต่ promo.sb กันแค่การอ่าน cafe.db กับ network คำสั่งที่แทรกเข้ามายังสร้างไฟล์ได้ ต้องแก้ที่โค้ดด้วย
  • อย่าลงทะเบียน receipt_vulnerable.py กับ Claude Code เพราะคำสั่งที่แทรกเข้ามารันด้วยสิทธิ์ของเรา ใช้ try_injection.py แทน

Summary

print_receipt ที่ต่อ string แล้วรันด้วย shell=True ปล่อยให้ชื่อลูกค้าสร้าง pwned.txt และให้ชื่อไฟล์ที่ AI เลือกเขียนออกนอก receipts ได้ โดย tool ยังตอบสำเร็จทุกครั้ง ส่วนแบบที่ส่ง list ไม่ผ่าน shell และตรวจชื่อไฟล์ด้วย allowlist พิมพ์ชื่อลูกค้าตรงตัวและปฏิเสธ ../escaped.txt เทสต์ชุด 11 ตัวนี้ Fail ทุกครั้งที่ถอดการป้องกันตัวใดตัวหนึ่งออก

ตอนนี้ถ้ามีใครลองแทรกคำสั่งเข้ามา เรายังไม่รู้เลยว่าเกิดอะไรขึ้นบ้าง บทหน้า Audit Tool Calls บันทึกว่าใครเรียก tool ไหนด้วย argument อะไรครับ

References

Copyright © 2026