private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            var devices = new Dictionary <string, SecurityDescriptorEntry>(StringComparer.OrdinalIgnoreCase);

            foreach (string path in Path)
            {
                using (var result = OpenDirectory(path, null))
                {
                    if (result.IsSuccess)
                    {
                        FindDevicesInDirectory(result.Result, devices, MaxDepth ?? int.MaxValue);
                    }
                    else
                    {
                        // If failed, it might be an absolute path so just add it.
                        if (!devices.ContainsKey(path))
                        {
                            devices.Add(path, GetSecurityDescriptor(path));
                        }
                    }
                }
            }

            if (devices.Count > 0)
            {
                AccessMask    access_rights   = _file_type.MapGenericRights(Access);
                EaBuffer      ea_buffer       = CheckEaBuffer ? (EaBuffer ?? CreateDummyEaBuffer()) : null;
                List <string> namespace_paths = new List <string>(NamespacePath ?? new[] { "XYZ" });

                foreach (var entry in tokens)
                {
                    foreach (var pair in devices)
                    {
                        if (CheckDevice())
                        {
                            if (pair.Value != null)
                            {
                                AccessMask granted_access = NtSecurity.GetMaximumAccess(pair.Value.SecurityDescriptor, entry.Token, _file_type.GenericMapping);
                                if (IsAccessGranted(granted_access, access_rights))
                                {
                                    WriteObject(new DeviceAccessCheckResult(pair.Key, false, pair.Value.DeviceType,
                                                                            pair.Value.Characteristics, granted_access,
                                                                            pair.Value.SecurityDescriptor, entry.Information));
                                }
                            }
                            else
                            {
                                if (!NoImpersonation)
                                {
                                    CheckAccessUnderImpersonation(entry, pair.Key, false, access_rights, OpenOptions, ea_buffer);
                                }
                            }
                        }

                        if (CheckNamespace() && !NoImpersonation)
                        {
                            foreach (string namespace_path in namespace_paths)
                            {
                                CheckAccessUnderImpersonation(entry, pair.Key + @"\" + namespace_path,
                                                              true, access_rights, OpenOptions, ea_buffer);
                            }
                        }
                    }
                }
            }
            else
            {
                WriteWarning("Couldn't find any devices to check");
            }
        }
コード例 #2
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":
                {
                    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":
                {
                    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());
        }
コード例 #3
0
        /// <summary>
        /// Process record.
        /// </summary>
        protected override void ProcessRecord()
        {
            Sid sid;

            switch (ParameterSetName)
            {
            case "sddl":
                sid = new Sid(Sddl);
                break;

            case "name":
                sid = NtSecurity.LookupAccountName(Name);
                break;

            case "service":
                sid = NtSecurity.GetServiceSid(ServiceName);
                break;

            case "il":
                sid = NtSecurity.GetIntegritySid(IntegrityLevel);
                break;

            case "il_raw":
                sid = NtSecurity.GetIntegritySidRaw(IntegrityLevelRaw);
                break;

            case "package":
                sid = TokenUtils.DerivePackageSidFromName(PackageName);
                if (RestrictedPackageName != null)
                {
                    sid = TokenUtils.DeriveRestrictedPackageSidFromSid(sid, RestrictedPackageName);
                }
                break;

            case "known":
                sid = KnownSids.GetKnownSid(KnownSid);
                break;

            case "token":
                using (NtToken token = NtToken.OpenProcessToken())
                {
                    if (PrimaryGroup)
                    {
                        sid = token.PrimaryGroup;
                    }
                    else if (Owner)
                    {
                        sid = token.Owner;
                    }
                    else if (LogonGroup)
                    {
                        sid = token.LogonSid.Sid;
                    }
                    else if (AppContainer)
                    {
                        sid = token.AppContainerSid;
                    }
                    else if (Label)
                    {
                        sid = token.IntegrityLevelSid.Sid;
                    }
                    else
                    {
                        sid = token.User.Sid;
                    }
                }
                break;

            case "cap":
                sid = CapabilityGroup ? NtSecurity.GetCapabilityGroupSid(CapabilityName)
                                    : NtSecurity.GetCapabilitySid(CapabilityName);
                break;

            case "sid":
                sid = new Sid(SecurityAuthority, RelativeIdentifier ?? new uint[0]);
                break;

            case "rawsa":
                sid = new Sid(new SidIdentifierAuthority(SecurityAuthorityByte), RelativeIdentifier);
                break;

            case "logon":
                sid = NtSecurity.GetLogonSessionSid();
                break;

            case "trust":
                sid = NtSecurity.GetTrustLevelSid(TrustType, TrustLevel);
                break;

            case "ace":
                sid = AccessControlEntry.Sid;
                break;

            case "relsid":
                sid = BaseSid.CreateRelative(RelativeIdentifier);
                break;

            case "bytes":
                sid = new Sid(Byte);
                break;

            default:
                throw new ArgumentException("No SID type specified");
            }

            if (AsSddl)
            {
                WriteObject(sid.ToString());
            }
            else if (AsName)
            {
                WriteObject(sid.Name);
            }
            else
            {
                WriteObject(sid);
            }
        }
