예제 #1
0
        /// <summary>
        /// Finds ALPC endpoints which allows for the server binding. This brute forces all ALPC ports to try and find
        /// something which will accept the bind.
        /// </summary>
        /// <remarks>This could hang if the ALPC port is owned by a suspended process.</remarks>
        /// <param name="interface_id">Interface UUID to lookup.</param>
        /// <param name="interface_version">Interface version lookup.</param>
        /// <returns>A list of RPC endpoints which can bind the interface.</returns>
        /// <exception cref="NtException">Throws on error.</exception>
        public static IEnumerable <RpcEndpoint> FindAlpcEndpointForInterface(Guid interface_id, Version interface_version)
        {
            using (var dir = NtDirectory.Open(@"\RPC Control"))
            {
                var nt_type = NtType.GetTypeByType <NtAlpc>().Name;

                foreach (var port in dir.Query().Where(e => e.NtTypeName == nt_type))
                {
                    bool success = false;
                    try
                    {
                        using (var server = new RpcClient(interface_id, interface_version))
                        {
                            server.Connect(port.Name);
                            success = true;
                        }
                    }
                    catch
                    {
                    }
                    if (success)
                    {
                        yield return(new RpcEndpoint(interface_id, interface_version,
                                                     SafeRpcBindingHandle.Compose(null, "ncalrpc", null, port.Name, null), false));
                    }
                }
            }
        }
예제 #2
0
        private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            NtType winsta_type = NtType.GetTypeByType <NtWindowStation>();

            AccessMask winsta_access_rights = winsta_type.GenericMapping.MapMask(AccessRights);
            bool       check_winsta         = CheckMode == WindowStationCheckMode.WindowStationOnly || CheckMode == WindowStationCheckMode.WindowStationAndDesktop;
            bool       check_desktop        = CheckMode == WindowStationCheckMode.DesktopOnly || CheckMode == WindowStationCheckMode.WindowStationAndDesktop;

            using (var winstas = NtWindowStation.GetAccessibleWindowStations().ToDisposableList())
            {
                foreach (var winsta in winstas)
                {
                    if (check_winsta && winsta.IsAccessGranted(WindowStationAccessRights.ReadControl))
                    {
                        var sd = winsta.SecurityDescriptor;
                        foreach (TokenEntry token in tokens)
                        {
                            AccessMask granted_access = NtSecurity.GetMaximumAccess(sd,
                                                                                    token.Token, winsta_type.GenericMapping);
                            if (IsAccessGranted(granted_access, winsta_access_rights))
                            {
                                WriteAccessCheckResult(winsta.FullPath, winsta_type.Name, granted_access, winsta_type.GenericMapping,
                                                       sd, winsta_type.AccessRightsType, true, token.Information);
                            }
                        }
                    }

                    if (check_desktop && winsta.IsAccessGranted(WindowStationAccessRights.EnumDesktops))
                    {
                        RunAccessCheckDesktop(tokens, winsta);
                    }
                }
            }
        }
        private static string FormatText(NtHandle ent)
        {
            string size = string.Empty;

            try
            {
                using (NtSection section = NtSection.DuplicateFrom(ent.ProcessId, new IntPtr(ent.Handle), SectionAccessRights.Query))
                {
                    size = section.Size.ToString();
                }
            }
            catch (NtException)
            {
                size = "Unknown";
            }

            StringBuilder builder      = new StringBuilder();
            NtType        section_type = NtType.GetTypeByType <NtSection>();

            if (section_type.HasReadPermission(ent.GrantedAccess))
            {
                builder.Append("R");
            }

            if (section_type.HasWritePermission(ent.GrantedAccess))
            {
                builder.Append("W");
            }

            return($"[{ent.Handle}/0x{ent.Handle:X}] {ent.Name} Size: {size} Access: {builder}");
        }
        /// <summary>
        /// Get the NT type for a SE Object Type.
        /// </summary>
        /// <param name="type">The type of the resource.</param>
        /// <returns>The NT type if known, otherwise null.</returns>
        public static NtType GetNativeType(SeObjectType type)
        {
            switch (type)
            {
            case SeObjectType.File:
            case SeObjectType.LMShare:
                return(NtType.GetTypeByType <NtFile>());

            case SeObjectType.RegistryKey:
            case SeObjectType.RegistryWow6432Key:
            case SeObjectType.RegistryWow6464Key:
                return(NtType.GetTypeByType <NtKey>());

            case SeObjectType.Service:
                return(NtType.GetTypeByName(ServiceUtils.SERVICE_NT_TYPE_NAME));

            case SeObjectType.WmiGuid:
                return(NtType.GetTypeByType <NtEtwRegistration>());

            case SeObjectType.Ds:
            case SeObjectType.DsAll:
                return(NtType.GetTypeByName(DirectoryServiceUtils.DS_NT_TYPE_NAME));
            }
            return(null);
        }
