Skip to content

Commit

Permalink
Merge branch 'master' into snyk-upgrade-e2b41814242a201fd1532c0fbac91f4f
Browse files Browse the repository at this point in the history
  • Loading branch information
gerardog committed Feb 19, 2024
2 parents 57aafee + 1f7dd11 commit 0134977
Show file tree
Hide file tree
Showing 27 changed files with 358 additions and 113 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ Before creating one, please search https://github.com/gerardog/gsudo/issues?q=
## Context:
- Windows version:
<!-- To get Windows version, press Win+R, type `winver` and press enter.
For example: Win11 21H2 - Spanish ->
For example: Win11 21H2 - Spanish -->
- gsudo version:
<!-- Run `gsudo -v` to get gsudo version -->
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ Here are the `Credentials Cache` Modes:
- This is the default mode. (Use `gsudo config CacheMode Explicit` to revert to this value).
- `Auto:` Similar to unix-sudo. The first elevation shows a UAC popup and **starts a cache session automatically**.
- Run `gsudo config CacheMode Auto` to use this mode.
- `Disabled:` Every elevation shows a UAC popup, and tryoing to start a cache session will throw an error..
- `Disabled:` Every elevation shows a UAC popup, and trying to start a cache session will throw an error..
- Run `gsudo config CacheMode Disabled` to use this mode.

In any case, you can stop all cache sessions with `gsudo -k`.
Expand Down
70 changes: 70 additions & 0 deletions docs/docs/gsudo-vs-sudo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
---
sidebar_position: 7
title: Comparison with Microsoft sudo
#hide_title: true
---

# Comparison between gsudo and Microsoft sudo

`gsudo` was born in 2019 as a productivity tool and is open-source. It has been downloaded over 700k times so far and has enjoyed a warm reception from users.

Microsoft initially declined to create a similar tool, citing security concerns. However `gsudo`'s documentation [challenged this view](security.md) arguing that absolute security is unattainable without altering Windows itself, and that the default same-desktop UAC is not completely secure either.

