private static Dictionary <Guid, EventTraceProvider> GetProvidersInternal()
        {
            int retry_count   = 10;
            int buffer_length = 1024;
            Dictionary <Guid, EventTraceProvider> providers = new Dictionary <Guid, EventTraceProvider>();

            while (retry_count-- > 0)
            {
                using (var buffer = new SafeStructureInOutBuffer <PROVIDER_ENUMERATION_INFO>(buffer_length, false))
                {
                    Win32Error error = Win32NativeMethods.TdhEnumerateProviders(buffer, ref buffer_length);
                    if (error == Win32Error.ERROR_INSUFFICIENT_BUFFER)
                    {
                        continue;
                    }
                    if (error != Win32Error.SUCCESS)
                    {
                        error.ToNtException();
                    }
                    var result = buffer.Result;
                    var data   = buffer.Data;
                    TRACE_PROVIDER_INFO[] infos = new TRACE_PROVIDER_INFO[result.NumberOfProviders];
                    buffer.Data.ReadArray(0, infos, 0, infos.Length);
                    foreach (var info in infos)
                    {
                        if (!providers.ContainsKey(info.ProviderGuid))
                        {
                            providers.Add(info.ProviderGuid,
                                          new EventTraceProvider(info.ProviderGuid,
                                                                 buffer.ReadNulTerminatedUnicodeString(info.ProviderNameOffset),
                                                                 info.SchemaSource == 0));
                        }
                    }
                    break;
                }
            }
            foreach (var guid in GetTraceGuids())
            {
                if (!providers.ContainsKey(guid))
                {
                    providers.Add(guid, new EventTraceProvider(guid));
                }
            }
            using (var key = NtKey.Open(@"\REGISTRY\MACHINE\SYSTEM\CurrentControlSet\Control\WMI\Security",
                                        null, KeyAccessRights.QueryValue, KeyCreateOptions.NonVolatile, false))
            {
                if (key.IsSuccess)
                {
                    foreach (var value in key.Result.QueryValues())
                    {
                        if (Guid.TryParse(value.Name, out Guid id) && !providers.ContainsKey(id))
                        {
                            providers.Add(id, new EventTraceProvider(id,
                                                                     SecurityDescriptor.Parse(value.Data, false).GetResultOrDefault()));
                        }
                    }
                }
            }
            return(providers);
        }
Exemple #2
0
        internal ScheduledTaskEntry(IRegisteredTask task)
        {
            SecurityDescriptor = SecurityDescriptor.Parse(task.GetSecurityDescriptor((int)SecurityInformation.AllBasic), false).GetResultOrDefault();
            Path    = task.Path;
            Enabled = task.Enabled;
            Xml     = task.Xml;
            var definition = task.Definition;
            var settings   = definition.Settings;

            Hidden           = settings.Hidden;
            AllowDemandStart = settings.AllowDemandStart;
            var principal = definition.Principal;

            if (principal.RunLevel == _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST)
            {
                RunLevel = TaskRunLevel.Highest;
            }

            List <string> privs = new List <string>();

            if (principal is IPrincipal2 prin2)
            {
                privs.AddRange(Enumerable.Range(0, prin2.RequiredPrivilegeCount).Select(i => prin2.RequiredPrivilege[i]));
                ProcessTokenSid = (TaskProcessTokenSid)(int)prin2.ProcessTokenSidType;
            }
            RequiredPrivilege = privs.AsReadOnly();

            TaskLogonType logon_type     = TaskLogonType.None;
            string        principal_name = string.Empty;

            switch (principal.LogonType)
            {
            case _TASK_LOGON_TYPE.TASK_LOGON_GROUP:
                logon_type     = TaskLogonType.Group;
                principal_name = principal.GroupId;
                break;

            case _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN:
            case _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD:
            case _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD:
                logon_type     = TaskLogonType.User;
                principal_name = principal.UserId;
                break;

            case _TASK_LOGON_TYPE.TASK_LOGON_SERVICE_ACCOUNT:
                logon_type     = TaskLogonType.ServiceAccount;
                principal_name = principal.UserId;
                break;

            case _TASK_LOGON_TYPE.TASK_LOGON_S4U:
                logon_type     = TaskLogonType.S4U;
                principal_name = principal.UserId;
                break;
            }
            LogonType          = logon_type;
            Principal          = principal_name;
            Actions            = definition.Actions.Cast <IAction>().Select(a => new ScheduledTaskAction(a)).ToList().AsReadOnly();
            HasActionArguments = Actions.Any(a => a.HasArguments);
            Triggers           = definition.Triggers.Cast <ITrigger>().Select(ScheduledTaskTrigger.Create).ToList().AsReadOnly();
        }
