Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Created August 5, 2025 13:01
Show Gist options
  • Save ksamuel/fcc2e5c12c330b68e7672afa13901c09 to your computer and use it in GitHub Desktop.
Save ksamuel/fcc2e5c12c330b68e7672afa13901c09 to your computer and use it in GitHub Desktop.
ChatGPT t-string attempt
import os
import subprocess
# ✅ SAFE: run a command using t-string and subprocess.run
def run_command(cmd: t-str):
"""Run a shell command safely using t-strings and subprocess.run."""
print(f"Running securely: {cmd}")
result = subprocess.run(cmd, capture_output=True, text=True)
print("Output:", result.stdout.strip())
if result.stderr:
print("Error:", result.stderr.strip())
# ❌ UNSAFE: vulnerable function using os.system
def vulnerable_command(user_input: str):
"""Run a shell command using os.system (vulnerable to injection)."""
cmd = f"echo Listing file: {user_input}"
print(f"Running insecurely: {cmd}")
os.system(cmd)
# === DEMO ===
# Simulated "safe" input
safe_input = "safe_file.txt"
# Simulated "malicious" input that would cause injection in vulnerable code
malicious_input = "safe_file.txt; echo 'Injected!' > /tmp/hacked"
print("\n--- SAFE COMMAND USING t-STRINGS ---")
run_command(t"echo Listing file: {safe_input}")
print("\n--- UNSAFE COMMAND USING os.system ---")
vulnerable_command(malicious_input)
# Show if /tmp/hacked was created (injected)
if os.path.exists("/tmp/hacked"):
print("\n⚠️ Injection succeeded! /tmp/hacked was created.")
with open("/tmp/hacked") as f:
print("Contents of /tmp/hacked:", f.read().strip())
else:
print("\n✅ Injection prevented. /tmp/hacked does not exist.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment