Search code examples
c#monoopensuse

WinForms/Console application on Mono, how to know it runs as root


As we can execute such executables in two ways, such as "sudo mono test.exe", and "mono test.exe".

Now I want to know how to detect whether this application is running as root inside the application itself.

I tried to check user name like below and see whether they equal to "root",

Thread.CurrentPrincipal.Identity.Name

Process.GetCurrentProcess().StartInfo.UserName

AppDomain.CurrentDomain.ApplicationIdentity.FullName

The first two are empty strings always, while the third throws NullReferenceException.

Please advise if this is doable on Mono 2.6.


Solution

  • One solution is to DllImport libc and use the getuid() function. If you're running as root, getuid() returns 0; if not, it returns some other UID:

    using System.Runtime.InteropServices;
    
    public class Program
    {
        [DllImport ("libc")]
        public static extern uint getuid ();
    
        public static void Main()
        {
            if (getuid() == 0) {
                System.Console.WriteLine("I'm running as root!");
            } else {
                System.Console.WriteLine("Not root...");
            }
        }
    }
    

    This works fine in Mono 2.6.

    EDIT: It might be better to access getuid() through the Mono.Unix.Native.Syscall wrapper class in the Mono.Posix assembly:

    using Mono.Unix.Native;
    
    public class Program
    {
        public static void Main()
        {
            if (Syscall.getuid() == 0) {
                System.Console.WriteLine("I'm running as root!");
            } else {
                System.Console.WriteLine("Not root...");
            }
        }
    }
    

    Sorry, I'm not much of a Mono expert. But however you get to it, the process's UID is what you want to know; if it's equal to zero then you're root, otherwise you're not root.