Exemple #3
0
        public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
        {
            if (inputData is string var_name && var_name.StartsWith("$"))
            {
                // Work around a weird bug, if this starts with a $ it's probably a variable.
                // Query for it from the session state.
                inputData = engineIntrinsics.SessionState.PSVariable.GetValue(var_name.Substring(1));
            }

            if (inputData is string s)
            {
                var result = SecurityDescriptor.Parse(s, false);
                if (result.IsSuccess)
                {
                    return(result.Result);
                }
            }

            if (inputData is PSObject obj)
            {
                if (obj.BaseObject is SecurityDescriptor sd)
                {
                    return(sd);
                }
            }

            return(new SecurityDescriptor());
        }
        /// <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));
            }
        }
Exemple #5
0
 internal SecurityDescriptor GetSecurityDescriptor()
 {
     if (Type != DEVPROPTYPE.SECURITY_DESCRIPTOR)
     {
         return(null);
     }
     return(SecurityDescriptor.Parse(Data, NtType.GetTypeByType <NtFile>(),
                                     false).GetResultOrDefault());
 }
        private static SecurityDescriptor GetObjectSecurityDescriptor(SearchResult result)
        {
            var sd = GetPropertyValue <byte[]>(result, kNTSecurityDescriptor);

            if (sd == null)
            {
                return(null);
            }
            return(SecurityDescriptor.Parse(sd, DirectoryServiceUtils.NtType, false).GetResultOrDefault());
        }
Exemple #7
0
 /// <summary>
 /// Query the Auditing Security Descriptor.
 /// </summary>
 /// <param name="security_information">The security information to query.</param>
 /// <param name="throw_on_error">True to throw on error.</param>
 /// <returns>The security descriptor.</returns>
 public static NtResult <SecurityDescriptor> QuerySecurity(SecurityInformation security_information, bool throw_on_error)
 {
     if (!SecurityNativeMethods.AuditQuerySecurity(security_information, out SafeAuditBuffer buffer))
     {
         return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <SecurityDescriptor>(throw_on_error));
     }
     using (buffer) {
         return(SecurityDescriptor.Parse(buffer, NtType, throw_on_error));
     }
 }
