BlackSpy
BlackSpy

Reputation: 5603

How to run app as sudo

I have written a .NET Core Mac OSX Menu Agent App (i.e. UI is an icon in the menu bar with a context menu).

One of the features of this app is hosts file updates (i.e. add/remove entries from /etc/hosts). But to write to the file you need sudo permissions.

The file update re-writes the whole file using System.IO.File.WriteAllText.

How can I either:

  1. Launch the app as sudo (prompting in some way) while still allowing users to click on the App rather than launch from terminal, or

  2. Provide sudo access in some way to the File.WriteAllText command (prompting the user when needed).

In short, what do I need to do to provide access to update the hosts file?

Upvotes: 3

Views: 2132

Answers (2)

BlackSpy
BlackSpy

Reputation: 5603

I finally found the solution to this thanks to @SushiHangover's suggestions which led to the following post: https://forums.xamarin.com/discussion/103039/xamarin-mac-multiple-do-shell-script-with-administrator-privilege-with-one-password-request

Instead of using the System.IO.File static methods to write to the hosts file directly, I instead write to a temporary file. I then launch the cat command to overwrite the contents of the hosts file with the contents of the temp file by using the ExecuteWithPrivileges method. This brings up the Mac default prompt for the users password and the cat command is executed as sudo.

private static void WriteToHostsFile(IEnumerable<HostEntry> hostEntries, IHostsFileWriter hostsWriter)
    {
        var hostsText = hostsWriter.GetHostsFileText(hostEntries);
        var fi = new FileInfo("hoststemp.txt");
        File.WriteAllText("hoststemp.txt", hostsText);
        var defaults = Security.AuthorizationFlags.Defaults;
        using (var auth = Security.Authorization.Create(defaults))
        {
            auth.ExecuteWithPrivileges("/bin/cat", defaults, new[] { fi.FullName + " > /etc/hosts" });
        }
    }

It should be noted that this method has been marked as deprecated in favor of SMJobBless: https://developer.apple.com/library/archive/samplecode/SMJobBless/Introduction/Intro.html

I haven't managed to work that out in Xamarin yet though, and looks quite involved for the small task I needed to do.

Upvotes: 1

Courtney The coder
Courtney The coder

Reputation: 147

in your apps boot script you want this.

/usr/bin/osascript -e 'Run app "dotnet MyCoolApp" with administrator privileges?'

More info here: Getting sudo to ask for password via the GUI

Upvotes: 0

Related Questions