Получите привилегии администратора с gsudo

Sudo in PowerShell: Get Administrator Privileges With gsudo

Installing gsudo With WinGet

We can simply install the gsudo package using the Windows Package Manager (winget). If you’re unsure if you have winget installed I cover this awesome Windows tool in a previous blog post.

The package we are going to install is the geradog.gsudo application. We can perform a simple search for this package using winget. To find the correct Windows package we’ll use the winget search command to find the appropriate package.

Получите привилегии администратора с gsudo

winget search gsudo

winget install geradog.gsudo

winget install geradog.gsudo

winget install geradog.gsudo

Once installed we need to make sure that gsudo is correctly added to the Windows Path environment variable.

Adding gsudo To the Windows Path Variable

$OldPath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path

Next let’s append the path to gsudo.exe to our current path.

$NewPath = "$OldPath;C:\Program Files\gsudo\Current\"

Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $NewPath

Получите привилегии администратора с gsudo

windows powershell updating path variable process

If successful we should see the correct path to gsudo appended to our Windows path variable.

output of $env:path shows that gsudo was added successfully to the path

Windows path variable now includes the path to gsudo

Running gsudo

Once we have added the location of gsudo.exe to our Windows PATH variable we can run gsudo from our PowerShell terminal to elevate the our prompt. We can simply run gsudo from the PowerShell terminal

Получите привилегии администратора с gsudo

gsudo UAC confirmation

gsudo elevated prompt window

gsudo elevated prompt window

Once we have successfully run gsudo notice the elevated terminal. We can verify the window is elevated by running gusdo again. If already elevated gsudo will return an already running with elevated permissions error.

gsudo already running with specified user/permission-level error

Getting Help with gsudo Usage

Like most command-line tools we can use the help command to see gsudo usage information as well as common syntax options.

gsudo —help command

gsudo —help command

You can also visit the gsudo documentation page for usage tips and tricks as well as everyday usage. If you run into any issues there is also a common troubleshooting page as well as a known issues page.

Conclusion

If you have any questions or have issues feel free to message me on social media.

The Windows Insider Preview build 26052 just shipped with a sudo command, I thought I’d just take a quick peek to see what it does and how it does it. This is only a short write up of my findings, I think this code is probably still in early stages so I wouldn’t want it to be treated too harshly. You can see the official announcement

To run a command using sudo you can just type:

C:\> sudo powershell.exe

This is slightly disappointing as I was hoping the developers would have implemented a sudo service running at a higher privilege level to mediate access. Instead this is really just a fancy executable that you can elevate using the existing UAC mechanisms. 

:/>  Как создать пакетный файл в Windows 11 или 10?

There are four modes of operation that can be configured in system settings, why this needs to be a system setting I don’t really know. 

Initially sudo is disabled, running the sudo command just prints “Sudo is disabled on this machine. To enable it, go to the Developer Settings page in the Settings app”. This isn’t because of some fundamental limit on the behavior of the sudo implementation, instead it’s just an which is set to 0.

The next option (value 1) is to run the command in a new window. All this does is pass the command line you gave to sudo to verb. Therefore you just get the normal UAC dialog showing for that command. Considering the general move to using PowerShell for everything you can already do this easily enough with the command:

PS> Start-Process -Verb runas powershell.exe

C:\> sudo elevate -p 1234 powershell.exe

Oddly, as we’ll see passing the PID and the command seems to be mostly unnecessary. At best it’s useful if you want to show more information about the command in the UAC dialog, but again as we’ll see this isn’t that useful.

The only difference between the two is “With input disabled” you can only output text from the elevated application, you can’t interact with it. Whereas the Inline mode allows you to run the command elevated in the same console session. This final mode has the obvious risk that the command is running elevated but attached to a low privileged window. Malicious code could inject keystrokes into that console window to control the privileged process. This was pointed out in the Microsoft blog post linked earlier. However, the blog does say that running it with input disabled mitigates this issue somewhat, as we’ll see it does not.

How It Really Works

A diagram showing how sudo on windows works. Importantly it shows that there's an RPC channel between a normal sudo process and an elevated one.

What always gets me interested is where there’s an RPC channel involved. The reason a communications channel exists is due to the limitations of UAC, it very intentionally doesn’t allow you to attach elevated console processes to an existing low privileged console (UAC is not a security boundary, but then why did this do this if it wasn’t ). It also doesn’t pass along a few important settings such as the current directory or the environment which would be useful features to have in a sudo like command. Therefore to do all that it makes sense for the normal privileged sudo to pass that information to the elevated version.

Let’s check out the RPC server using NtObjectManager:

PS> $rpc = Get-RpcServer C:\windows\system32\sudo.exe

PS> Format-RpcServer $rpc

HANDLE p0 – Handle to the calling process.

int p1 – The type of the new process, 2 being input disabled, 3 being inline.

char* p2 – The command line to execute (oddly, in ANSI characters)

int p4 – Size of p3.

char* p5 – The current directory.

:/>  Как изменить дату в lumia 525

int p6 – Not sure, seems to be set to 1 when called.

int p7 – Not sure, seems to be set to 0 when called.

The RPC server is registered to use with the port name being where PID is just the value passed on the elevation command line for the argument. The PID isn’t used for determining the console to attach to, this is instead passed through the HANDLE parameter, and is only used to query its PID to pass to the

PS> $c = Get-RpcClient $rpc

PS> Connect-RpcClient $c -EndpointPath sudo_elevate_4652

There are no checks for the caller’s PID to make sure it’s really the non-elevated sudo making the request. As long as the RPC server is running you can make the call. Finding the ALPC port is easy enough, you can just enumerate all the ALPC ports in l to find them. 

PS> Start-Process -Verb runas -FilePath sudo -ArgumentList “elevate”, “-p”, 1111, “cmd.exe”

Fortunately sudo will exit immediately if it’s configured in disabled mode, so as long as you don’t change the defaults it’s fine I guess.

Looking back at how the RPC server is registered can be enlightening:

  result = RpcServerUseProtseqEpA(“ncalrpc”, 

      RPC_C_PROTSEQ_MAX_REQS_DEFAULT, Endpoint, NULL);

  if ( !result )

    result = RpcServerRegisterIf(server_sudo_rpc_ServerIfHandle, NULL, NULL);

    if ( !result )

      return RpcServerListen(1, RPC_C_PROTSEQ_MAX_REQS_DEFAULT, 0);

PS> $as = Get-NtAlpcServer

PS> Format-NtSecurityDescriptor $sudo -Summary

<Group> : DESKTOP-9CF6144\None

Yup, the DACL for the ALPC port has the group. It would even allow restricted tokens with the SID set such as the Chromium GPU processes to access the server. This is pretty poor security engineering and you wonder how this got approved to ship in such a prominent form. 

I will give Microsoft props though for writing the code in Rust, at least most of it. Of course it turns out that the likelihood that it would have had any useful memory corruption flaws to be low even if they’d written it in ANSI C. This is a good lesson on why just writing in Rust isn’t going to save you if you end up just introducing logical bugs instead.

В Windows 11 в обозримом будущем может появиться встроенная поддержка выполнения команд с автоматическим кратковременным повышением прав до суперпользователя. В Linux есть похожая команда – Sudo, и именно она может быть внедрена в Windows 11 в одной из ближайших сборок.

Была Windows, стал Linux

Пример использования Sudo в Linux

Microsoft, судя по всему, решила не отставать от конкурентов. Поддержка Sudo будет добавлена в привычный инструментарий Windows – в командную строку выполнения команд и оболочку PowerShell.

Никаких подробностей

Как именно будет функционировать Sudo в составе Windows с использованием ее посредством командной строки и утилиты PowerShell, к моменту выхода материала известно не было. Возможно, поддержка команды станет частью именно самой Windows 11, или же она каким-либо образом будет связана с подсистемой Windows Subsystem for Linux, появившейся весной 2019 г. и позволяющей запускать Linux-приложения и даже Linux-дистрибутивы непосредственно из-под Windows.