Exemple #8
0
        /// <summary>
        /// Parse an SDDL conditional expression.
        /// </summary>
        /// <param name="condition_sddl">The SDDL expression to parse.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The parsed conditional expression.</returns>
        public static NtResult <ConditionalExpression> Parse(string condition_sddl, bool throw_on_error)
        {
            var sd = SecurityDescriptor.Parse($"D:(XA;;1;;;WD;({condition_sddl}))", throw_on_error);

            if (!sd.IsSuccess)
            {
                return(sd.Cast <ConditionalExpression>());
            }
            return(Parse(sd.Result.Dacl[0].ApplicationData, throw_on_error));
        }
        /// <summary>
        /// Get the security descriptor specifying which parts to retrieve
        /// </summary>
        /// <param name="security_information">What parts of the security descriptor to retrieve</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The security descriptor</returns>
        public NtResult <SecurityDescriptor> GetSecurityDescriptor(SecurityInformation security_information, bool throw_on_error)
        {
            var status = SecurityNativeMethods.SamQuerySecurityObject(_handle, security_information, out SafeSamMemoryBuffer sd);

            if (!status.IsSuccess())
            {
                return(status.CreateResultFromError <SecurityDescriptor>(throw_on_error));
            }
            using (sd)
            {
                return(SecurityDescriptor.Parse(sd, NtType, throw_on_error));
            }
        }
 internal DirectoryServiceSchemaClass(string domain, string dn, Guid schema_id,
                                      string name, string ldap_name, string description, string object_class,
                                      string subclass_of, List <DirectoryServiceSchemaClassAttribute> attributes, string default_security_desc)
     : base(domain, dn, schema_id, name, ldap_name, description, object_class)
 {
     SubClassOf = subclass_of ?? string.Empty;
     Attributes = attributes.AsReadOnly();
     DefaultSecurityDescriptorSddl = default_security_desc;
     if (!string.IsNullOrWhiteSpace(default_security_desc))
     {
         DefaultSecurityDescriptor = SecurityDescriptor.Parse(default_security_desc, DirectoryServiceUtils.NtType, true, false).GetResultOrDefault();
     }
 }
        /// <summary>
        /// Get security descriptor for the printer.
        /// </summary>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The printer's security descriptor.</returns>
        public NtResult <SecurityDescriptor> GetSecurityDescriptor(bool throw_on_error)
        {
            PrintingNativeMethods.GetPrinter(_handle, 3, SafeHGlobalBuffer.Null, 0, out int length);
            using (var buffer = new SafeStructureInOutBuffer <PRINTER_INFO_3>(length, false))
            {
                var error = PrintingNativeMethods.GetPrinter(_handle, 3, buffer, length, out length).GetLastWin32Error();
                if (error != Win32Error.SUCCESS)
                {
                    return(error.CreateResultFromDosError <SecurityDescriptor>(throw_on_error));
                }

                return(SecurityDescriptor.Parse(buffer.Result.pSecurityDescriptor, _type, throw_on_error));
            }
        }
        /// <summary>
        /// Get the security descriptor for a named resource.
        /// </summary>
        /// <param name="name">The name of the resource.</param>
        /// <param name="type">The type of the resource.</param>
        /// <param name="security_information">The security information to get.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The security descriptor.</returns>
        public static NtResult <SecurityDescriptor> GetSecurityInfo(
            string name,
            SeObjectType type,
            SecurityInformation security_information,
            bool throw_on_error)
        {
            using (var result = Win32NativeMethods.GetNamedSecurityInfo(name, type,
                                                                        security_information, null,
                                                                        null, null, null, out SafeLocalAllocBuffer sd).MapDosErrorToStatus().CreateResult(throw_on_error, () => sd))
            {
                if (!result.IsSuccess)
                {
                    return(result.Cast <SecurityDescriptor>());
                }

                return(SecurityDescriptor.Parse(result.Result, GetNativeType(type), throw_on_error));
            }
        }
 internal DirectoryServiceSchemaClass(string domain, string dn, Guid schema_id,
                                      string name, string ldap_name, string description, string object_class,
                                      bool system_only, string subclass_of, List <DirectoryServiceSchemaClassAttribute> attributes,
                                      string default_security_desc, List <DirectoryServiceReferenceClass> auxiliary_classes,
                                      List <DirectoryServiceReferenceClass> superior_classes, int category, string[] possible_inferiors)
     : base(domain, dn, schema_id, name, ldap_name, description, object_class, system_only)
 {
     SubClassOf = subclass_of ?? string.Empty;
     Attributes = attributes.AsReadOnly();
     DefaultSecurityDescriptorSddl = default_security_desc;
     if (!string.IsNullOrWhiteSpace(default_security_desc))
     {
         DefaultSecurityDescriptor = SecurityDescriptor.Parse(default_security_desc,
                                                              DirectoryServiceUtils.NtType, true, false).GetResultOrDefault();
     }
     AuxiliaryClasses  = auxiliary_classes.AsReadOnly();
     PossibleSuperiors = superior_classes.AsReadOnly();
     Category          = (DirectoryServiceSchemaClassCategory)category;
     PossibleInferiors = new List <string>(possible_inferiors ?? new string[0]).AsReadOnly();
 }