コード例 #4
0
        /// <summary>
        /// Set ACL for control.
        /// </summary>
        /// <param name="acl">The ACL to view.</param>
        /// <param name="access_type">The enum type for the view.</param>
        /// <param name="mapping">Generic mapping for the type.</param>
        /// <param name="valid_access">The valid bit mask for access for this type.</param>
        /// <param name="is_container">True to indicate this object is a container.</param>
        /// <param name="sdk_names">Show the ACEs using SDK style names.</param>
        public void SetAcl(Acl acl, Type access_type, GenericMapping mapping, AccessMask valid_access, bool is_container, bool sdk_names)
        {
            _acl          = acl;
            _access_type  = access_type;
            _mapping      = mapping;
            _valid_access = valid_access;
            _is_container = is_container;
            _sdk_names    = sdk_names;
            showSDKNamesToolStripMenuItem.Checked = sdk_names;

            bool has_conditional_ace      = false;
            bool has_inherited_object_ace = false;
            bool has_object_ace           = false;

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

            if (acl.Defaulted)
            {
                flags.Add("Defaulted");
            }
            if (acl.Protected)
            {
                flags.Add("Protected");
            }
            if (acl.AutoInherited)
            {
                flags.Add("AutoInherited");
            }
            if (acl.AutoInheritReq)
            {
                flags.Add("AutoInheritReq");
            }

            if (flags.Count > 0)
            {
                lblFlags.Text = $"Flags: {string.Join(", ", flags)}";
            }
            else
            {
                lblFlags.Text = "Flags: None";
            }

            if (acl.NullAcl)
            {
                lblFlags.Text             += Environment.NewLine + "NULL ACL";
                listViewAcl.Visible        = false;
                listViewAccess.Visible     = false;
                groupBoxAclEntries.Visible = false;
                groupBoxAccess.Visible     = false;
                return;
            }

            listViewAcl.Items.Clear();
            listViewAcl.Visible    = true;
            listViewAccess.Visible = true;
            listViewAccess.Items.Clear();
            _current_access_type       = null;
            groupBoxAclEntries.Visible = true;
            groupBoxAccess.Visible     = true;

            foreach (var ace in acl)
            {
                if (ace.IsConditionalAce)
                {
                    has_conditional_ace = true;
                }
                if (ace.IsObjectAce)
                {
                    if (ace.ObjectType.HasValue)
                    {
                        has_object_ace = true;
                    }
                    if (ace.InheritedObjectType.HasValue)
                    {
                        has_inherited_object_ace = true;
                    }
                }
            }

            if (!has_conditional_ace)
            {
                listViewAcl.Columns.Remove(columnHeaderCondition);
                copyConditionToolStripMenuItem.Visible = false;
            }

            if (!has_object_ace)
            {
                listViewAcl.Columns.Remove(columnHeaderObject);
            }

            if (!has_inherited_object_ace)
            {
                listViewAcl.Columns.Remove(columnHeaderInheritedObject);
            }

            foreach (var ace in acl)
            {
                var item = listViewAcl.Items.Add(sdk_names ? NtSecurity.AceTypeToSDKName(ace.Type) : ace.Type.ToString());
                item.SubItems.Add(ace.Sid.Name);
                string access;
                if (ace.Type == AceType.MandatoryLabel)
                {
                    access = NtSecurity.AccessMaskToString(ace.Mask.ToMandatoryLabelPolicy(), sdk_names);
                }
                else if (ace.Flags.HasFlag(AceFlags.InheritOnly))
                {
                    access = NtSecurity.AccessMaskToString(ace.Mask.ToSpecificAccess(access_type), sdk_names);
                }
                else
                {
                    AccessMask mapped_mask = mapping.MapMask(ace.Mask);
                    mapped_mask = mapping.UnmapMask(mapped_mask);
                    access      = NtSecurity.AccessMaskToString(mapped_mask.ToSpecificAccess(access_type), sdk_names);
                }

                item.SubItems.Add(access);
                item.SubItems.Add(sdk_names ? NtSecurity.AceFlagsToSDKName(ace.Flags) : ace.Flags.ToString());
                if (has_conditional_ace)
                {
                    item.SubItems.Add(ace.Condition);
                }

                if (has_object_ace)
                {
                    item.SubItems.Add(ace.ObjectType?.ToString() ?? string.Empty);
                }

                if (has_inherited_object_ace)
                {
                    item.SubItems.Add(ace.InheritedObjectType?.ToString() ?? string.Empty);
                }

                item.Tag = ace;

                switch (ace.Type)
                {
                case AceType.Allowed:
                case AceType.AllowedCallback:
                case AceType.AllowedCallbackObject:
                case AceType.AllowedObject:
                    item.BackColor = Color.LightGreen;
                    break;

                case AceType.Denied:
                case AceType.DeniedCallback:
                case AceType.DeniedCallbackObject:
                case AceType.DeniedObject:
                    item.BackColor = Color.LightSalmon;
                    break;

                case AceType.ProcessTrustLabel:
                    item.BackColor = Color.LightSkyBlue;
                    break;

                case AceType.MandatoryLabel:
                    item.BackColor = Color.LightGoldenrodYellow;
                    break;

                case AceType.Audit:
                case AceType.AuditCallback:
                case AceType.AuditCallbackObject:
                case AceType.AuditObject:
                    item.BackColor = Color.LightCoral;
                    break;
                }
            }
            listViewAcl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewAcl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }
        /// <summary>
        /// Overridden ProcessRecord
        /// </summary>
        protected override void ProcessRecord()
        {
            AccessMask mask;

            switch (ParameterSetName)
            {
            case "FromAce":
                mask = AccessControlEntry.Mask;
                break;

            case "FromSecurityInformation":
                if (SetSecurity)
                {
                    mask = NtSecurity.SetSecurityAccessMask(SecurityInformation);
                }
                else
                {
                    mask = NtSecurity.QuerySecurityAccessMask(SecurityInformation);
                }
                break;

            default:
                mask  = AccessMask;
                mask |= MapGeneric(SpecificAccessType.File, FileAccess);
                mask |= MapGeneric(SpecificAccessType.File, FileDirectoryAccess);
                mask |= MapGeneric(SpecificAccessType.IoCompletion, IoCompletionAccess);
                mask |= MapGeneric(SpecificAccessType.Mutant, MutantAccess);
                mask |= MapGeneric(SpecificAccessType.Semaphore, SemaphoreAccess);
                mask |= MapGeneric(SpecificAccessType.RegistryTransaction, RegistryTransactionAccess);
                mask |= MapGeneric(SpecificAccessType.ALPCPort, AlpcPortAccess);
                mask |= MapGeneric(SpecificAccessType.Section, SectionAccess);
                mask |= MapGeneric(SpecificAccessType.Key, KeyAccess);
                mask |= MapGeneric(SpecificAccessType.Event, EventAccess);
                mask |= MapGeneric(SpecificAccessType.SymbolicLink, SymbolicLinkAccess);
                mask |= MapGeneric(SpecificAccessType.Token, TokenAccess);
                mask |= GenericAccess;
                mask |= MapGeneric(SpecificAccessType.Directory, DirectoryAccess);
                mask |= MapGeneric(SpecificAccessType.Thread, ThreadAccess);
                mask |= MapGeneric(SpecificAccessType.DebugObject, DebugObjectAccess);
                mask |= MapGeneric(SpecificAccessType.Job, JobAccess);
                mask |= MapGeneric(SpecificAccessType.Process, ProcessAccess);
                mask |= MapGeneric(SpecificAccessType.Transaction, TransactionAccess);
                mask |= MapGeneric(SpecificAccessType.TransactionManager, TransactionManagerAccess);
                mask |= MapGeneric(SpecificAccessType.ResourceManager, ResourceManagerAccess);
                mask |= MapGeneric(SpecificAccessType.Enlistment, EnlistmentAccess);
                mask |= (uint)ManadatoryLabelPolicy;
                break;
            }

            if (ToGenericAccess)
            {
                WriteObject(mask.ToGenericAccess());
            }
            else if (ToMandatoryLabelPolicy)
            {
                WriteObject(mask.ToMandatoryLabelPolicy());
            }
            else if (ToSpecificAccess == SpecificAccessType.None && ToTypeAccess == null)
            {
                WriteObject(mask);
            }
            else
            {
                NtType type = ToTypeAccess ?? GetTypeObject(ToSpecificAccess);
                WriteObject(mask.ToSpecificAccess(type.AccessRightsType));
            }
        }
コード例 #6
0
        static void Main(string[] args)
        {
            try
            {
                int  pid        = NtProcess.Current.ProcessId;
                bool show_help  = false;
                bool print_sddl = false;

                OptionSet opts = new OptionSet()
                {
                    { "p|pid=", "Specify a PID of a process for access check.", v => pid = int.Parse(v.Trim()) },
                    { "sddl", "Print SDDL security descriptor.", v => print_sddl = v != null },
                    { "h|help", "show this message and exit",
                      v => show_help = v != null },
                };

                HashSet <int> pids = new HashSet <int>(opts.Parse(args).Select(a => int.Parse(a)));
                if (show_help)
                {
                    ShowHelp(opts);
                    return;
                }

                Dictionary <string, string> ports = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                NtToken.EnableDebugPrivilege();
                using (NtToken token = NtToken.OpenProcessToken(pid))
                {
                    IEnumerable <NtHandle> handles         = NtSystemInfo.GetHandles(-1, false);
                    HashSet <ulong>        checked_objects = new HashSet <ulong>();

                    if (pids.Count > 0)
                    {
                        handles = handles.Where(h => pids.Contains(h.ProcessId));
                    }

                    handles = handles.Where(h => h.ObjectType.Equals("ALPC Port", StringComparison.OrdinalIgnoreCase));
                    Dictionary <int, NtProcess> pid_to_process = new Dictionary <int, NtProcess>();
                    foreach (NtHandle handle in handles.Where(h => h.GrantedAccess.IsAccessGranted(GenericAccessRights.ReadControl)))
                    {
                        if (!pid_to_process.ContainsKey(handle.ProcessId))
                        {
                            var result = NtProcess.Open(handle.ProcessId,
                                                        ProcessAccessRights.QueryLimitedInformation | ProcessAccessRights.DupHandle, false);
                            pid_to_process[handle.ProcessId] = result.IsSuccess ? result.Result : null;
                        }

                        NtProcess proc = pid_to_process[handle.ProcessId];
                        if (proc == null)
                        {
                            continue;
                        }

                        try
                        {
                            using (NtAlpc obj = NtAlpc.DuplicateFrom(proc, new IntPtr(handle.Handle)))
                            {
                                string name = obj.FullPath;
                                // We only care about named ALPC ports.
                                if (String.IsNullOrEmpty(name))
                                {
                                    continue;
                                }

                                if (ports.ContainsKey(name))
                                {
                                    continue;
                                }

                                SecurityDescriptor sd             = obj.SecurityDescriptor;
                                AccessMask         granted_access = NtSecurity.GetAllowedAccess(sd, token, AlpcAccessRights.Connect, obj.NtType.GenericMapping);
                                if (granted_access.IsEmpty)
                                {
                                    continue;
                                }
                                ports.Add(name, sd.ToSddl());
                            }
                        }
                        catch (NtException)
                        {
                        }
                    }
                }
                foreach (var pair in ports.OrderBy(p => p.Key))
                {
                    Console.WriteLine(pair.Key);
                    if (print_sddl)
                    {
                        Console.WriteLine("SDDL: {0}", pair.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }
コード例 #7
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="flags">Flags for the ACE.</param>
 /// <param name="policy">The mandatory label policy.</param>
 /// <param name="integrity_level">The integrity level.</param>
 public MandatoryLabelAce(AceFlags flags, MandatoryLabelPolicy policy, TokenIntegrityLevel integrity_level)
     : this(flags, policy, NtSecurity.GetIntegritySid(integrity_level))
 {
 }
        private void BuildAuthZContext()
        {
            _resource_manager = string.IsNullOrWhiteSpace(Server) ? AuthZResourceManager.Create(GetType().Name,
                                                                                                AuthZResourceManagerInitializeFlags.NoAudit | AuthZResourceManagerInitializeFlags.NoCentralAccessPolicies,
                                                                                                null) : AuthZResourceManager.Create(Server, null, AuthZResourceManagerRemoteServiceType.Default);

            var sids = new HashSet <Sid>();

            if (UserSid != null)
            {
                foreach (var sid in UserSid)
                {
                    sids.Add(sid);
                }
            }
            if (UserName != null)
            {
                foreach (var name in UserName)
                {
                    sids.Add(NtSecurity.LookupAccountName(name));
                }
            }
            if (sids.Count == 0)
            {
                sids.Add(NtToken.CurrentUser.Sid);
            }

            if (_resource_manager.Remote || UseLocalGroup)
            {
                _context.AddRange(sids.Select(s => _resource_manager.CreateContext(s, AuthZContextInitializeSidFlags.None)));
            }
            else
            {
                foreach (var sid in sids)
                {
                    if (!NtSecurity.IsDomainSid(sid) || NtSecurity.IsLocalDomainSid(sid))
                    {
                        _context.AddResource(_resource_manager.CreateContext(sid, AuthZContextInitializeSidFlags.None));
                        continue;
                    }

                    WriteProgress($"Building security context for {sid.Name}");
                    var context = _context.AddResource(_resource_manager.CreateContext(sid, AuthZContextInitializeSidFlags.SkipTokenGroups));
                    context.AddSids(_cached_user_groups.GetOrAdd(Tuple.Create(Domain, sid), _ => GetUserDomainSids(Domain, sid)));
                }
            }

            foreach (var context in Context)
            {
                if (sids.Add(context.User.Sid))
                {
                    var next_ctx = _context.AddResource(_resource_manager.CreateContext(context.User.Sid, AuthZContextInitializeSidFlags.SkipTokenGroups));
                    foreach (var group in context.Groups)
                    {
                        next_ctx.AddSid(group.Sid);
                    }
                }
            }

            _token_info = _context.Select(c => new TokenInformation(c)).ToList();
        }
        private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            if (CheckScmAccess)
            {
                SecurityDescriptor sd          = ServiceUtils.GetScmSecurityDescriptor();
                GenericMapping     scm_mapping = ServiceUtils.GetScmGenericMapping();
                foreach (TokenEntry token in tokens)
                {
                    AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, scm_mapping);
                    WriteAccessCheckResult("SCM", "SCM", granted_access, scm_mapping, sd,
                                           typeof(ServiceControlManagerAccessRights), false, token.Information);
                }
            }
            else
            {
                IEnumerable <Win32Service>      services    = GetServices();
                InternalGetAccessibleFileCmdlet file_cmdlet = null;
                HashSet <string> checked_files = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                if (CheckFiles)
                {
                    file_cmdlet = new InternalGetAccessibleFileCmdlet(this)
                    {
                        FormatWin32Path = true
                    };
                }

                GenericMapping service_mapping = ServiceUtils.GetServiceGenericMapping();
                AccessMask     access_rights   = service_mapping.MapMask(Access);

                foreach (var service in services.Where(s => s?.SecurityDescriptor != null))
                {
                    foreach (TokenEntry token in tokens)
                    {
                        AccessMask granted_access = NtSecurity.GetMaximumAccess(service.SecurityDescriptor,
                                                                                token.Token, service_mapping);
                        ServiceAccessRights trigger_access = GetTriggerAccess(service, token.Token);
                        if (IsAccessGranted(granted_access, access_rights))
                        {
                            WriteObject(new ServiceAccessCheckResult(service.Name, granted_access | trigger_access,
                                                                     service.SecurityDescriptor, token.Information, trigger_access,
                                                                     granted_access.ToSpecificAccess <ServiceAccessRights>(), service));
                        }
                    }
                    if (CheckFiles)
                    {
                        if (!string.IsNullOrWhiteSpace(service.ImagePath) &&
                            File.Exists(service.ImagePath) &&
                            checked_files.Add(service.ImagePath))
                        {
                            file_cmdlet.RunAccessCheckPathInternal(tokens, service.ImagePath);
                        }

                        if (!string.IsNullOrWhiteSpace(service.ServiceDll) &&
                            File.Exists(service.ServiceDll) &&
                            checked_files.Add(service.ServiceDll))
                        {
                            file_cmdlet.RunAccessCheckPathInternal(tokens, service.ServiceDll);
                        }
                    }
                }
            }
        }
コード例 #10
0
 /// <summary>
 /// Add an AppContainer capability by name.
 /// </summary>
 /// <param name="capability_name"></param>
 public void AddNamedCapability(string capability_name)
 {
     Capabilities.Add(NtSecurity.GetCapabilitySid(capability_name));
 }
コード例 #11
0
        /// <summary>
        /// Process record.
        /// </summary>
        protected override void ProcessRecord()
        {
            Sid sid;

            if (Sddl != null)
            {
                sid = new Sid(Sddl);
            }
            else if (Name != null)
            {
                sid = NtSecurity.LookupAccountName(Name);
            }
            else if (ServiceName != null)
            {
                sid = NtSecurity.GetServiceSid(ServiceName);
            }
            else if (IntegrityLevel.HasValue)
            {
                sid = NtSecurity.GetIntegritySid(IntegrityLevel.Value);
            }
            else if (IntegrityLevelRaw.HasValue)
            {
                sid = NtSecurity.GetIntegritySidRaw(IntegrityLevelRaw.Value);
            }
            else if (PackageName != null)
            {
                sid = TokenUtils.DerivePackageSidFromName(PackageName);
                if (RestrictedPackageName != null)
                {
                    sid = TokenUtils.DeriveRestrictedPackageSidFromSid(sid, RestrictedPackageName);
                }
            }
            else if (KnownSid.HasValue)
            {
                sid = KnownSids.GetKnownSid(KnownSid.Value);
            }
            else if (Token)
            {
                using (NtToken token = NtToken.OpenProcessToken())
                {
                    if (PrimaryGroup)
                    {
                        sid = token.PrimaryGroup;
                    }
                    else if (Owner)
                    {
                        sid = token.Owner;
                    }
                    else if (LogonGroup)
                    {
                        sid = token.LogonSid.Sid;
                    }
                    else if (AppContainer)
                    {
                        sid = token.AppContainerSid;
                    }
                    else if (Label)
                    {
                        sid = token.IntegrityLevelSid.Sid;
                    }
                    else
                    {
                        sid = token.User.Sid;
                    }
                }
            }
            else
            {
                throw new ArgumentException("No SID type specified");
            }

            WriteObject(sid);
        }
コード例 #12
0
ファイル: CentralAccessPolicy.cs プロジェクト: codehz/winsilo
        /// <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());
        }
        /// <summary>
        /// Process record.
        /// </summary>
        protected override void ProcessRecord()
        {
            IEnumerable <Sid> sids;

            switch (ParameterSetName)
            {
            case "sddl":
                sids = Sddl.Select(s => new Sid(s));
                break;

            case "name":
                sids = Name.Select(s => NtSecurity.LookupAccountName(s));
                break;

            case "service":
                sids = ServiceName.Select(s => NtSecurity.GetServiceSid(s));
                break;

            case "il":
                sids = IntegrityLevel.Select(s => NtSecurity.GetIntegritySid(s));
                break;

            case "il_raw":
                sids = IntegrityLevelRaw.Select(s => NtSecurity.GetIntegritySidRaw(s));
                break;

            case "package":
                sids = PackageName.Select(s => TokenUtils.DerivePackageSidFromName(s));
                if (RestrictedPackageName != null)
                {
                    sids = sids.Select(s => TokenUtils.DeriveRestrictedPackageSidFromSid(s, RestrictedPackageName));
                }
                if (AsCapability)
                {
                    sids = sids.Select(s => NtSecurity.PackageSidToCapability(s));
                }
                break;

            case "known":
                sids = KnownSid.Select(s => KnownSids.GetKnownSid(s));
                break;

            case "token":
                using (NtToken token = NtToken.OpenProcessToken())
                {
                    Sid temp = null;
                    if (PrimaryGroup)
                    {
                        temp = token.PrimaryGroup;
                    }
                    else if (Owner)
                    {
                        temp = token.Owner;
                    }
                    else if (LogonGroup)
                    {
                        temp = token.LogonSid.Sid;
                    }
                    else if (AppContainer)
                    {
                        temp = token.AppContainerSid;
                    }
                    else if (Label)
                    {
                        temp = token.IntegrityLevelSid.Sid;
                    }
                    else
                    {
                        temp = token.User.Sid;
                    }
                    sids = new[] { temp };
                }
                break;

            case "cap":
                sids = CapabilityName.Select(s => CapabilityGroup ? NtSecurity.GetCapabilityGroupSid(s)
                        : NtSecurity.GetCapabilitySid(s));
                break;

            case "sid":
                sids = new[] { new Sid(SecurityAuthority, RelativeIdentifier ?? new uint[0]) };
                break;

            case "rawsa":
                sids = new[] { new Sid(new SidIdentifierAuthority(SecurityAuthorityByte), RelativeIdentifier) };
                break;

            case "logon":
                sids = new[] { NtSecurity.GetLogonSessionSid() };
                break;

            case "trust":
                sids = new[] { NtSecurity.GetTrustLevelSid(TrustType, TrustLevel) };
                break;

            case "ace":
                sids = AccessControlEntry.Select(a => a.Sid);
                break;

            case "relsid":
                sids = new[] { Sibling?BaseSid.CreateSibling(RelativeIdentifier) : BaseSid.CreateRelative(RelativeIdentifier) };
                break;

            case "bytes":
                sids = new[] { new Sid(Byte) };
                break;

            default:
                throw new ArgumentException("No SID type specified");
            }

            if (AsSddl)
            {
                WriteObject(sids.Select(s => s.ToString()), true);
            }
            else if (AsName)
            {
                WriteObject(sids.Select(s => s.Name), true);
            }
            else
            {
                WriteObject(sids, true);
            }
        }
        /// <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);
            }
        }