:/>  Как создать bat файл и работать с ним

Microsoft хранит молчание, бета-тестеры, имеющие доступ к ранним сборкам Windows – тоже. Нововведение, похоже, достанется только Windows 11 – ее предшественница (Windows 10), явившая миру подсистему WSL, с весны 2023 г. не получает обновления функциональности.

Код уже готов

Зачем Microsoft понадобилась поддержка Sudo в Windows, пока неясно

Xeno утверждает, что нашел в коде следующие строки: SystemSettings_Developer_Mode_Setting_Sudo, Enable sudo, Enable the sudo command и Configure how sudo runs applications. Как именно он их обнаружил, Xeno не уточнил.

Откуда в Windows суперпользователь

Если предположить, что поддержку Sudo Microsoft встроит в Windows 11 без связи с подсистемой WSL, то, получится, что она продублирует уже имеющуюся в системе аналогичную возможность. В современных Windows есть пользователь «Администратор», учетная запись которого по умолчанию отключена. «Администратор» обладает существенно большим набором прав в системе по сравнению с обычным пользователем, а в Windows есть опция запуска любой программы от имени «Администратора».

Все уже придумано заранее

В утилите PowerShell аналогичное действие выполняется при помощи команды start-process. Пример: start-process “C:\Program Files\Google\Chrome\Application\chrome.exe” –verb runas.

Дмитрий Чудинов, Почта России: Некоторые сложные кибероперации так и остаются нерасследованными

Получите привилегии администратора с gsudo

Также можно вручную активировать в системе профиль «Администратор» использовать его в качестве основной учетной записи.

Активированная учетная запись «Администратор» в Windows 11 22H2

В этом случае команда «запустить от имени Администратора» больше никогда не потребуется.


Время на прочтение

Получите привилегии администратора с gsudo

Microsoft официально представила новую функцию «Sudo для Windows» для Windows 11. Компания опубликовала наработки по проекту утилиты sudo на GitHub под открытой лицензией MIT. «Sudo для Windows» появилась спустя 44 года после выхода первой версии sudo на 4.1BSD.

Получите привилегии администратора с gsudo

«Наша команда работает над открытием исходного кода “Sudo для Windows”. Вы можете внести свой вклад в скрипт sudo.ps1. Он предназначен для создания вспомогательной оболочки sudo.exe, которая обеспечивает более удобный интерфейс использования sudo из PowerShell», — обратились к сообществу специалисты из Microsoft.

Примечательно, что репозиторий Sudo for Windows Documentation ещё закрыт, но находится в разработке.

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

Получите привилегии администратора с gsudo

Также можно будет включить Sudo для Windows, выполнив следующую команду в сеансе консоли с повышенными привилегиями: sudo config –enable <configuration_option>.

При активации опции можно будет настроить поведение команд sudo, установив предпочтения для работы команд, запускаемых с помощью этой утилиты. Для этого нужно выбрать один один из трёх режимов работы sudo: In a New Window (forceNewWindow), Input closed (disableInput) и Inline (normal):

Получите привилегии администратора с gsudo
Получите привилегии администратора с gsudo

Пример работы с Sudo в режиме New Window (запуск команды sudo netstat -ab):

В Microsoft пояснили, что проект только начал развиваться. «Если вам нужны дополнительные опции, которых нет в “Sudo для Windows”, ознакомьтесь с gsudo разработчика Джерардо Гриньоли. Этот проект имеет ряд дополнительных функций и параметров конфигурации», — уточнили разработчики из Microsoft.

A Brief History of Sudo. Sudo было задумано и реализовано Бобом Коггешхоллом и Клиффом Спенсером примерно в 1980 году на факультете компьютерных наук SUNY/Buffalo, первый запуск утилиты был на VAX-11/750 под управлением 4.1BSD. Sudo в его нынешнем виде поддерживается мейнтейнером проекта Тоддом К. Миллером , который продолжает улучшать sudo и исправлять ошибки.

Если эта публикация вас вдохновила и вы хотите поддержать автора — не стесняйтесь нажать на кнопку