Exemple #14
0
        /// <summary>
        /// Get the security descriptor for a resource.
        /// </summary>
        /// <param name="handle">The handle to the resource.</param>
        /// <param name="type">The type of the resource.</param>
        /// <param name="security_information">The security information to get.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The security descriptor.</returns>
        public static NtResult <SecurityDescriptor> GetSecurityInfo(
            SafeHandle handle,
            SeObjectType type,
            SecurityInformation security_information,
            bool throw_on_error)
        {
            using (var result = SecurityNativeMethods.GetSecurityInfo(handle, type,
                                                                      security_information, null,
                                                                      null, null, null, out SafeLocalAllocBuffer sd).MapDosErrorToStatus().CreateResult(throw_on_error, () => sd)) {
                if (!result.IsSuccess)
                {
                    return(result.Cast <SecurityDescriptor>());
                }

                NtType sd_type = null;
                if (handle is SafeKernelObjectHandle kernel_handle)
                {
                    sd_type = NtType.GetTypeByName(kernel_handle.NtTypeName, false);
                }

                return(SecurityDescriptor.Parse(result.Result, sd_type ?? GetNativeType(type), throw_on_error));
            }
        }
Exemple #15
0
        /// <summary>
        /// Parse the policy from the Local Security Authority.
        /// </summary>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The list of Central Access Policies.</returns>
        public static NtResult <CentralAccessPolicy[]> ParseFromLsa(bool throw_on_error)
        {
            NtStatus status = SecurityNativeMethods.LsaGetAppliedCAPIDs(null, out SafeLsaMemoryBuffer capids, out int capid_count);

            if (!status.IsSuccess())
            {
                return(status.CreateResultFromError <CentralAccessPolicy[]>(throw_on_error));
            }
            List <CentralAccessPolicy> ret = new List <CentralAccessPolicy>();

            using (capids) {
                status = SecurityNativeMethods.LsaQueryCAPs(capids.DangerousGetHandle(), capid_count, out SafeLsaMemoryBuffer caps, out uint cap_count);
                if (!status.IsSuccess())
                {
                    return(status.CreateResultFromError <CentralAccessPolicy[]>(throw_on_error));
                }
                caps.Initialize <CENTRAL_ACCESS_POLICY>(cap_count);
                CENTRAL_ACCESS_POLICY[] policies = new CENTRAL_ACCESS_POLICY[cap_count];
                caps.ReadArray(0, policies, 0, policies.Length);
                foreach (var policy in policies)
                {
                    SafeHGlobalBuffer buffer       = new SafeHGlobalBuffer(policy.CAPEs, policy.CAPECount * IntPtr.Size, false);
                    IntPtr[]          rule_entries = new IntPtr[policy.CAPECount];
                    buffer.ReadArray(0, rule_entries, 0, policy.CAPECount);
                    List <CentralAccessRule> rules = new List <CentralAccessRule>();
                    foreach (var ptr in rule_entries)
                    {
                        var entry                     = new SafeStructureInOutBuffer <CENTRAL_ACCESS_POLICY_ENTRY>(ptr, Marshal.SizeOf(typeof(CENTRAL_ACCESS_POLICY_ENTRY)), false);
                        var r                         = entry.Result;
                        SecurityDescriptor sd         = null;
                        SecurityDescriptor staged_sd  = null;
                        string             applies_to = string.Empty;
                        if (r.LengthSD > 0)
                        {
                            var result = SecurityDescriptor.Parse(r.SD, throw_on_error);
                            if (!result.IsSuccess)
                            {
                                return(result.Cast <CentralAccessPolicy[]>());
                            }
                            sd = result.Result;
                        }
                        if (r.LengthStagedSD > 0)
                        {
                            var result = SecurityDescriptor.Parse(r.StagedSD, throw_on_error);
                            if (!result.IsSuccess)
                            {
                                return(result.Cast <CentralAccessPolicy[]>());
                            }
                            staged_sd = result.Result;
                        }
                        if (r.LengthAppliesTo > 0)
                        {
                            byte[] condition = new byte[r.LengthAppliesTo];
                            Marshal.Copy(r.AppliesTo, condition, 0, r.LengthAppliesTo);
                            var result = NtSecurity.ConditionalAceToString(condition, throw_on_error);
                            if (!result.IsSuccess)
                            {
                                return(result.Cast <CentralAccessPolicy[]>());
                            }
                            applies_to = result.Result;
                        }

                        rules.Add(new CentralAccessRule(r.Name.ToString(), r.Description.ToString(),
                                                        sd, staged_sd, applies_to, r.ChangeId.ToString(), r.Flags));
                    }
                    var capid = Sid.Parse(policy.CAPID, throw_on_error);
                    if (!capid.IsSuccess)
                    {
                        return(capid.Cast <CentralAccessPolicy[]>());
                    }
                    ret.Add(new CentralAccessPolicy(capid.Result, policy.Flags, policy.Name.ToString(),
                                                    policy.Description.ToString(), policy.ChangeId.ToString(), rules));
                }
            }
            return(ret.ToArray().CreateResult());
        }
