Khaine775
Khaine775

Reputation: 2765

HttpListener "Access denied" with trying to add url to ACL

I have a WPF application using HttpListener, but whenever I start listening I get an "access denied" exception due to not running the app as administrator. I have the following code which will restart the server in case the user is not an admin and start the server with elevated privileges but I suspect it won't work unless the end user has administrator rights.

private static bool IsAdmin()
    {
        WindowsIdentity identity = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }


    private void StartServerButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (IsAdmin() != true)
            {
                MessageBox.Show("You need admin privileges to run this server. Restarting server as admin.");
                var programName = Process.GetCurrentProcess().MainModule.FileName;
                ProcessStartInfo startInfo = new ProcessStartInfo(programName);
                startInfo.Verb = "runas";
                Process.Start(startInfo);
                Application.Current.Shutdown();
                return;
            }

I've read that HttpListener uses the kernel driver and opening listeners here is secured by the ACL, so I need to set up the ACL using netsh, but I'm a little clueless as to how I do this. I've tried doing the following which makes the UAC prompt me about allowing the program to make changes to my computer, but I still get an access denied when trying to start the listener?

I'm calling AddAddress(localIp) after initializing the main window.

 public void AddAddress(string address)
    {
        AddAddressToAcl(address, Environment.UserDomainName, Environment.UserName);
    }

    public static void AddAddressToAcl(string address, string domain, string user)
    {
        string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);

        ProcessStartInfo startInfo = new ProcessStartInfo("netsh", args);
        startInfo.Verb = "runas";
        startInfo.CreateNoWindow = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.UseShellExecute = true;

        Process.Start(startInfo).WaitForExit();
    }

Upvotes: 0

Views: 895

Answers (1)

Khaine775
Khaine775

Reputation: 2765

It seemed like the problem I had was that the address I gave to AddAddress() was wrong.

Upvotes: 1

Related Questions