예제 #5
0
        private void RunAccessCheckDesktop(IEnumerable <TokenEntry> tokens, NtWindowStation winsta)
        {
            NtType     desktop_type          = NtType.GetTypeByType <NtDesktop>();
            AccessMask desktop_access_rights = desktop_type.GenericMapping.MapMask(DesktopAccessRights);

            using (var desktops = winsta.GetAccessibleDesktops().ToDisposableList())
            {
                foreach (var desktop in desktops)
                {
                    if (desktop.IsAccessGranted(DesktopAccessRights.ReadControl))
                    {
                        var sd = desktop.SecurityDescriptor;
                        foreach (TokenEntry token in tokens)
                        {
                            AccessMask granted_access = NtSecurity.GetMaximumAccess(sd,
                                                                                    token.Token, desktop_type.GenericMapping);
                            if (IsAccessGranted(granted_access, desktop_access_rights))
                            {
                                WriteAccessCheckResult($"{winsta.FullPath}{desktop.FullPath}", desktop_type.Name, granted_access, desktop_type.GenericMapping,
                                                       sd, desktop_type.AccessRightsType, true, token.Information);
                            }
                        }
                    }
                }
            }
        }
예제 #6
0
        private void ShowProcessSecurity(ProcessTokenEntry process)
        {
            var viewer = new SecurityDescriptorViewerForm($"{process.Name}:{process.ProcessId}",
                                                          process.ProcessSecurity, NtType.GetTypeByType <NtProcess>(), false);

            viewer.ShowDialog(this);
        }
예제 #7
0
 private static Tuple <NtType, bool> GetTypeFromSecurity(ObjectSecurity object_security)
 {
     if (object_security is GenericObjectSecurity sd)
     {
         return(Tuple.Create(sd.NtType, sd.IsDirectory));
     }
     else if (object_security is FileSecurity)
     {
         return(Tuple.Create(NtType.GetTypeByType <NtFile>(), false));
     }
     else if (object_security is DirectorySecurity)
     {
         return(Tuple.Create(NtType.GetTypeByType <NtFile>(), true));
     }
     else if (object_security is DirectoryObjectSecurity)
     {
         return(Tuple.Create(DirectoryServiceUtils.NtType, true));
     }
     else if (object_security is RegistrySecurity)
     {
         return(Tuple.Create(NtType.GetTypeByType <NtKey>(), true));
     }
     else if (object_security is MutexSecurity)
     {
         return(Tuple.Create(NtType.GetTypeByType <NtMutant>(), false));
     }
     else if (object_security is SemaphoreSecurity)
     {
         return(Tuple.Create(NtType.GetTypeByType <NtSemaphore>(), false));
     }
     return(Tuple.Create((NtType)null, false));
 }