In February 2024, Microsoft reversed its stance and released [Sudo for Windows](https://devblogs.microsoft.com/commandline/introducing-sudo-for-windows/).

Surprisingly, Microsoft's sudo does not leverage new OS features to enhance security. Its mechanisms are akin to `gsudo`, making their security models comparable. The question of which one is more secure depends on which version of each are you comparing, and how many open bugs it has. The initial release of Microsoft's sudo presented some [critical issues](https://www.tiraniddo.dev/2024/02/sudo-on-windows-quick-rundown.html) that they will hopefully address very soon. `gsudo` has fixed similar issues in the past and may in the future.

## Sudo Tools Feature Comparison

### Is it a proper Sudo tool?
| Feature | `gsudo` | Sudo for Windows |
| ------- | ------- | ------------------ |
| Executes command with elevated permissions | Yes | Yes |
| Supports output redirection (`sudo dir > file.txt`) | Yes | Yes |
| Supports input redirection (`echo md folder \| sudo cmd`) | Yes | Partial (Only with output redirection) |
| Returns the command exit code | Yes | No |
| Source code available | [Yes](https://github.com/gerardog/gsudo) | Not for `sudo.exe`, but [promised](https://github.com/microsoft/sudo/blob/f8f1d05/README.md#contributing) |

### Security Impersonation Features

| Feature | `gsudo` | Sudo for Windows |
| ------- | ------- | ------------------ |
| Run with custom Integrity | Yes (`-i`, `--integrity`) | No |
| Run as System | Yes (`-s`, `--system`) | No |
| Run as TrustedInstaller | Yes (`--ti`)| No |
| Run as user | Yes (`-u user`) | No |

### User Experience

| Feature | `gsudo` | Sudo for Windows |
| ------- | ------- | ------------------ |
| Easy to install and update | Yes (winget, choco, scoop) | No (Windows Insider build required) |
| See less UAC Pop-ups | Yes ([Credentials Cache](credentials-cache.md)) | No |
| Elevate current shell | Yes | No |
| Elevate commands using current shell | Yes | No |
| Red # indicator for elevation on CMD | Yes | No |

### Additional Features

| Feature | `gsudo` | Sudo for Windows |
| ------- | ------- | ------------------ |
| Run in new window | Yes | Yes |
| Option to keep new window open until a key is pressed | [Yes](tips/elevation-in-new-window.md) | No |
| Option to keep new window's shell open | [Yes](tips/elevation-in-new-window.md) | No |
| Run with Input Disabled | [Yes](https://gerardog.github.io/gsudo/docs/security#what-are-the-risks-of-running-gsudo) | Yes |
| Elevate last command with `sudo !!` | Yes | No |

### PowerShell

| Feature | `gsudo` | Sudo for Windows |
| ------- | ------- | ------------------ |
| Elevation syntax | `gsudo { Script } -args $a,$b` [syntax](usage/powershell.md#using-gsudo-scriptblock-syntax) | Unknown, possibly: `sudo pwsh { script }` |
| Auto-complete of last 3 commands | Yes (with [gsudoModule](usage/powershell.md#gsudo-powershell-module)) | No |
| Auto-complete of options | Yes (with [gsudoModule](usage/powershell.md#gsudo-powershell-module)) | No |
| Red # indicator for elevation | Yes (with [gsudoModule](usage/powershell.md#gsudo-powershell-module)) | No |

## What if I install both?

If you have both Microsoft Sudo and `gsudo` installed, they both should work independently.

The `sudo` keyword will run Microsoft's sudo instead of `gsudo` because the typical install of `Sudo for Windows` (which is via a Windows Insider build) puts it in `c:\Windows\System32\sudo.exe`. This folder appears first in the `PATH` environment variable, therefore when running `sudo`, the Microsoft `sudo.exe` will take precedence over gsudo's `sudo` alias.
30 changes: 17 additions & 13 deletions docs/docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ title: Security Considerations
hide_title: true
---

## Why Windows doesn't have a `sudo` command? Should it have one?
## Why doesn't Windows have a `sudo` command? Should it have one?

To answer this question, we first have to take a look back at the history.

In August 2002, Chris Paget released a white paper describing a form of attack against event-driven systems that he termed Shatter Attack. It allowed processes in the same session to bypass security restrictions by abusing Windows Message loop.

Microsoft response was to add "User Interface Privilege Isolation" (UIPI) and the "User Access Control" (UAC) popup to the next major release: Windows Vista. Privileged processes would then run "elevated" at high integrity level, out of reach of processes at lower, non-admin, levels.
Microsoft's response was to add "User Interface Privilege Isolation" (UIPI) and the "User Access Control" (UAC) popup to the next major release: Windows Vista. Privileged processes would then run "elevated" at high integrity level, out of reach of processes at lower, non-admin, levels.

I assume that at this point Microsoft decided not to make a `sudo` tool for windows. It would be an unwanted bridge between two worlds that intended to isolate.
I assume that at this point, Microsoft decided not to make a `sudo` tool for windows. It would be an unwanted bridge between two worlds that intended to isolate.

But that insulation quickly proved weak. Let me [quote Raymond Chen from Microsoft](https://devblogs.microsoft.com/oldnewthing/20160816-00/?p=94105):
However, that insulation quickly proved to be weak. Let me [quote Raymond Chen from Microsoft](https://devblogs.microsoft.com/oldnewthing/20160816-00/?p=94105):

> There’s a setting that lets you specify how often you want to be prompted by UAC. You can set any of four levels:
>
Expand All @@ -28,40 +28,44 @@ But that insulation quickly proved weak. Let me [quote Raymond Chen from Microso
> - Always notify
> - Meh
>
> The reason why all the other options collapse into Meh is that the `Notify only when apps try to change settings` option can be subverted by any app simply by injecting a thread into (...)
> The reason why all the other options collapse into Meh is that the `Notify only when apps try to change settings` option can be subverted by any app simply by injecting a thread (... a hacking technique explained ...)
And, up to this day, Windows 10 & 11, defaults to "Meh". Microsoft default is: user convenience at the expense of lesser security.
And, up to this day, Windows 10 & 11, defaults corresponds to that "Meh". Microsoft's default stance is user convenience at the expense of lesser security.

---
![Vista UAC](../static/img/Vista-UAC.png)
[Windows 11 UAC Settings: Default mode is recommended only if you **don't** run untrusted software.]

---

Over time, no less than a hundred UAC-bypass techniques were disclosed. Many of them still work in an updated Windows 11. Windows Defender, or your antivirus of choice, will stop them (hopefully). But if you disable your AV, UAC bypass is easy.
Over time, more than a hundred UAC-bypass techniques have been disclosed. Many of them still work in an updated Windows 11. It is Windows Defender, or your antivirus of choice, who may stop them (hopefully). But if you disable your AV, UAC bypass is easy.

Microsoft did not patch them. Instead, they assumed publicly that `UAC/UIPI` in default mode is not a security boundary. I will [quote Microsoft documentation](https://docs.microsoft.com/en-us/troubleshoot/windows-server/windows-security/disable-user-account-control#:~:text=More%20important%2C%20Same%2Ddesktop%20Elevation,be%20considered%20a%20convenience%20feature.) :
And Microsoft can't just patch them all without loosing 'convenience' features. They instead, they assumed publicly that `UAC/UIPI` in default mode is not a security boundary. I will [quote Microsoft documentation](https://docs.microsoft.com/en-us/troubleshoot/windows-server/windows-security/disable-user-account-control#:~:text=More%20important%2C%20Same%2Ddesktop%20Elevation,be%20considered%20a%20convenience%20feature.) :

> Same-desktop Elevation in UAC isn't a security boundary. It can be hijacked by unprivileged software that runs on the same desktop. Same-desktop Elevation should be considered a convenience feature.
Which means: <b>UAC does not protect you from threats. It's a convenience tool that protects you from shooting yourself in the foot. </b>
Which to me, it means: <b>UAC is a convenience tool. It does not protect you from threats, it works as a warning that protects you from shooting yourself in the foot.</b>

And, in my opinion, it's not doing the best possible job:
And if UAC is a convenience tool, in my opinion it's not doing the best possible job:

- You waste important time by switching between elevated and unelevated windows. You must manually carry your command and context to the elevated window, each time, back and forth.
- ... or you suffer from "elevation fatigue". For example, you elevate a whole console beforehand, and you do all your stuff there, likely running non-admin or untrusted stuff as admin.

**In conclusion:**
**In conclusion:**

- Same-desktop UAC is a vulnerable convenience feature, and so is `gsudo`. In any case, **the only thing that protects you from malware is you and your Antivirus.**.
- Same-desktop UAC is a vulnerable convenience feature.
- `gsudo` is also a vulnerable convenience feature.
- Whether you use `gsudo` or not, **the only thing that protects you from malware is not UAC, it is you and your Antivirus.**.

So, if you decide to use `gsudo`, here are the risks:

## What are the risks of running gsudo?

gsudo could be used as an attack vector for escalation of privileges. Using antivirus software and avoiding running untrusted software

- **Abusing an elevation made with gsudo:**

A medium integrity process could drive the gsudo-elevated process.
A medium integrity process could drive the gsudo-elevated process.

When gsudo elevates **in the same console**, it creates a connection between a medium and a high integrity process. A malicious process (at medium integrity) can then drive the medium integrity console: sending keystrokes to the high integrity app, or scrapping its screen.

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/troubleshooting.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
sidebar_position: 7
sidebar_position: 10
hide_title: true
title: Troubleshooting
---
Expand Down
3 changes: 2 additions & 1 deletion docs/docs/usage/powershell.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ When the current shell is `PowerShell`, gsudo can be used in the following ways:
3. [`gsudo 'string command'`](#using-gsudo-command-syntax) => Old, legacy syntax.

- You can [add `gsudo` PowerShell Module](#powershell-profile-config) to your `$PROFILE`
- This enables to use `gsudo !!` to elevate last command.
- This allows tab-key auto-completition. For example, write 'gsudo` then `space` and then `tab` and your last executed command will be suggested.
- Also enables to use `gsudo !!` to elevate last command.

- In a pipeline of commands, `gsudo` only elevates one command.

Expand Down
2 changes: 1 addition & 1 deletion docs/docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const darkCodeTheme = require('prism-react-renderer/themes/dracula');

/** @type {import('@docusaurus/types').Config} */
const config = {
title: 'gsudo (sudo for windows)',
title: 'gsudo Documentation',
tagline: 'The missing piece in Windows. Cherry-pick which commands to elevate with just one keyword.',
url: 'https://gerardog.github.io',
baseUrl: '/gsudo/',
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function HomepageHeader() {
return (
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<h1 className="hero__title">{siteConfig.title}</h1>
<h1 className="hero__title">gsudo (sudo for Windows)</h1>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.buttons}>
<Link
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
},
"dependencies": {
"@docusaurus/core": "^2.4.3",
"@docusaurus/plugin-google-gtag": "^2.4.1",
"@docusaurus/plugin-sitemap": "^2.4.1",
"@docusaurus/plugin-google-gtag": "^2.4.3",
"@docusaurus/plugin-sitemap": "^2.4.3",
"@docusaurus/preset-classic": "^2.4.1",
"@mdx-js/react": "^1.6.22",
"clsx": "^1.1.1",
Expand Down
2 changes: 1 addition & 1 deletion src/gsudo.Wrappers.Tests/Invoke-gsudo.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Describe "PS Invoke-Gsudo (PSv$($PSVersionTable.PSVersion.Major))" {
}

It "It throws with .Net Exceptions" {
{ Invoke-gsudo { [int]::Parse('foo') } } | Should -throw "*Input string was not*"
{ Invoke-gsudo { [int]::Parse('foo') } } | Should -throw "*nput string*"
}

It "It throws when ErrorAction = Stop" {
Expand Down
3 changes: 2 additions & 1 deletion src/gsudo.Wrappers/gsudo
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@
# For better experience (fix credentials cache) in git-bash/MinGw create this wrapper can be added as function in .bashrc:
# gsudo() { WSLENV=WSL_DISTRO_NAME:USER:$WSLENV MSYS_NO_PATHCONV=1 gsudo.exe "$@"; }

WSLENV=WSL_DISTRO_NAME:USER:$WSLENV MSYS_NO_PATHCONV=1 "$( dirname -- "$0")/gsudo.exe" "$@"
thisdir="$(dirname "$(readlink "$0")")"
WSLENV=WSL_DISTRO_NAME:USER:$WSLENV MSYS_NO_PATHCONV=1 "${thisdir}/gsudo.exe" "$@"
12 changes: 9 additions & 3 deletions src/gsudo/AppSettings/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class Settings

public static RegistrySetting<string> ExceptionList { get; } =
new RegistrySetting<string>(nameof(ExceptionList),
defaultValue: "notepad.exe;powershell.exe;whoami.exe;",
defaultValue: "notepad.exe;powershell.exe;whoami.exe;vim.exe;nano.exe;",
deserializer: (string s)=>s,
scope: RegistrySettingScope.GlobalOnly);

Expand Down Expand Up @@ -127,8 +127,14 @@ internal static TimeSpan TimeSpanParseWithInfinite(string value)
{
if (value.In("-1", "Infinite"))
return TimeSpan.MaxValue;
else
return TimeSpan.Parse(value, CultureInfo.InvariantCulture);

var timeSpan = TimeSpan.Parse(value, CultureInfo.InvariantCulture);

// Cap at 24 days.
if (timeSpan.TotalDays > 24)
return TimeSpan.MaxValue;

return timeSpan;
}

internal static string TimeSpanWithInfiniteToString(TimeSpan value)
Expand Down
9 changes: 6 additions & 3 deletions src/gsudo/Commands/RunCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,15 +231,18 @@ private void AdjustUacIsolationRequest(ElevationRequest elevationRequest, bool i
}
}

internal static bool IsRunningAsDesiredUser()
internal static bool IsRunningAsDesiredUser(bool allowHigherIntegrity = false)
{
if (InputArguments.TrustedInstaller && !WindowsIdentity.GetCurrent().Claims.Any(c => c.Value == Constants.TI_SID))
return false;

if (InputArguments.RunAsSystem && !WindowsIdentity.GetCurrent().IsSystem)
return false;
return false;

if ((int)InputArguments.GetIntegrityLevel() != SecurityHelper.GetCurrentIntegrityLevel())
if ((int)InputArguments.GetIntegrityLevel() != SecurityHelper.GetCurrentIntegrityLevel() && !allowHigherIntegrity)
return false;

if ((int)InputArguments.GetIntegrityLevel() > SecurityHelper.GetCurrentIntegrityLevel())
return false;

if (InputArguments.UserName != null && InputArguments.UserName != WindowsIdentity.GetCurrent().Name)
Expand Down
4 changes: 3 additions & 1 deletion src/gsudo/Commands/ServiceCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ class ServiceCommand : ICommand, IDisposable

void EnableTimer()
{
if (CacheDuration > TimeSpan.FromDays(24)) CacheDuration = TimeSpan.FromDays(24);

if (CacheDuration != TimeSpan.MaxValue)
ShutdownTimer.Change((int)CacheDuration.TotalMilliseconds, Timeout.Infinite);
}
Expand Down Expand Up @@ -55,7 +57,7 @@ public async Task<int> Execute()
|| (InputArguments.RunAsSystem && !System.Security.Principal.WindowsIdentity.GetCurrent().IsSystem)
|| (InputArguments.UserName != null && !SecurityHelper.IsAdministrator() && SecurityHelper.IsMemberOfLocalAdmins())
)*/
if (!RunCommand.IsRunningAsDesiredUser())
if (!RunCommand.IsRunningAsDesiredUser(allowHigherIntegrity: true))
{
Logger.Instance.Log("This service is not running with desired credentials. Starting a new service instance.", LogLevel.Info);
#if DEBUG
Expand Down
2 changes: 1 addition & 1 deletion src/gsudo/Commands/StatusCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private static void PrintToConsole(Dictionary<string, object> result)

foreach (string s in result["CacheSessions"] as string[])
{
Console.WriteLine($" {s},");
Console.WriteLine($" {s}");
}

if ((bool)result["IsRedirected"])
Expand Down
Loading

0 comments on commit 0134977

Please sign in to comment.