Exemple #16
0
        internal static NtResult <CentralAccessRule> FromRegistry(NtKey key, bool throw_on_error)
        {
            string             name        = string.Empty;
            string             description = string.Empty;
            SecurityDescriptor sd          = null;
            SecurityDescriptor staged_sd   = null;
            string             applies_to  = string.Empty;
            string             change_id   = string.Empty;
            uint flags = 0;

            foreach (var value in key.QueryValues())
            {
                switch (value.Name.ToLower())
                {
                case "appliesto":
                    if (value.Data.Length > 0)
                    {
                        var result = NtSecurity.ConditionalAceToString(value.Data, throw_on_error);
                        if (!result.IsSuccess)
                        {
                            return(result.Cast <CentralAccessRule>());
                        }
                        applies_to = result.Result;
                    }
                    break;

                case "sd":
                {
                    if (value.Data.Length > 0)
                    {
                        var sd_result = SecurityDescriptor.Parse(value.Data, throw_on_error);
                        if (!sd_result.IsSuccess)
                        {
                            return(sd_result.Cast <CentralAccessRule>());
                        }
                        sd = sd_result.Result;
                    }
                }
                break;

                case "stagedsd":
                {
                    if (value.Data.Length > 0)
                    {
                        var sd_result = SecurityDescriptor.Parse(value.Data, throw_on_error);
                        if (!sd_result.IsSuccess)
                        {
                            return(sd_result.Cast <CentralAccessRule>());
                        }
                        staged_sd = sd_result.Result;
                    }
                }
                break;

                case "changeid":
                    change_id = value.ToString().TrimEnd('\0');
                    break;

                case "description":
                    description = value.ToString().TrimEnd('\0');
                    break;

                case "flags":
                    if (value.Type == RegistryValueType.Dword)
                    {
                        flags = (uint)value.ToObject();
                    }
                    break;

                case "name":
                    name = value.ToString().TrimEnd('\0');
                    break;
                }
            }
            return(new CentralAccessRule(name, description, sd, staged_sd, applies_to, change_id, flags).CreateResult());
        }
Exemple #17
0
 internal ScheduledTaskEntry(ITaskFolder folder)
 {
     Folder             = true;
     SecurityDescriptor = SecurityDescriptor.Parse(folder.GetSecurityDescriptor((int)SecurityInformation.AllBasic), false).GetResultOrDefault();
     Path = folder.Path;
 }
 protected override NtResult <object> Parse(string value, bool throw_on_error)
 {
     return(SecurityDescriptor.Parse(value, false).Cast <object>());
 }