예제 #8
0
        private protected override void RunAccessCheckPath(IEnumerable <TokenEntry> tokens, string path)
        {
            FileOpenOptions options = _open_for_backup ? FileOpenOptions.OpenForBackupIntent : FileOpenOptions.None;

            if (!FollowLink)
            {
                options |= FileOpenOptions.OpenReparsePoint;
            }
            NtType     type              = NtType.GetTypeByType <NtFile>();
            AccessMask access_rights     = type.MapGenericRights(Access);
            AccessMask dir_access_rights = type.MapGenericRights(DirectoryAccess);

            using (var result = OpenFile(path, null, options))
            {
                NtFile file = result.GetResultOrThrow();
                if (FollowPath(file, GetFilePath))
                {
                    DumpFile(tokens,
                             access_rights,
                             dir_access_rights,
                             null,
                             result.Result);
                    if (IsDirectoryNoThrow(result.Result))
                    {
                        DumpDirectory(tokens, access_rights, dir_access_rights, file, options, GetMaxDepth());
                    }
                }
            }
        }
 /// <summary>
 /// Query the security descriptor for a device.
 /// </summary>
 /// <param name="installer_class">The installer device class.</param>
 /// <param name="throw_on_error">True to throw on error.</param>
 /// <returns>The security descriptor.</returns>
 public static NtResult <SecurityDescriptor> GetDeviceSecurityDescriptor(Guid installer_class, bool throw_on_error)
 {
     using (var buffer = GetDeviceRegistryPropertyBuffer(installer_class, CmDeviceProperty.SECURITY, throw_on_error))
     {
         return(buffer.Map(b => new SecurityDescriptor(b.ToArray(), NtType.GetTypeByType <NtFile>())));
     }
 }
        /// <summary>
        /// Query security of an event.
        /// </summary>
        /// <param name="guid">The event GUID to query.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The event security descriptor.</returns>
        public static NtResult <SecurityDescriptor> QueryTraceSecurity(Guid guid, bool throw_on_error)
        {
            int        length = 0;
            Win32Error error  = Win32NativeMethods.EventAccessQuery(ref guid, SafeHGlobalBuffer.Null, ref length);

            if (error == Win32Error.ERROR_FILE_NOT_FOUND && guid != TraceKnownGuids.DefaultTraceSecurity)
            {
                return(QueryTraceSecurity(TraceKnownGuids.DefaultTraceSecurity, throw_on_error));
            }

            if (error != Win32Error.ERROR_MORE_DATA)
            {
                return(error.CreateResultFromDosError <SecurityDescriptor>(throw_on_error));
            }

            using (var buffer = new SafeHGlobalBuffer(length))
            {
                error = Win32NativeMethods.EventAccessQuery(ref guid, buffer, ref length);
                if (error != Win32Error.SUCCESS)
                {
                    return(error.CreateResultFromDosError <SecurityDescriptor>(throw_on_error));
                }
                return(SecurityDescriptor.Parse(buffer, NtType.GetTypeByType <NtEtwRegistration>(), throw_on_error));
            }
        }
        private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            if (!NtToken.EnableDebugPrivilege())
            {
                WriteWarning("Current process doesn't have SeDebugPrivilege, results may be inaccurate");
            }

            NtType     type               = NtType.GetTypeByType <NtToken>();
            AccessMask access_rights      = type.MapGenericRights(AccessRights);
            int        current_session_id = NtProcess.Current.SessionId;

            using (var procs = NtProcess.GetProcesses(ProcessAccessRights.QueryInformation | ProcessAccessRights.ReadControl, false).ToDisposableList())
            {
                IEnumerable <NtProcess> proc_enum = procs;
                if (CurrentSession)
                {
                    proc_enum = proc_enum.Where(p => CheckSession(p, current_session_id));
                }
                foreach (var proc in proc_enum.Where(p => ShowDeadProcesses || !p.IsDeleting))
                {
                    using (var result = NtToken.OpenProcessToken(proc, TokenAccessRights.ReadControl | TokenAccessRights.Query, false))
                    {
                        if (!result.IsSuccess)
                        {
                            WriteWarning($"Couldn't open token for Process {proc.Name} PID: {proc.ProcessId} Status: {result.Status}");
                            continue;
                        }

                        NtToken primary_token = result.Result;
                        var     sd_result     = primary_token.GetSecurityDescriptor(SecurityInformation.AllBasic, false);
                        if (!sd_result.IsSuccess)
                        {
                            WriteWarning($"Couldn't get token's Security Descriptor for Process {proc.Name} PID: {proc.ProcessId} Status: {sd_result.Status}");
                            continue;
                        }

                        var    sd              = sd_result.Result;
                        string process_name    = proc.Name;
                        string process_cmdline = proc.CommandLine;
                        string image_path      = proc.FullPath;
                        int    process_id      = proc.ProcessId;

                        foreach (var token in tokens)
                        {
                            if (proc.GetMaximumAccess(token.Token).HasFlag(ProcessAccessRights.QueryLimitedInformation))
                            {
                                AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping);
                                if (IsAccessGranted(granted_access, access_rights))
                                {
                                    WriteObject(new TokenAccessCheckResult(primary_token, proc,
                                                                           granted_access, sd, token.Information));
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #12
0
        /// <summary>
        /// Overridden ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (MapType && Type == null)
            {
                WriteWarning("Must specify Type for MapType to work correctly.");
            }

            SecurityDescriptor sd;

            switch (ParameterSetName)
            {
            case "FromToken":
            {
                Type = Type ?? Parent?.NtType ?? Creator?.NtType;
                if (Type == null)
                {
                    WriteWarning("Security descriptor type not specified, defaulting to File.");
                    Type = NtType.GetTypeByType <NtFile>();
                }
                sd = SecurityDescriptor.Create(Parent, Creator, IsDirectory, AutoInherit, Token, Type.GenericMapping);
            }
            break;

            case "FromSddl":
                sd = new SecurityDescriptor(Sddl);
                break;

            case "FromBytes":
                sd = new SecurityDescriptor(Bytes);
                break;

            case "FromKey":
                sd = new SecurityDescriptor(Key.QueryValue(ValueName).Data);
                break;

            case "FromKeyValue":
                sd = new SecurityDescriptor(KeyValue.Data);
                break;

            default:
                sd = new SecurityDescriptor
                {
                    Dacl = new Acl()
                };
                sd.Dacl.NullAcl = NullDacl;
                break;
            }

            sd.NtType = Type;
            if (MapType)
            {
                sd.MapGenericAccess();
            }

            UpdateSecurityDescriptorControl(sd, Control);
            WriteObject(sd);
        }
예제 #13
0
 internal SecurityDescriptor GetSecurityDescriptor()
 {
     if (Type != DEVPROPTYPE.SECURITY_DESCRIPTOR)
     {
         return(null);
     }
     return(SecurityDescriptor.Parse(Data, NtType.GetTypeByType <NtFile>(),
                                     false).GetResultOrDefault());
 }
        private ServiceAccessRights GetTriggerAccess(Win32Service service, NtToken token)
        {
            if (IgnoreTrigger)
            {
                return(0);
            }

            ServiceAccessRights granted_access = 0;
            NtType type = NtType.GetTypeByType <NtEtwRegistration>();

            foreach (var trigger in service.Triggers)
            {
                bool accessible = false;
                if (trigger.TriggerType == ServiceTriggerType.NetworkEndpoint)
                {
                    accessible = true;
                }
                else if (trigger is EtwServiceTriggerInformation etw_trigger)
                {
                    if (etw_trigger.SecurityDescriptor == null)
                    {
                        WriteWarning($"Can't access ETW Security Descriptor for service {service.Name}. Running as Administrator might help.");
                    }
                    else
                    {
                        accessible = CheckForAccess(etw_trigger.SecurityDescriptor, token,
                                                    TraceAccessRights.GuidEnable, type.GenericMapping);
                    }
                }
                else if (trigger is WnfServiceTriggerInformation wnf_trigger)
                {
                    if (wnf_trigger.Name?.SecurityDescriptor == null)
                    {
                        WriteWarning($"Can't access WNF Security Descriptor for service {service.Name}");
                    }
                    else
                    {
                        accessible = CheckForAccess(wnf_trigger.Name.SecurityDescriptor, token,
                                                    WnfAccessRights.WriteData, NtWnf.GenericMapping);
                    }
                }

                if (accessible)
                {
                    if (trigger.Action == ServiceTriggerAction.Start)
                    {
                        granted_access |= ServiceAccessRights.Start;
                    }
                    else
                    {
                        granted_access |= ServiceAccessRights.Stop;
                    }
                }
            }

            return(granted_access);
        }
예제 #15
0
        static Form GetFormFromArgs(string[] args)
        {
            try
            {
                int    pid       = -1;
                int    handle    = -1;
                string text      = string.Empty;
                bool   show_help = false;

                OptionSet opts = new OptionSet()
                {
                    { "p|pid=", "Specify a process ID to view the token.",
                      v => pid = int.Parse(v) },
                    { "handle=", "Specify an inherited handle to view.",
                      v => handle = int.Parse(v) },
                    { "text=", "Specify a text string for the token window.",
                      v => text = v },
                    { "h|help", "Show this message and exit",
                      v => show_help = v != null },
                };

                opts.Parse(args);

                if (show_help || (handle <= 0 && pid <= 0))
                {
                    ShowHelp(opts);
                }
                else if (handle > 0)
                {
                    using (NtToken token = NtToken.FromHandle(new SafeKernelObjectHandle(new IntPtr(handle), true)))
                    {
                        if (token.NtType != NtType.GetTypeByType <NtToken>())
                        {
                            throw new ArgumentException("Passed handle is not a token");
                        }

                        return(new TokenForm(token.Duplicate(), text));
                    }
                }
                else if (pid > 0)
                {
                    using (NtProcess process = NtProcess.Open(pid, ProcessAccessRights.QueryLimitedInformation))
                    {
                        return(new TokenForm(process.OpenToken(),
                                             $"{process.Name}:{pid}"));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

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

            int  pid             = Process.GetCurrentProcess().Id;
            int  recursive_depth = 1;
            bool no_files        = false;

            try
            {
                PrintDeprecationWarning();
                OptionSet opts = new OptionSet()
                {
                    { "r", "Recursive tree directory listing",
                      v => recursive_depth = v != null ? int.MaxValue : 1 },
                    { "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(ConvertPath(v)) },
                    { "q", "Don't print errors", v => _quiet = v != null },
                    { "g", "Map access mask to generic rights.", v => _map_to_generic = v != null },
                    { "nofiles", "Don't show permission of files.", v => no_files = v != null },
                    { "depth", "Specify a recursive depth", v => recursive_depth = int.Parse(v) },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                };

                List <string> paths = opts.Parse(args).Select(p => ConvertPath(p)).ToList();

                if (show_help || (paths.Count == 0))
                {
                    ShowHelp(opts);
                }
                else
                {
                    _type  = NtType.GetTypeByType <NtFile>();
                    _token = NtToken.OpenProcessToken(pid);

                    foreach (string path in paths)
                    {
                        DumpFile(path, null, recursive_depth, no_files);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            NtType     type          = NtType.GetTypeByType <NtFile>();
            AccessMask access_rights = type.MapGenericRights(AccessRights);

            using (var result = OpenFile("",
                                         FileAccessRights.ReadData, false))
            {
                NtFile file = result.GetResultOrThrow();
                foreach (var entry in result.Result.QueryDirectoryInfo())
                {
                    DumpFile(tokens, access_rights, entry.FileName);
                }
            }
        }
예제 #18
0
        private static IEnumerable <RpcAlpcServer> GetAlpcServersInternal(IEnumerable <NtHandle> handles)
        {
            NtType alpc_type = NtType.GetTypeByType <NtAlpc>();

            foreach (var handle in handles.Where(h => h.NtType == alpc_type &&
                                                 h.Name.StartsWith(@"\RPC Control\", StringComparison.OrdinalIgnoreCase)))
            {
                List <RpcEndpoint> endpoints = new List <RpcEndpoint>();
                try {
                    endpoints.AddRange(RpcEndpointMapper.QueryEndpointsForAlpcPort(handle.Name));
                } catch (SafeWin32Exception) {
                }

                if (endpoints.Count > 0)
                {
                    yield return(new RpcAlpcServer(handle, endpoints));
                }
            }
        }
        private static NtType GetTypeObject(SpecificAccessType type)
        {
            switch (type)
            {
            case SpecificAccessType.Transaction:
                return(NtType.GetTypeByType <NtTransaction>());

            case SpecificAccessType.TransactionManager:
                return(NtType.GetTypeByType <NtTransactionManager>());

            case SpecificAccessType.ResourceManager:
                return(NtType.GetTypeByType <NtResourceManager>());

            case SpecificAccessType.Enlistment:
                return(NtType.GetTypeByType <NtEnlistment>());

            case SpecificAccessType.ALPCPort:
                return(NtType.GetTypeByType <NtAlpc>());
            }

            return(NtType.GetTypeByName(type.ToString(), false));
        }
        private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            NtType     type          = NtType.GetTypeByType <NtEtwRegistration>();
            AccessMask access_rights = type.GenericMapping.MapMask(Access);
            var        providers     = EventTracing.GetProviders();

            if (ProviderId != null && ProviderId.Length > 0)
            {
                HashSet <Guid> guids = new HashSet <Guid>(ProviderId);
                providers = providers.Where(p => guids.Contains(p.Id));
            }
            else if (Name != null && Name.Length > 0)
            {
                var names = new HashSet <string>(Name, StringComparer.OrdinalIgnoreCase);
                providers = providers.Where(p => names.Contains(p.Name));
            }

            foreach (var provider in providers)
            {
                var sd = provider.SecurityDescriptor;
                if (sd == null)
                {
                    WriteWarning($"Couldn't query security for ETW Provider {provider.Name}. Perhaps run as administrator.");
                    continue;
                }

                foreach (TokenEntry token in tokens)
                {
                    AccessMask granted_access = NtSecurity.GetMaximumAccess(sd,
                                                                            token.Token, type.GenericMapping);
                    if (IsAccessGranted(granted_access, access_rights))
                    {
                        WriteObject(new EventTraceAccessCheckResult(provider, type,
                                                                    granted_access, sd, token.Information));
                    }
                }
            }
        }
        /// <summary>
        /// Get the NT type for a SE Object Type.
        /// </summary>
        /// <param name="type">The type of the resource.</param>
        /// <returns>The NT type if known, otherwise null.</returns>
        public static NtType GetNativeType(SeObjectType type)
        {
            switch (type)
            {
            case SeObjectType.File:
                return(NtType.GetTypeByType <NtFile>());

            case SeObjectType.RegistryKey:
            case SeObjectType.RegistryWow6432Key:
            case SeObjectType.RegistryWow6464Key:
                return(NtType.GetTypeByType <NtKey>());

            case SeObjectType.Service:
                return(ServiceUtils.GetServiceNtType("Service"));

            case SeObjectType.WmiGuid:
                return(NtType.GetTypeByType <NtEtwRegistration>());

            case SeObjectType.Ds:
            case SeObjectType.DsAll:
                return(DirectoryServiceUtils.NtType);
            }
            return(null);
        }
        /// <summary>
        /// Process Record.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (!_dict.GetValue("Access", out Enum access))
            {
                if (!RawAccess.HasValue && RequiresAccess(Type))
                {
                    throw new ArgumentException("Invalid access value.");
                }
                else
                {
                    access = GenericAccessRights.None;
                }
            }

            _dict.GetValue("Condition", out string condition);
            _dict.GetValue("ObjectType", out Guid? object_type);
            _dict.GetValue("InheritedObjectType", out Guid? inherited_object_type);
            _dict.GetValue("ServerSid", out Sid server_sid);
            _dict.GetValue("SecurityAttribute", out ClaimSecurityAttribute security_attribute);

            Acl acl;

            if (NtSecurity.IsSystemAceType(Type))
            {
                if (SecurityDescriptor.Sacl == null)
                {
                    SecurityDescriptor.Sacl = new Acl();
                }
                acl = SecurityDescriptor.Sacl;
            }
            else
            {
                if (SecurityDescriptor.Dacl == null)
                {
                    SecurityDescriptor.Dacl = new Acl();
                }
                acl = SecurityDescriptor.Dacl;
            }

            AccessMask mask = access;

            if (RawAccess.HasValue)
            {
                mask |= RawAccess.Value;
            }

            if (MapGeneric)
            {
                NtType type = SecurityDescriptor.NtType;
                if (type == null)
                {
                    WriteWarning("No NtType specified in security descriptor. Defaulting to File.");
                    type = NtType.GetTypeByType <NtFile>();
                }
                mask = type.MapGenericRights(mask);
            }

            Ace ace = new Ace(Type, Flags, mask, GetSid());

            if ((NtSecurity.IsCallbackAceType(Type) || Type == AceType.AccessFilter) && !string.IsNullOrWhiteSpace(condition))
            {
                ace.Condition = condition;
            }
            if (NtSecurity.IsObjectAceType(Type))
            {
                ace.ObjectType          = object_type;
                ace.InheritedObjectType = inherited_object_type;
            }
            if (Type == AceType.AllowedCompound)
            {
                ace.ServerSid = server_sid;
            }
            if (Type == AceType.ResourceAttribute)
            {
                ace.ResourceAttribute = security_attribute;
            }

            acl.Add(ace);
            if (PassThru)
            {
                WriteObject(ace);
            }
        }
        /// <summary>
        /// Overridden ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (MapGeneric && Type == null)
            {
                WriteWarning("Must specify Type for MapGeneric to work correctly.");
            }

            SecurityDescriptor sd;

            switch (ParameterSetName)
            {
            case "FromToken":
            {
                Type = Type ?? Parent?.NtType ?? Creator?.NtType;
                if (Type == null)
                {
                    WriteWarning("Security descriptor type not specified, defaulting to File.");
                    Type = NtType.GetTypeByType <NtFile>();
                }

                using (var list = new DisposableList())
                {
                    if (EffectiveToken)
                    {
                        Token = list.AddResource(NtToken.OpenEffectiveToken());
                    }
                    sd = SecurityDescriptor.Create(Parent, Creator, ObjectType,
                                                   Container, AutoInherit, Token, Type.GenericMapping);
                }
            }
            break;

            case "FromSddl":
                sd = new SecurityDescriptor(Sddl);
                break;

            case "FromBytes":
                sd = new SecurityDescriptor(Byte);
                break;

            case "FromKey":
                sd = new SecurityDescriptor(Key.QueryValue(ValueName).Data);
                break;

            case "FromKeyValue":
                sd = new SecurityDescriptor(KeyValue.Data);
                break;

            case "FromBase64":
                sd = SecurityDescriptor.ParseBase64(Base64);
                break;

            default:
                sd = CreateNewSecurityDescriptor();
                break;
            }

            sd.NtType    = Type;
            sd.Container = Container;
            if (MapGeneric)
            {
                sd.MapGenericAccess();
            }

            sd.Control |= Control;
            WriteObject(sd);
        }
예제 #24
0
 private void showThreadSecurityToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (listViewThreads.SelectedItems.Count > 0)
     {
         if (listViewThreads.SelectedItems[0].Tag is ThreadTokenEntry thread)
         {
             if (thread.ThreadSecurity != null)
             {
                 var viewer = new SecurityDescriptorViewerForm($"{thread.Name}:{thread.ProcessId}.{thread.ThreadId}",
                                                               thread.ThreadSecurity, NtType.GetTypeByType <NtThread>(), false);
                 viewer.ShowDialog(this);
             }
         }
     }
 }
 internal DeviceAccessCheckResult(string name, bool namespace_path, FileDeviceType device_type, FileDeviceCharacteristics device_chars,
                                  AccessMask granted_access, SecurityDescriptor sd, TokenInformation token_info) : base(name, "Device",
                                                                                                                        granted_access, NtType.GetTypeByType <NtFile>().GenericMapping, sd, typeof(FileAccessRights), true, token_info)
 {
     NamespacePath   = namespace_path;
     DeviceType      = device_type;
     Characteristics = device_chars;
 }
 internal DeviceAccessCheckResult(string name, bool namespace_path, FileDeviceType device_type,
                                  AccessMask granted_access, string sddl, TokenInformation token_info) : base(name, "Device",
                                                                                                              granted_access, NtType.GetTypeByType <NtFile>().GenericMapping, sddl, typeof(FileAccessRights), false, token_info)
 {
     NamespacePath = namespace_path;
     DeviceType    = device_type;
 }