Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Last active August 5, 2025 13:08
Show Gist options
  • Save ksamuel/88607765d7a218172181295ef599bcea to your computer and use it in GitHub Desktop.
Save ksamuel/88607765d7a218172181295ef599bcea to your computer and use it in GitHub Desktop.
Claude t-string attempt
#!/usr/bin/env python3.14
"""
Demonstration of Python 3.14's new t-string feature for secure command execution.
This script shows how t-strings help prevent command injection attacks.
"""
import subprocess
import os
import sys
from string.templatelib import Template, Interpolation
def run_command(template: Template) -> subprocess.CompletedProcess:
"""
Execute a command using a t-string template.
This function safely constructs a command list from a template,
preventing shell injection attacks by properly separating the
command and its arguments.
"""
# Build command list from template parts
cmd_parts = []
for item in template:
if isinstance(item, str):
# Static string parts are added as-is
if item.strip(): # Skip empty strings
cmd_parts.extend(item.split())
elif isinstance(item, Interpolation):
# Interpolated values are added as separate arguments
# This prevents them from being interpreted as shell metacharacters
value = str(item.value)
cmd_parts.append(value)
# Run the command with shell=False for safety
return subprocess.run(cmd_parts, capture_output=True, text=True, shell=False)
def demonstrate_injection_vulnerability():
"""Show how regular strings with os.system are vulnerable to injection."""
print("=== Demonstration: Command Injection Vulnerability ===\n")
# Simulated user input - normally this would come from untrusted source
user_input = "test.txt; echo 'INJECTED COMMAND' > hacked.txt"
print(f"User input: {user_input}")
print("\n1. Using os.system with string concatenation (VULNERABLE):")
# DON'T DO THIS - Vulnerable to injection!
command = f"echo 'Processing file: {user_input}'"
print(f" Command string: {command}")
print(" Executing with os.system()...")
# This would execute both commands if run
# os.system(command) # Commented out for safety
print(" [BLOCKED: Would execute injection if uncommented]\n")
print("2. Using subprocess with regular f-string (STILL VULNERABLE if misused):")
# Even with subprocess, using shell=True with f-strings is dangerous
command = f"echo 'Processing file: {user_input}'"
print(f" Command string: {command}")
# subprocess.run(command, shell=True) # Also vulnerable!
print(" [BLOCKED: Would execute injection with shell=True]\n")
def demonstrate_tstring_safety():
"""Show how t-strings provide safer command execution."""
print("=== Demonstration: T-String Safety ===\n")
# Same potentially malicious input
user_input = "test.txt; echo 'INJECTED COMMAND' > hacked.txt"
print(f"User input: {user_input}")
print("\n3. Using t-string with run_command (SAFE):")
# Create a t-string template
template = t"echo Processing file: {user_input}"
print(f" Template type: {type(template)}")
print(f" Static parts: {template.strings}")
print(f" Interpolations: [{', '.join(repr(i.value) for i in template.interpolations)}]")
# Execute safely
result = run_command(template)
print(f"\n Command executed safely!")
print(f" stdout: {result.stdout.strip()}")
print(f" stderr: {result.stderr.strip() if result.stderr else '(none)'}")
print(f" Return code: {result.returncode}")
def demonstrate_complex_example():
"""Show a more complex example with multiple interpolations."""
print("\n=== Demonstration: Complex T-String Example ===\n")
# Multiple user inputs
filename = "data.csv"
search_term = "'; DROP TABLE users; --"
output_file = "results.txt"
print(f"Filename: {filename}")
print(f"Search term: {search_term}")
print(f"Output file: {output_file}\n")
# Using t-string for a grep-like command
template = t"grep {search_term} {filename}"
print("4. Complex command with t-string:")
print(f" Template strings: {template.strings}")
print(f" Number of interpolations: {len(template.interpolations)}")
# Show how each interpolation is handled
for i, interp in enumerate(template.interpolations):
print(f" Interpolation {i}: value={repr(interp.value)}, expr={repr(interp.expression)}")
# This would safely execute grep without risk of SQL injection
# result = run_command(template)
print("\n [Command would be executed safely, treating search_term as literal text]")
def demonstrate_format_spec():
"""Show how format specifications work in t-strings."""
print("\n=== Demonstration: Format Specifications ===\n")
count = 42
precision = 2
# T-string with format specification
template = t"Processing {count} items with {precision:.1f} precision"
print("5. T-string with format specifications:")
print(f" Template type: {type(template)}")
for i, interp in enumerate(template.interpolations):
print(f"\n Interpolation {i}:")
print(f" value: {interp.value}")
print(f" expression: {interp.expression}")
print(f" format_spec: {repr(interp.format_spec)}")
print(f" conversion: {interp.conversion}")
def main():
"""Run all demonstrations."""
print("Python 3.14 T-String Security Demonstration")
print("==========================================\n")
# Check Python version
if sys.version_info < (3, 14):
print(f"WARNING: This script requires Python 3.14 or later.")
print(f"You are running Python {sys.version}")
print("T-strings are not available in your Python version.\n")
return
# Run demonstrations
demonstrate_injection_vulnerability()
print("\n" + "="*60 + "\n")
demonstrate_tstring_safety()
print("\n" + "="*60 + "\n")
demonstrate_complex_example()
print("\n" + "="*60 + "\n")
demonstrate_format_spec()
print("\n\nKey Takeaways:")
print("- T-strings provide access to both static and dynamic parts separately")
print("- This separation enables safe command construction without shell interpretation")
print("- User input is always treated as data, never as code")
print("- Format specifications and conversions are preserved for processing")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment