public CreateRestrictedTokenForm(NtToken token)
 {
     InitializeComponent();
     _token = token;
     PopulateGroupList(listViewDisableSids, new UserGroup[] { token.User});
     PopulateGroupList(listViewDisableSids, token.Groups.Where(g => !g.DenyOnly));
     foreach (TokenPrivilege priv in token.Privileges)
     {
         ListViewItem item = new ListViewItem(priv.Name);
         item.SubItems.Add(priv.DisplayName);
         item.Tag = priv;
         listViewDeletePrivs.Items.Add(item);
     }
 }
 private void toolStripMenuItemOpenThreadToken_Click(object sender, EventArgs e)
 {
     if (listViewThreads.SelectedItems.Count > 0)
     {
         NtThread thread = listViewThreads.SelectedItems[0].Tag as NtThread;
         if (thread != null)
         {
             NtToken token = GetToken(thread);
             if (token != null)
             {
                 TokenForm.OpenForm(token, false);
             }
         }
     }
 }
 internal TokenInformation(NtToken token)
 {
     SourceData               = new Dictionary <string, object>();
     TokenId                  = token.Id;
     UserName                 = token.User.Sid;
     IntegrityLevel           = token.IntegrityLevel;
     TokenType                = token.TokenType;
     ImpersonationLevel       = token.ImpersonationLevel;
     AppContainer             = token.AppContainer;
     AppContainerSid          = token.AppContainerSid;
     Elevated                 = token.Elevated;
     Restricted               = token.Restricted;
     LowPrivilegeAppContainer = token.LowPrivilegeAppContainer;
     SessionId                = token.SessionId;
 }
 /// <summary>
 /// Get the token from the clipboard.
 /// </summary>
 /// <param name="desired_access">The access rights for the opened token.</param>
 /// <returns>The clipboard token.</returns>
 public static NtToken GetTokenFromClipboard(TokenAccessRights desired_access)
 {
     try
     {
         return(NtToken.FromHandle(OpenClipboardToken(desired_access)));
     }
     catch (NtException)
     {
         throw;
     }
     catch
     {
         throw new InvalidOperationException("GetClipboardAccessToken doesn't exist");
     }
 }
예제 #5
0
        static void ListenTest(int pid, IPEndPoint ep)
        {
            using (var imp = NtToken.Impersonate(pid, SecurityImpersonationLevel.Impersonation))
            {
                TcpListener listener = new TcpListener(ep);

                listener.Start();

                Console.WriteLine("Make a connection to {0}", ep);

                listener.AcceptTcpClient();

                Console.WriteLine("** Accepted Connection **");
            }
        }
 public static NtToken GetTokenFromClipboard()
 {
     try
     {
         return(NtToken.FromHandle(OpenClipboardToken()));
     }
     catch (SafeWin32Exception)
     {
         throw;
     }
     catch
     {
         throw new InvalidOperationException("GetClipboardAccessToken doesn't exist");
     }
 }
예제 #7
0
 private async Task <COMEnumerateInterfaces> GetSupportedInterfacesInternal(NtToken token)
 {
     try
     {
         return(await COMEnumerateInterfaces.GetInterfacesOOP(this, Database, token));
     }
     catch (Win32Exception)
     {
         throw;
     }
     catch (AggregateException agg)
     {
         throw agg.InnerException;
     }
 }
예제 #8
0
        private NtToken CreateLowBoxToken(NtToken token)
        {
            Sid package_sid = TokenUtils.GetPackageSidFromName(textBoxPackageSid.Text);

            Sid[] capabilities = GetGroupFromList(listViewCapabilities.Items.OfType <ListViewItem>());
            foreach (Sid cap in capabilities)
            {
                if (!NtSecurity.IsCapabilitySid(cap))
                {
                    throw new ArgumentException($"Invalid Capability Sid {cap}");
                }
            }

            return(token.CreateLowBoxToken(package_sid, capabilities,
                                           new NtObject[0], TokenAccessRights.MaximumAllowed));
        }
예제 #9
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;
 }
        /// <summary>
        /// Disable dynamic code policy on another process.
        /// </summary>
        public void DisableDynamicCodePolicy()
        {
            if (!NtToken.EnableDebugPrivilege())
            {
                throw new InvalidOperationException("Must have Debug privilege to disable code policy");
            }

            MitigationPolicy p = new MitigationPolicy();

            p.Policy = ProcessMitigationPolicy.ProcessDynamicCodePolicy;

            using (var buffer = p.ToBuffer())
            {
                NtSystemCalls.NtSetInformationProcess(Handle, ProcessInfoClass.ProcessMitigationPolicy, buffer, buffer.Length).ToNtException();
            }
        }
        private IEnumerable <AccessCheckResult> RunCheck(NtToken token, NtType type, ObjectTypeEntry[] object_types)
        {
            var results = new List <AccessCheckResult>();

            if (ResultList)
            {
                results.AddRange(NtSecurity.AccessCheckWithResultList(GetSecurityDescriptor(),
                                                                      token, GetDesiredAccess(), Principal, type.GenericMapping, object_types));
            }
            else
            {
                results.Add(NtSecurity.AccessCheck(GetSecurityDescriptor(),
                                                   token, GetDesiredAccess(), Principal, type.GenericMapping, object_types));
            }
            return(results);
        }
 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));
         }
     }
 }
 /// <summary>
 /// Adds details from a process, such as the process' App ID and package SID and token information.
 /// </summary>
 /// <param name="match_type">The match type.</param>
 /// <param name="process">The process.</param>
 public void AddProcess(FirewallMatchType match_type, NtProcess process)
 {
     AddFilename(match_type, process.Win32ImagePath);
     using (var token = NtToken.OpenProcessToken(process, TokenAccessRights.Query))
     {
         AddUserToken(match_type, token);
         if (token.AppContainer)
         {
             AddPackageSid(match_type, token.AppContainerSid);
         }
         else
         {
             AddPackageSid(match_type, KnownSids.Null);
         }
     }
 }
        /// <summary>
        /// Overridden process record method.
        /// </summary>
        protected override void ProcessRecord()
        {
            using (NtToken token = GetToken())
            {
                NtType type = GetNtType();
                if (type == null)
                {
                    throw new ArgumentException("Must specify a type.");
                }

                var object_types = ObjectType?.ToArray();
                // If we have multiple object types and pass result is true then
                // we don't support any another output format.
                if (object_types?.Length > 1 && PassResult)
                {
                    var result_list = NtSecurity.AccessCheckWithResultList(GetSecurityDescriptor(),
                                                                           token, AccessMask, Principal, type.GenericMapping, object_types);
                    WriteObject(result_list.Select(r => r.ToSpecificAccess(type.AccessRightsType)), true);
                    return;
                }

                var result = NtSecurity.AccessCheck(GetSecurityDescriptor(),
                                                    token, AccessMask, Principal, type.GenericMapping, object_types)
                             .ToSpecificAccess(type.AccessRightsType);
                if (PassResult)
                {
                    WriteObject(result);
                    return;
                }

                var mask = result.SpecificGrantedAccess;
                if (MapToGeneric)
                {
                    mask = result.SpecificGenericGrantedAccess;
                }

                if (ConvertToString)
                {
                    string access_string = NtSecurity.AccessMaskToString(mask, type.AccessRightsType, type.GenericMapping, false);
                    WriteObject(access_string);
                }
                else
                {
                    WriteObject(mask);
                }
            }
        }
        /// <summary>
        /// Logon user using S4U
        /// </summary>
        /// <param name="user">The username.</param>
        /// <param name="realm">The user's realm.</param>
        /// <param name="type">The type of logon token.</param>
        /// <returns>The logged on token.</returns>
        public static NtToken LogonS4U(string user, string realm, SecurityLogonType type)
        {
            LsaString pkgName = new LsaString("Negotiate");

            Win32NativeMethods.LsaConnectUntrusted(out SafeLsaHandle hlsa).ToNtException();
            using (hlsa)
            {
                uint authnPkg;
                Win32NativeMethods.LsaLookupAuthenticationPackage(hlsa, pkgName, out authnPkg).ToNtException();
                byte[] user_bytes  = Encoding.Unicode.GetBytes(user);
                byte[] realm_bytes = Encoding.Unicode.GetBytes(realm);

                using (var buffer = new SafeStructureInOutBuffer <KERB_S4U_LOGON>(user_bytes.Length + realm_bytes.Length, true))
                {
                    KERB_S4U_LOGON logon_struct = new KERB_S4U_LOGON
                    {
                        MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon
                    };
                    SafeHGlobalBuffer data_buffer = buffer.Data;

                    logon_struct.ClientUpn.Buffer = data_buffer.DangerousGetHandle();
                    data_buffer.WriteArray(0, user_bytes, 0, user_bytes.Length);
                    logon_struct.ClientUpn.Length        = (ushort)user_bytes.Length;
                    logon_struct.ClientUpn.MaximumLength = (ushort)user_bytes.Length;

                    logon_struct.ClientRealm.Buffer = data_buffer.DangerousGetHandle() + user_bytes.Length;
                    data_buffer.WriteArray((ulong)user_bytes.Length, realm_bytes, 0, realm_bytes.Length);
                    logon_struct.ClientRealm.Length        = (ushort)realm_bytes.Length;
                    logon_struct.ClientRealm.MaximumLength = (ushort)realm_bytes.Length;

                    Marshal.StructureToPtr(logon_struct, buffer.DangerousGetHandle(), false);

                    TOKEN_SOURCE tokenSource = new TOKEN_SOURCE("NtLmSsp");
                    Win32NativeMethods.AllocateLocallyUniqueId(out tokenSource.SourceIdentifier);

                    LsaString    originName   = new LsaString("S4U");
                    QUOTA_LIMITS quota_limits = new QUOTA_LIMITS();

                    Win32NativeMethods.LsaLogonUser(hlsa, originName, type, authnPkg,
                                                    buffer, buffer.Length, IntPtr.Zero,
                                                    tokenSource, out IntPtr profile, out int cbProfile, out Luid logon_id, out SafeKernelObjectHandle token_handle,
                                                    quota_limits, out NtStatus subStatus).ToNtException();
                    Win32NativeMethods.LsaFreeReturnBuffer(profile);
                    return(NtToken.FromHandle(token_handle));
                }
            }
        }
        private void btnRefreshHandles_Click(object sender, EventArgs e)
        {
            ClearList(listViewHandles);
            int current_pid = Process.GetCurrentProcess().Id;

            NtToken.EnableDebugPrivilege();
            List <ListViewItem> items = new List <ListViewItem>();

            foreach (var group in NtSystemInfo.GetHandles()
                     .Where(h => h.ProcessId != current_pid && h.ObjectType.Equals("token", StringComparison.OrdinalIgnoreCase))
                     .GroupBy(h => h.ProcessId))
            {
                using (var proc = NtProcess.Open(group.Key, ProcessAccessRights.DupHandle | ProcessAccessRights.QueryLimitedInformation, false))
                {
                    if (!proc.IsSuccess)
                    {
                        continue;
                    }

                    foreach (NtHandle handle in group)
                    {
                        using (var token_result = NtToken.DuplicateFrom(proc.Result, new IntPtr(handle.Handle),
                                                                        TokenAccessRights.Query | TokenAccessRights.QuerySource, DuplicateObjectOptions.None, false))
                        {
                            if (!token_result.IsSuccess)
                            {
                                continue;
                            }
                            NtToken      token = token_result.Result;
                            ListViewItem item  = new ListViewItem(handle.ProcessId.ToString());
                            item.SubItems.Add(proc.Result.Name);
                            item.SubItems.Add($"0x{handle.Handle:X}");
                            item.SubItems.Add(token.User.ToString());
                            item.SubItems.Add(token.IntegrityLevel.ToString());
                            item.SubItems.Add(token.Restricted.ToString());
                            item.SubItems.Add(token.AppContainer.ToString());
                            item.SubItems.Add(token.TokenType.ToString());
                            item.SubItems.Add(token.ImpersonationLevel.ToString());
                            item.Tag = token.Duplicate();
                            items.Add(item);
                        }
                    }
                }
            }
            listViewHandles.Items.AddRange(items.ToArray());
            ResizeColumns(listViewHandles);
        }
예제 #17
0
        private void btnTestS4U_Click(object sender, EventArgs e)
        {
            try
            {
                SecurityLogonType logon_type = (SecurityLogonType)comboBoxS4ULogonType.SelectedItem;

                if (radioLUNormal.Checked)
                {
                    SecureString str = new SecureString();
                    foreach (var ch in txtLUPassword.Text)
                    {
                        str.AppendChar(ch);
                    }

                    switch (logon_type)
                    {
                    case SecurityLogonType.Batch:
                    case SecurityLogonType.Interactive:
                    case SecurityLogonType.Network:
                    case SecurityLogonType.NetworkCleartext:
                    case SecurityLogonType.NewCredentials:
                    case SecurityLogonType.Service:
                        break;

                    default:
                        throw new ArgumentException("Invalid logon type for Logon");
                    }


                    using (NtToken token = Win32Security.LsaLogonUser(txtS4UUserName.Text, txtS4URealm.Text, str, logon_type, Logon32Provider.Default))
                    {
                        TokenForm.OpenForm(token, "LogonUser", true);
                    }
                }
                else
                {
                    using (NtToken token = TokenUtils.GetLogonS4UToken(txtS4UUserName.Text, txtS4URealm.Text, logon_type))
                    {
                        TokenForm.OpenForm(token, "S4U", true);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #18
0
        private NtToken GetLowBoxToken(NtToken token)
        {
            Sid package_sid = TokenUtils.GetPackageSidFromName(PackageSid);

            if (!string.IsNullOrEmpty(RestrictedPackageName))
            {
                package_sid = TokenUtils.DeriveRestrictedPackageSidFromSid(package_sid, RestrictedPackageName);
            }

            if (AppContainer)
            {
                return(TokenUtils.CreateAppContainerToken(token, package_sid, GetCapabilitySids()));
            }

            return(token.CreateLowBoxToken(package_sid, GetCapabilitySids(),
                                           Handle ?? new NtObject[0], TokenAccessRights.MaximumAllowed));
        }
 /// <summary>
 /// Get handle into the current process
 /// </summary>
 /// <returns>The handle to the object</returns>
 public NtObject GetObject()
 {
     NtToken.EnableDebugPrivilege();
     try
     {
         using (NtGeneric generic = NtGeneric.DuplicateFrom(ProcessId, new IntPtr(Handle)))
         {
             // Ensure that we get the actual type from the handle.
             NtType = generic.NtType;
             return(generic.ToTypedObject());
         }
     }
     catch
     {
     }
     return(null);
 }
        static void CheckAccess(NtToken token, NtObject obj)
        {
            if (!obj.IsAccessMaskGranted(GenericAccessRights.ReadControl))
            {
                return;
            }

            try
            {
                SecurityDescriptor sd = obj.SecurityDescriptor;
                AccessMask         granted_access;
                NtType             type = obj.NtType;

                if (_dir_rights != 0)
                {
                    granted_access = NtSecurity.GetAllowedAccess(sd, token,
                                                                 _dir_rights, type.GenericMapping);
                }
                else
                {
                    granted_access = NtSecurity.GetMaximumAccess(sd, token, type.GenericMapping);
                }

                if (!granted_access.IsEmpty)
                {
                    // As we can get all the rights for the directory get maximum
                    if (_dir_rights != 0)
                    {
                        granted_access = NtSecurity.GetMaximumAccess(sd, token, type.GenericMapping);
                    }

                    if (!_show_write_only || type.HasWritePermission(granted_access))
                    {
                        Console.WriteLine("<{0}> {1} : {2:X08} {3}", type.Name, obj.FullPath,
                                          granted_access, type.AccessMaskToString(granted_access, _map_to_generic));
                        if (_print_sddl)
                        {
                            Console.WriteLine("{0}", sd.ToSddl());
                        }
                    }
                }
            }
            catch (NtException)
            {
            }
        }
        public SelectSecurityCheckForm(bool process_security)
        {
            InitializeComponent();
            _process_security = process_security;
            _tokens           = new DisposableList <NtToken>();
            Disposed         += SelectSecurityCheckForm_Disposed;
            string username = String.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName);

            textBoxPrincipal.Text = username;
            NtToken.EnableDebugPrivilege();

            using (var ps = NtProcess.GetProcesses(ProcessAccessRights.QueryLimitedInformation, true).ToDisposableList())
            {
                foreach (var p in ps.OrderBy(p => p.ProcessId))
                {
                    var result = NtToken.OpenProcessToken(p, TokenAccessRights.MaximumAllowed, false);
                    if (result.IsSuccess)
                    {
                        NtToken token = result.Result;
                        _tokens.Add(token);
                        ListViewItem item = listViewProcesses.Items.Add(p.ProcessId.ToString());
                        item.SubItems.Add(p.Name);
                        item.SubItems.Add(p.User.Name);
                        item.SubItems.Add(token.IntegrityLevel.ToString());
                        item.Tag = token;
                    }
                }
            }
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewProcesses.ListViewItemSorter = new ListItemComparer(0);

            foreach (object value in Enum.GetValues(typeof(TokenIntegrityLevel)))
            {
                comboBoxIL.Items.Add(value);
            }
            comboBoxIL.SelectedItem = TokenIntegrityLevel.Low;
            if (process_security)
            {
                textBoxPrincipal.Enabled       = false;
                checkBoxLocalLaunch.Enabled    = false;
                checkBoxRemoteLaunch.Enabled   = false;
                checkBoxLocalActivate.Enabled  = false;
                checkBoxRemoteActivate.Enabled = false;
            }
        }
        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());
                }
            }
        }
예제 #23
0
        static void Main(string[] args)
        {
            bool show_help = false;

            int pid = Process.GetCurrentProcess().Id;

            try
            {
                OptionSet opts = new OptionSet()
                {
                    { "r", "Recursive tree directory listing",
                      v => _recursive = v != null },
                    { "sddl", "Print full SDDL security descriptors", v => _print_sddl = v != null },
                    { "p|pid=", "Specify a PID of a process to impersonate when checking", v => pid = int.Parse(v.Trim()) },
                    { "w", "Show only write permissions granted", v => _show_write_only = v != null },
                    { "k=", String.Format("Filter on a specific directory right [{0}]",
                                          String.Join(",", Enum.GetNames(typeof(DirectoryAccessRights)))), v => _dir_rights |= ParseRight(v, typeof(DirectoryAccessRights)) },
                    { "x=", "Specify a base path to exclude from recursive search", v => _walked.Add(v.ToLower()) },
                    { "t=", "Specify a type of object to include", v => _type_filter.Add(v.ToLower()) },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                };

                List <string> paths = opts.Parse(args);

                if (show_help || (paths.Count == 0))
                {
                    ShowHelp(opts);
                }
                else
                {
                    _token = NtToken.OpenProcessToken(pid);

                    foreach (string path in paths)
                    {
                        using (ObjectDirectory dir = ObjectNamespace.OpenDirectory(null, path))
                        {
                            DumpDirectory(dir);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
예제 #24
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);
        }
 private void listViewHandles_DoubleClick(object sender, EventArgs e)
 {
     if (listViewHandles.SelectedItems.Count > 0)
     {
         NtToken token = listViewHandles.SelectedItems[0].Tag as NtToken;
         if (token != null)
         {
             try
             {
                 TokenForm.OpenForm(token, true);
             }
             catch (NtException)
             {
             }
         }
     }
 }
예제 #26
0
        /// <summary>
        /// Get token for this cmdlet.
        /// </summary>
        /// <param name="desired_access">The token access required.</param>
        /// <returns>The token object.</returns>
        protected override NtToken GetToken(TokenAccessRights desired_access)
        {
            NtToken token = base.GetToken(desired_access);

            if (token == null)
            {
                if (Thread == null)
                {
                    token = NtToken.OpenProcessToken(NtProcess.Current, false, desired_access);
                }
                else
                {
                    token = NtToken.OpenProcessToken(Thread.ProcessId, false, desired_access);
                }
            }
            return(token);
        }
예제 #27
0
파일: NtHandle.cs 프로젝트: codehz/winsilo
        /// <summary>
        /// Get handle into the current process
        /// </summary>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The handle to the object</returns>
        public NtResult <NtObject> GetObject(bool throw_on_error)
        {
            NtToken.EnableDebugPrivilege();
            using (var result = NtGeneric.DuplicateFrom(ProcessId, new IntPtr(Handle), 0,
                                                        DuplicateObjectOptions.SameAccess | DuplicateObjectOptions.SameAttributes, throw_on_error)) {
                if (!result.IsSuccess)
                {
                    return(result.Cast <NtObject>());
                }

                NtGeneric generic = result.Result;

                // Ensure that we get the actual type from the handle.
                NtType = generic.NtType;
                return(generic.ToTypedObject(throw_on_error).Cast <NtObject>());
            }
        }
예제 #28
0
        /// <summary>
        /// Get list of supported Interface IIDs (that we know about)
        /// NOTE: This will load the object itself to check what is supported, it _might_ crash the app
        /// The returned array is cached so subsequent calls to this function return without calling into COM
        /// </summary>
        /// <param name="refresh">Force the supported interface list to refresh</param>
        /// <param name="token">Token to use when checking for the interfaces.</param>
        /// <returns>Returns true if supported interfaces were refreshed.</returns>
        /// <exception cref="Win32Exception">Thrown on error.</exception>
        public async Task <bool> LoadSupportedInterfacesAsync(bool refresh, NtToken token)
        {
            if (Clsid == Guid.Empty)
            {
                return(false);
            }

            if (refresh || !InterfacesLoaded)
            {
                COMEnumerateInterfaces enum_int = await GetSupportedInterfacesInternal(token);

                m_interfaces         = new List <COMInterfaceInstance>(enum_int.Interfaces);
                m_factory_interfaces = new List <COMInterfaceInstance>(enum_int.FactoryInterfaces);
                InterfacesLoaded     = true;
                return(true);
            }
            return(false);
        }
        private NtToken GetLogonToken(TokenAccessRights desired_access)
        {
            IEnumerable <UserGroup> groups = null;

            if (AdditionalGroups != null && AdditionalGroups.Length > 0)
            {
                groups = AdditionalGroups.Select(s => new UserGroup(s,
                                                                    GroupAttributes.Enabled | GroupAttributes.EnabledByDefault | GroupAttributes.Mandatory));
            }
            using (NtToken token = TokenUtils.GetLogonUserToken(User, Domain, Password, LogonType, groups))
            {
                if (desired_access == TokenAccessRights.MaximumAllowed)
                {
                    return(token.Duplicate());
                }
                return(token.Duplicate(desired_access));
            }
        }
 private void AddProcessNode(NtProcess entry)
 {
     try
     {
         using (NtToken token = entry.OpenToken())
         {
             TreeNode node = new TreeNode(String.Format("Pid: {0} - Name: {1} (User:{2}, IL: {3}, R: {4}, AC: {5})",
                                                        entry.ProcessId, entry.Name, token.User, token.IntegrityLevel,
                                                        token.Restricted, token.AppContainer));
             node.Tag = entry.Duplicate();
             treeViewProcesses.Nodes.Add(node);
         }
     }
     catch
     {
         // Do nothing
     }
 }
예제 #31
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));
         }
     }
 }
        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();
            }
        }
        public static void OpenForm(NtToken token, bool copy)
        {
            if (token != null)
            {
                TokenForm form = new TokenForm(copy ? token.Duplicate() : token);

                _forms.Add(form);
                form.FormClosed += form_FormClosed;

                form.Show(_main_form);
            }
        }
        public static NtToken GetTokenFromSaferLevel(NtToken token, SaferLevel level, bool make_inert)
        {
            IntPtr level_handle;

            if (!SaferCreateLevel(SaferScope.User, level, SAFER_LEVEL_OPEN, out level_handle, IntPtr.Zero))
            {
                throw new SafeWin32Exception();
            }

            try
            {
                using (NtToken duptoken = token.Duplicate(TokenAccessRights.GenericRead | TokenAccessRights.GenericExecute))
                {
                    SafeKernelObjectHandle handle;
                    if (SaferComputeTokenFromLevel(level_handle, duptoken.Handle, out handle, make_inert ? SaferFlags.MakeInert : 0, IntPtr.Zero))
                    {
                        return NtToken.FromHandle(handle);
                    }
                    else
                    {
                        throw new SafeWin32Exception();
                    }
                }
            }
            finally
            {
                SaferCloseLevel(level_handle);
            }
        }
 private void btnCreate_Click(object sender, EventArgs e)
 {
     try
     {
         _newtoken = CreateRestrictedToken();
         DialogResult = DialogResult.OK;
         Close();
     }
     catch (Win32Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        public TokenForm(NtToken token)
        {
            InitializeComponent();
            this.Disposed += TokenForm_Disposed;
            _token = token;

            foreach (object v in Enum.GetValues(typeof(TokenIntegrityLevel)))
            {
                comboBoxIL.Items.Add(v);
                comboBoxILForDup.Items.Add(v);
            }

            UpdateTokenData();
            comboBoxImpLevel.Items.Add(SecurityImpersonationLevel.Anonymous);
            comboBoxImpLevel.Items.Add(SecurityImpersonationLevel.Identification);
            comboBoxImpLevel.Items.Add(SecurityImpersonationLevel.Impersonation);
            comboBoxImpLevel.Items.Add(SecurityImpersonationLevel.Delegation);
            comboBoxImpLevel.SelectedItem = SecurityImpersonationLevel.Impersonation;

            comboBoxTokenType.Items.Add(TokenType.Primary);
            comboBoxTokenType.Items.Add(TokenType.Impersonation);
            comboBoxTokenType.SelectedItem = TokenType.Impersonation;

            foreach (object v in Enum.GetValues(typeof(SaferLevel)))
            {
                comboBoxSaferLevel.Items.Add(v);
            }

            comboBoxSaferLevel.SelectedItem = SaferLevel.NormalUser;
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="base_object">Base object for security descriptor</param>
        /// <param name="token">Token for determining user rights</param>
        /// <param name="is_directory">True if a directory security descriptor</param>
        public SecurityDescriptor(NtObject base_object, NtToken token, bool is_directory) : this()
        {
            if ((base_object == null) && (token == null))
            {
                throw new ArgumentNullException();
            }

            SecurityDescriptor parent_sd = null;
            if (base_object != null)
            {
                parent_sd = base_object.SecurityDescriptor;
            }

            SecurityDescriptor creator_sd = null;
            if (token != null)
            {
                creator_sd = new SecurityDescriptor();
                creator_sd.Owner = new SecurityDescriptorSid(token.Owner, false);
                creator_sd.Group = new SecurityDescriptorSid(token.PrimaryGroup, false);
                creator_sd.Dacl = token.DefaultDalc;
            }

            NtType type = NtType.GetTypeByName(base_object.NtTypeName);

            SafeBuffer parent_sd_buffer = SafeHGlobalBuffer.Null;
            SafeBuffer creator_sd_buffer = SafeHGlobalBuffer.Null;
            SafeSecurityObjectHandle security_obj = null;
            try
            {
                if (parent_sd != null)
                {
                    parent_sd_buffer = parent_sd.ToSafeBuffer();
                }
                if (creator_sd != null)
                {
                    creator_sd_buffer = creator_sd.ToSafeBuffer();
                }

                GenericMapping mapping = type.GenericMapping;
                NtRtl.RtlNewSecurityObject(parent_sd_buffer, creator_sd_buffer, out security_obj, is_directory,
                    token != null ? token.Handle : SafeKernelObjectHandle.Null, ref mapping).ToNtException();
                ParseSecurityDescriptor(security_obj);
            }
            finally
            {
                if (parent_sd_buffer != null)
                {
                    parent_sd_buffer.Close();
                }
                if (creator_sd_buffer != null)
                {
                    creator_sd_buffer.Close();
                }
                if (security_obj != null)
                {
                    security_obj.Close();
                }
            }
        }
        static void Main(string[] args)
        {
            bool show_help = false;

            int pid = Process.GetCurrentProcess().Id;

            try
            {
                OptionSet opts = new OptionSet() {
                            { "r", "Recursive tree directory listing",  
                                v => _recursive = v != null },                                  
                            { "sddl", "Print full SDDL security descriptors", v => _print_sddl = v != null },
                            { "p|pid=", "Specify a PID of a process to impersonate when checking", v => pid = int.Parse(v.Trim()) },
                            { "w", "Show only write permissions granted", v => _show_write_only = v != null },
                            { "f=", String.Format("Filter on a file right [{0}]", 
                                String.Join(",", Enum.GetNames(typeof(FileAccessRights)))), v => _file_filter |= ParseRight(v, typeof(FileAccessRights)) },  
                            { "d=", String.Format("Filter on a directory right [{0}]", 
                                String.Join(",", Enum.GetNames(typeof(FileDirectoryAccessRights)))), v => _dir_filter |= ParseRight(v, typeof(FileDirectoryAccessRights)) },
                            { "x=", "Specify a base path to exclude from recursive search", v => _walked.Add(v) },
                            { "q", "Don't print errors", v => _quiet = v != null },
                            { "onlydirs", "Only check the permissions of directories", v => _only_dirs = v != null },
                            { "h|help",  "show this message and exit", v => show_help = v != null },
                        };

                List<string> paths = opts.Parse(args);

                if (show_help || (paths.Count == 0))
                {
                    ShowHelp(opts);
                }
                else
                {
                    _type = NtType.GetTypeByName("file");
                    _token = NtToken.OpenProcessToken(pid);

                    foreach (string path in paths)
                    {
                        if ((File.GetAttributes(path) & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory)
                        {
                            DumpDirectory(new DirectoryInfo(path));
                        }
                        else
                        {
                            DumpFile(new FileInfo(path));
                        }
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
 /// <summary>
 /// Constructor from a token default DACL and ownership values.
 /// </summary>
 /// <param name="token">The token to use for its default DACL</param>
 public SecurityDescriptor(NtToken token) : this()
 {
     Owner = new SecurityDescriptorSid(token.Owner, true);
     Group = new SecurityDescriptorSid(token.PrimaryGroup, true);
     Dacl = token.DefaultDalc;
     if (token.IntegrityLevel< TokenIntegrityLevel.Medium)
     {
         Sacl = new Acl();
         Sacl.Add(new Ace(AceType.MandatoryLabel, AceFlags.None, 1, token.IntegrityLevelSid.Sid));
     }
 }
        public static Win32Process CreateProcessAsUser(NtToken token, string application_name, string command_line, CreateProcessFlags flags, string desktop)
        {
            STARTUPINFOEX start_info = new STARTUPINFOEX();
            start_info.StartupInfo.lpDesktop = desktop;
            PROCESS_INFORMATION proc_info = new PROCESS_INFORMATION();

            if (!CreateProcessAsUser(token.Handle, application_name, command_line, 
                IntPtr.Zero, IntPtr.Zero, false, flags, IntPtr.Zero, null, ref start_info, out proc_info))
            {
                if (!CreateProcessWithTokenW(token.Handle, 0, application_name, command_line, 
                    flags, IntPtr.Zero, null, ref start_info, out proc_info))
                {
                    throw new SafeWin32Exception();
                }
            }

            return new Win32Process(proc_info);
        }
        static void Main(string[] args)
        {
            bool show_help = false;

            int pid = Process.GetCurrentProcess().Id;
            try
            {
                OptionSet opts = new OptionSet() {
                            { "r", "Recursive tree directory listing",  
                                v => _recursive = v != null },                                  
                            { "sddl", "Print full SDDL security descriptors", v => _print_sddl = v != null },
                            { "p|pid=", "Specify a PID of a process to impersonate when checking", v => pid = int.Parse(v.Trim()) },
                            { "w", "Show only write permissions granted", v => _show_write_only = v != null },
                            { "k=", String.Format("Filter on a specific directory right [{0}]", 
                                String.Join(",", Enum.GetNames(typeof(DirectoryAccessRights)))), v => _dir_rights |= ParseRight(v, typeof(DirectoryAccessRights)) },  
                            { "x=", "Specify a base path to exclude from recursive search", v => _walked.Add(v.ToLower()) },
                            { "t=", "Specify a type of object to include", v => _type_filter.Add(v.ToLower()) },
                            { "h|help",  "show this message and exit", v => show_help = v != null },
                        };

                List<string> paths = opts.Parse(args);

                if (show_help || (paths.Count == 0))
                {
                    ShowHelp(opts);
                }
                else
                {
                    _token = NtToken.OpenProcessToken(pid);

                    foreach (string path in paths)
                    {
                        using (ObjectDirectory dir = ObjectNamespace.OpenDirectory(null, path))
                        {
                            DumpDirectory(dir);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }