[C#] Enable process privileges

Write C# code to enable SeDebugPrivilege for the current process.
Here's a C# code snippet to enable SeDebugPrivilege for the current process:

C#:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;

class Program
{
    static void Main(string[] args)
    {
        IntPtr token;
        if (OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out token))
        {
            try
            {
                var luid = new LUID();
                if (LookupPrivilegeValue(null, SE_DEBUG_NAME, out luid))
                {
                    var tokenPrivileges = new TOKEN_PRIVILEGES
                    {
                        PrivilegeCount = 1,
                        Privileges = new LUID_AND_ATTRIBUTES[1]
                        {
                            new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = SE_PRIVILEGE_ENABLED }
                        }
                    };
                    if (AdjustTokenPrivileges(token, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero))
                    {
                        Console.WriteLine("SeDebugPrivilege has been enabled!");
                    }
                    else
                    {
                        Console.WriteLine("Failed to enable SeDebugPrivilege with error code: " + Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    Console.WriteLine("Failed to lookup SeDebugPrivilege with error code: " + Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                CloseHandle(token);
            }
        }
        else
        {
            Console.WriteLine("Failed to get process handle with error code: " + Marshal.GetLastWin32Error());
        }
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool CloseHandle(IntPtr hObject);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);

    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);

    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivileges, ref TOKEN_PRIVILEGES newState, uint bufferLength, IntPtr previousState, IntPtr returnLength);

    const uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
    const uint TOKEN_QUERY = 0x0008;
    const uint SE_PRIVILEGE_ENABLED = 0x00000002;
    const string SE_DEBUG_NAME = "SeDebugPrivilege";

    struct LUID
    {
        public uint LowPart;
        public int HighPart;
    }

    struct LUID_AND_ATTRIBUTES
    {
        public LUID Luid;
        public uint Attributes;
    }

    struct TOKEN_PRIVILEGES
    {
        public uint PrivilegeCount;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public LUID_AND_ATTRIBUTES[] Privileges;
    }
}

This code opens the current process token, looks up the LUID for the SeDebugPrivilege, and enables the privilege by adjusting the token privileges. If there are any errors, they are printed to the console. Make sure to run this code with administrative privileges, as SeDebugPrivilege requires it.
 
Write same code to enable SeSecurityPrivilege and SeTakeOwnershipPrivilege privilages, then optimize the code.
 
Write same code to enable SeSecurityPrivilege and SeTakeOwnershipPrivilege privilages, then optimize the code.
Here's a C# code snippet to enable SeSecurityPrivilege and SeTakeOwnershipPrivilege privileges:

Код:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            EnablePrivilege("SeSecurityPrivilege");
            EnablePrivilege("SeTakeOwnershipPrivilege");
            Console.WriteLine("All privileges enabled successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to enable privileges: " + ex.ToString());
        }
    }

    private static void EnablePrivilege(string privilegeName)
    {
        using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
        {
            IntPtr token;
            if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query, out token))
            {
                throw new Exception("Failed to obtain process token.");
            }

            try
            {
                LUID luid;
                if (!LookupPrivilegeValue(null, privilegeName, out luid))
                {
                    throw new Exception("Failed to obtain privilege ID for " + privilegeName + ".");
                }

                TOKEN_PRIVILEGES tokenPrivs = new TOKEN_PRIVILEGES();
                tokenPrivs.PrivilegeCount = 1;
                tokenPrivs.Privileges = new LUID_AND_ATTRIBUTES[1];
                tokenPrivs.Privileges[0].Luid = luid;
                tokenPrivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

                if (!AdjustTokenPrivileges(token, false, ref tokenPrivs, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    throw new Exception("Failed to enable privilege: " + privilegeName);
                }
            }
            finally {
                CloseHandle(token);
            }
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct LUID {
        public uint LowPart;
        public int HighPart;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct LUID_AND_ATTRIBUTES {
        public LUID Luid;
        public uint Attributes;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct TOKEN_PRIVILEGES {
        public uint PrivilegeCount;
        public LUID_AND_ATTRIBUTES[] Privileges;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool CloseHandle(IntPtr handle);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr processHandle, TokenAccessLevels desiredAccess, out IntPtr tokenHandle);

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern bool LookupPrivilegeValue(string systemName, string name, out LUID luid);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivileges, ref TOKEN_PRIVILEGES newState, uint bufferLength, IntPtr previousState, IntPtr returnLength);

    private const uint SE_PRIVILEGE_ENABLED = 0x00000002;

    [Flags]
    private enum TokenAccessLevels : uint
    {
        AssignPrimary = 0x00000001,
        Duplicate = 0x00000002,
        Impersonate = 0x00000004,
        Query = 0x00000008,
        QuerySource = 0x00000010,
        AdjustPrivileges = 0x00000020,
        AdjustGroups = 0x00000040,
        AdjustDefault = 0x00000080,
        AdjustSessionId = 0x00000100,

        AllAccess = (AssignPrimary |
            Duplicate |
            Impersonate |
            Query |
            QuerySource |
            AdjustPrivileges |
            AdjustGroups |
            AdjustDefault |
            AdjustSessionId),

        Read = (Query | QuerySource),
        Write = (AdjustPrivileges |
            AdjustGroups |
            AdjustDefault),
    }
}

This code uses a EnablePrivilege method that takes the name of the privilege as input, rather than duplicating the code to enable each privilege separately. The Enum and DllImport definitions have also been improved. The error handling has also been improved by using try-catch blocks instead of returning exceptions.
 
Назад
Сверху Снизу