/// <summary>
        /// Overridden ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            NtToken token = null;

            if (Duplicate)
            {
                using (NtToken base_token = GetToken(TokenAccessRights.Duplicate))
                {
                    if (base_token != null)
                    {
                        token = base_token.DuplicateToken(TokenType, ImpersonationLevel, Access);
                        if (IntegrityLevel.HasValue)
                        {
                            using (NtToken set_token = token.Duplicate(TokenAccessRights.AdjustDefault))
                            {
                                set_token.SetIntegrityLevel(IntegrityLevel.Value);
                            }
                        }
                    }
                }
            }
            else
            {
                token = GetToken(Access);
            }
            WriteObject(token);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Do an access check between a security descriptor and a token to determine the allowed access.
        /// </summary>
        /// <param name="sd">The security descriptor</param>
        /// <param name="token">The access token.</param>
        /// <param name="access_rights">The set of access rights to check against</param>
        /// <param name="generic_mapping">The type specific generic mapping (get from corresponding NtType entry).</param>
        /// <returns>The allowed access mask as a unsigned integer.</returns>
        /// <exception cref="NtException">Thrown if an error occurred in the access check.</exception>
        public static uint GetAllowedAccess(SecurityDescriptor sd, NtToken token, GenericAccessRights access_rights, GenericMapping generic_mapping)
        {
            if (sd == null)
            {
                throw new ArgumentNullException("sd");
            }

            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            using (var sd_buffer = sd.ToSafeBuffer())
            {
                using (NtToken imp_token = token.DuplicateToken(SecurityImpersonationLevel.Identification))
                {
                    uint     granted_access;
                    NtStatus result_status;
                    using (var privs = new SafePrivilegeSetBuffer())
                    {
                        int buffer_length = privs.Length;

                        NtSystemCalls.NtAccessCheck(sd_buffer, imp_token.Handle, (uint)access_rights,
                                                    ref generic_mapping, privs, ref buffer_length, out granted_access, out result_status).ToNtException();
                        if (result_status.IsSuccess())
                        {
                            return(granted_access);
                        }
                        return(0);
                    }
                }
            }
        }
 private NtToken OpenImpersonationToken()
 {
     using (NtToken token = NtToken.OpenProcessToken())
     {
         return(token.DuplicateToken(SecurityImpersonationLevel.Identification));
     }
 }
 private void btnDuplicate_Click(object sender, EventArgs e)
 {
     try
     {
         using (NtToken token = _token.DuplicateToken((TokenType)comboBoxTokenType.SelectedItem,
                                                      (SecurityImpersonationLevel)comboBoxImpLevel.SelectedItem, TokenAccessRights.MaximumAllowed))
         {
             TokenIntegrityLevel il = GetILFromComboBox(comboBoxILForDup);
             if (il != token.IntegrityLevel)
             {
                 token.SetIntegrityLevel(il);
             }
             OpenForm(token, "Duplicate", true);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
 private static NtToken DuplicateToken(NtToken token)
 {
     if (token.TokenType == TokenType.Primary)
     {
         return(token.DuplicateToken(TokenType.Impersonation, SecurityImpersonationLevel.Impersonation,
                                     TokenAccessRights.Query | TokenAccessRights.Impersonate | TokenAccessRights.Duplicate));
     }
     else
     {
         return(token.Duplicate(TokenAccessRights.Query | TokenAccessRights.Impersonate | TokenAccessRights.Duplicate));
     }
 }
 private NtToken GetToken()
 {
     if (Token != null)
     {
         return(Token.DuplicateToken(TokenType.Impersonation,
                                     SecurityImpersonationLevel.Identification, TokenAccessRights.Query));
     }
     else
     {
         using (NtToken token = NtToken.OpenEffectiveToken())
         {
             return(token.DuplicateToken(TokenType.Impersonation,
                                         SecurityImpersonationLevel.Identification, TokenAccessRights.Query));
         }
     }
 }
Ejemplo n.º 7
0
 public COMAccessCheck(NtToken token,
                       string principal,
                       COMAccessRights access_rights,
                       COMAccessRights launch_rights,
                       bool ignore_default)
 {
     m_access_cache = new Dictionary <string, bool>();
     m_launch_cache = new Dictionary <string, bool>();
     m_access_cache[string.Empty] = false;
     m_launch_cache[string.Empty] = false;
     m_access_token   = token.DuplicateToken(SecurityImpersonationLevel.Identification);
     m_principal      = principal;
     m_access_rights  = access_rights;
     m_launch_rights  = launch_rights;
     m_ignore_default = ignore_default;
 }
        static NtToken CreateProcessForToken(string cmdline, NtToken token, bool make_interactive)
        {
            using (NtToken newtoken = token.DuplicateToken(TokenType.Primary, SecurityImpersonationLevel.Anonymous, TokenAccessRights.MaximumAllowed))
            {
                string desktop = null;
                if (make_interactive)
                {
                    desktop = @"WinSta0\Default";
                    newtoken.SetSessionId(NtProcess.Current.SessionId);
                }

                using (Win32Process process = Win32Process.CreateProcessAsUser(newtoken, null, cmdline, CreateProcessFlags.None, desktop))
                {
                    return(process.Process.OpenToken());
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Overridden ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            NtToken token = null;

            if (Duplicate)
            {
                using (NtToken base_token = GetToken(TokenAccessRights.Duplicate))
                {
                    token = base_token.DuplicateToken(TokenType, ImpersonationLevel, Access);
                }
            }
            else
            {
                token = GetToken(Access);
            }
            WriteObject(token);
        }
Ejemplo n.º 10
0
 public static NtToken GetAccessToken(NtToken token, NtProcess process, int process_id)
 {
     if (token != null)
     {
         return(token.DuplicateToken(SecurityImpersonationLevel.Identification));
     }
     else if (process != null)
     {
         return(GetProcessAccessToken(process));
     }
     else
     {
         using (var p = NtProcess.Open(process_id, ProcessAccessRights.QueryLimitedInformation))
         {
             return(GetProcessAccessToken(p));
         }
     }
 }
Ejemplo n.º 11
0
        private static NtToken DuplicateForAccessCheck(NtToken token)
        {
            if (token.IsPseudoToken)
            {
                // This is a pseudo token, pass along as no need to duplicate.
                return(token);
            }

            if (token.TokenType == TokenType.Primary)
            {
                return(token.DuplicateToken(TokenType.Impersonation, SecurityImpersonationLevel.Identification, TokenAccessRights.Query));
            }
            else if (!token.IsAccessGranted(TokenAccessRights.Query))
            {
                return(token.Duplicate(TokenAccessRights.Query));
            }
            else
            {
                // If we've got query access rights already just create a shallow clone.
                return(token.ShallowClone());
            }
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            Win32Process new_process = null;

            try
            {
                CreateProcessFlags flags = CreateProcessFlags.None;
                bool parent_process      = false;
                bool set_il            = false;
                TokenIntegrityLevel il = 0;
                bool show_help         = false;

                OptionSet opts = new OptionSet()
                {
                    { "p", "Use parent technique to create the new process", v => parent_process = v != null },
                    { "j", "Try and break away from the current process job", v => flags |= v != null ? CreateProcessFlags.BreakawayFromJob : 0 },
                    { "c", "Create a new console for the process", v => flags |= v != null ? CreateProcessFlags.NewConsole : 0 },
                    { "s", "Create the process suspended", v => flags |= v != null ? CreateProcessFlags.Suspended : 0 },
                    { "i|il=", "Set the process IL level", v => {
                          il = ParseIL(v); set_il = true;
                      } },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                };

                int pid;

                List <string> commands = opts.Parse(args);
                if (show_help || commands.Count < 2)
                {
                    ShowHelp(opts);
                }

                if (!int.TryParse(commands[0], out pid))
                {
                    throw new ArgumentException("Couldn't parse PID value");
                }

                if (!NtToken.EnableDebugPrivilege())
                {
                    Console.WriteLine("WARNING: Couldn't enable Debug privilege");
                }

                using (NtProcess process = NtProcess.Open(pid, ProcessAccessRights.MaximumAllowed))
                {
                    if (parent_process)
                    {
                        new_process = Win32Process.CreateProcess(process, null, commands[1], set_il ? flags | CreateProcessFlags.Suspended : flags, null);
                        if (set_il)
                        {
                            using (NtToken token = new_process.Process.OpenToken())
                            {
                                token.SetIntegrityLevel(il);
                            }
                            if ((flags & CreateProcessFlags.Suspended) == 0)
                            {
                                new_process.Thread.Resume();
                            }
                        }
                    }
                    else
                    {
                        using (NtToken token = process.OpenToken())
                        {
                            using (NtToken target_token = token.DuplicateToken(TokenType.Primary, SecurityImpersonationLevel.Anonymous, TokenAccessRights.MaximumAllowed))
                            {
                                if (set_il)
                                {
                                    target_token.SetIntegrityLevel(il);
                                }

                                new_process = Win32Process.CreateProcessAsUser(target_token, null, commands[1], flags, null);
                            }
                        }
                    }

                    using (new_process)
                    {
                        Console.WriteLine("Created Process: PID: {0}, SID {1}", new_process.Pid, new_process.Process.SessionId);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: {0}", ex.Message);
                if (new_process != null && new_process.Process != null)
                {
                    try
                    {
                        new_process.Process.Terminate(NtStatus.STATUS_WAIT_1);
                    }
                    catch
                    {
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private async static Task <InterfaceLists> GetInterfacesOOP(string command_line, bool runtime_class, COMRegistry registry, NtToken token)
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In,
                                                                                    HandleInheritability.Inheritable, 16 * 1024, null))
            {
                using (var imp_token = token?.DuplicateToken(SecurityImpersonationLevel.Impersonation))
                {
                    if (imp_token != null)
                    {
                        imp_token.Inherit = true;
                    }

                    string process = null;
                    if (!Environment.Is64BitOperatingSystem || Environment.Is64BitProcess)
                    {
                        process = COMUtilities.GetExePath();
                    }
                    else
                    {
                        process = COMUtilities.Get32bitExePath();
                    }

                    Process       proc = new Process();
                    List <string> args = new List <string>
                    {
                        runtime_class ? "-r" : "-e",
                                  server.GetClientHandleAsString(),
                                  command_line
                    };

                    if (imp_token != null)
                    {
                        args.Insert(0, imp_token.Handle.DangerousGetHandle().ToInt32().ToString());
                        args.Insert(0, "-t");
                    }

                    ProcessStartInfo info = new ProcessStartInfo(process, string.Join(" ", args))
                    {
                        UseShellExecute = false,
                        CreateNoWindow  = true
                    };
                    proc.StartInfo = info;
                    proc.Start();
                    try
                    {
                        List <COMInterfaceInstance> interfaces         = new List <COMInterfaceInstance>();
                        List <COMInterfaceInstance> factory_interfaces = new List <COMInterfaceInstance>();
                        server.DisposeLocalCopyOfClientHandle();

                        using (StreamReader reader = new StreamReader(server))
                        {
                            while (true)
                            {
                                string line = await reader.ReadLineAsync();

                                if (line == null)
                                {
                                    break;
                                }

                                if (line.StartsWith("ERROR:"))
                                {
                                    uint errorCode;
                                    try
                                    {
                                        errorCode = uint.Parse(line.Substring(6), System.Globalization.NumberStyles.AllowHexSpecifier);
                                    }
                                    catch (FormatException ex)
                                    {
                                        Debug.WriteLine(ex.ToString());
                                        errorCode = 0x80004005;
                                    }

                                    throw new Win32Exception((int)errorCode);
                                }
                                else
                                {
                                    bool factory = false;

                                    if (line.StartsWith("*"))
                                    {
                                        factory = true;
                                        line    = line.Substring(1);
                                    }

                                    string[] parts = line.Split(new char[] { ',' }, 3);
                                    if (Guid.TryParse(parts[0], out Guid g))
                                    {
                                        string module_path   = null;
                                        long   vtable_offset = 0;
                                        if (parts.Length == 3)
                                        {
                                            module_path = parts[1];
                                            long.TryParse(parts[2], out vtable_offset);
                                        }

                                        if (factory)
                                        {
                                            factory_interfaces.Add(new COMInterfaceInstance(g, module_path, vtable_offset, registry));
                                        }
                                        else
                                        {
                                            interfaces.Add(new COMInterfaceInstance(g, module_path, vtable_offset, registry));
                                        }
                                    }
                                }
                            }

                            if (!proc.WaitForExit(5000))
                            {
                                proc.Kill();
                            }
                            int exitCode = proc.ExitCode;
                            if (exitCode != 0)
                            {
                                interfaces         = new List <COMInterfaceInstance>(new COMInterfaceInstance[] { new COMInterfaceInstance(COMInterfaceEntry.IID_IUnknown, registry) });
                                factory_interfaces = new List <COMInterfaceInstance>(new COMInterfaceInstance[] { new COMInterfaceInstance(COMInterfaceEntry.IID_IUnknown, registry) });
                            }
                            return(new InterfaceLists()
                            {
                                Interfaces = interfaces, FactoryInterfaces = factory_interfaces
                            });
                        }
                    }
                    finally
                    {
                        proc.Close();
                    }
                }
            }
        }
        public static NtToken CreateProcessForToken(string cmdline, NtToken token, bool make_interactive)
        {
            try
            {
                using (NtToken newtoken = token.DuplicateToken(TokenType.Primary, SecurityImpersonationLevel.Anonymous, TokenAccessRights.MaximumAllowed))
                {
                    string desktop = null;
                    if (make_interactive)
                    {
                        desktop = @"WinSta0\Default";
                        newtoken.SetSessionId(NtProcess.Current.SessionId);
                    }

                    using (Win32Process process = Win32Process.CreateProcessAsUser(newtoken, null, cmdline, CreateProcessFlags.None, desktop))
                    {
                        return process.Process.OpenToken();
                    }
                }
            }
            catch (NtException ex)
            {
                throw ex.AsWin32Exception();
            }
        }