Tag Archives: C#

C# ‘sudo’

I wanted to create a sudo-clone for Windows using C#. Due to security stuff in Windows you cannot redirect input/output from the elevated cmd, so I was only able to open a new elevated cmd.

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace sudo
{
    class Program
    {
        static void Main(string[] args)
        {
            String path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
            String ownDir = ";" + Environment.CurrentDirectory;

            if (!path.Contains(ownDir))
            {
                if (MessageBox.Show("Install into path variable?", "Install?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Environment.SetEnvironmentVariable("Path", path + ownDir, EnvironmentVariableTarget.Machine);
                    MessageBox.Show("Installed to path variable.");
                }
            }
            else
            {
                ProcessStartInfo proc = new ProcessStartInfo();
                proc.UseShellExecute = true;
                proc.WorkingDirectory = @"C:\Windows\System32";
                proc.FileName = @"C:\Windows\System32\cmd.exe";
                proc.Verb = "runas";

                try
                {
                    Process.Start(proc);
                    Console.WriteLine("Successfully elevated!");
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to elevate.");
                }
            }
        }
    }
}

First, I check if the current working dir is in our environment variable. If it isn’t, I ask if you want to add it (‘install it’). When done, you should be able to just type ‘sudo’ in a command prompt. This will launch the executable which will create a new elevated cmd.

I added a app.manifest file to make sure the program will launch with admin rights, otherwise I wouldn’t be able to install – and when spawning an elevated cmd it’d still create an UAC popup.

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />