private bool GenClientContext(AuthenticationToken token)
        {
            using (DisposableList list = new DisposableList())
            {
                SecStatusCode result = 0;

                SecBuffer     out_sec_buffer  = list.AddResource(new SecBuffer(SecBufferType.Token, 64 * 1024));
                SecBufferDesc out_buffer_desc = list.AddResource(new SecBufferDesc(out_sec_buffer));

                InitializeContextRetFlags flags;
                LargeInteger expiry = new LargeInteger();
                if (token != null)
                {
                    List <SecBuffer> buffers = new List <SecBuffer>();
                    buffers.Add(list.AddResource(new SecBuffer(SecBufferType.Token, token.ToArray())));
                    if (_channel_binding != null)
                    {
                        buffers.Add(list.AddResource(SecBuffer.CreateForChannelBinding(_channel_binding)));
                    }
                    SecBufferDesc in_buffer_desc = list.AddResource(new SecBufferDesc(buffers.ToArray()));
                    result = SecurityNativeMethods.InitializeSecurityContext(_creds.CredHandle, _context, _target, _req_attributes, 0,
                                                                             _data_rep, in_buffer_desc, 0, _context, out_buffer_desc, out flags, expiry).CheckResult();
                    Flags = flags;
                }
                else
                {
                    SecBufferDesc    in_buffer_desc = null;
                    List <SecBuffer> buffers        = new List <SecBuffer>();
                    if (_channel_binding != null)
                    {
                        buffers.Add(list.AddResource(SecBuffer.CreateForChannelBinding(_channel_binding)));
                        in_buffer_desc = list.AddResource(new SecBufferDesc(buffers.ToArray()));
                    }

                    result = SecurityNativeMethods.InitializeSecurityContext(_creds.CredHandle, null, _target,
                                                                             _req_attributes, 0, _data_rep, in_buffer_desc, 0, _context,
                                                                             out_buffer_desc, out flags, expiry).CheckResult();
                }

                Expiry = expiry.QuadPart;
                Flags  = flags;
                if (result == SecStatusCode.CompleteNeeded || result == SecStatusCode.CompleteAndContinue)
                {
                    SecurityNativeMethods.CompleteAuthToken(_context, out_buffer_desc).CheckResult();
                }

                Token = AuthenticationToken.Parse(_creds.PackageName, _token_count++, true, out_buffer_desc.ToArray()[0].ToArray());
                return(!(result == SecStatusCode.ContinueNeeded || result == SecStatusCode.CompleteAndContinue));
            }
        }
コード例 #2
0
        /// <summary>
        /// Get the source of inherited ACEs.
        /// </summary>
        /// <param name="name">The name of the resource.</param>
        /// <param name="type">The type of the resource.</param>
        /// <param name="container">Whether the resource is a container.</param>
        /// <param name="object_types">Optional list of object types.</param>
        /// <param name="security_descriptor">The security descriptor for the resource.</param>
        /// <param name="sacl">True to check the SACL otherwise checks the DACL.</param>
        /// <param name="generic_mapping">Generic mapping for the resource.</param>
        /// <param name="query_security">Query security descriptors for sources.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The list of inheritance sources.</returns>
        public static NtResult <IEnumerable <SecurityDescriptorInheritanceSource> > GetInheritanceSource(
            string name,
            SeObjectType type,
            bool container,
            Guid[] object_types,
            SecurityDescriptor security_descriptor,
            bool sacl,
            GenericMapping generic_mapping,
            bool query_security,
            bool throw_on_error)
        {
            Acl acl = sacl ? security_descriptor.Sacl : security_descriptor.Dacl;

            if (acl == null || acl.NullAcl)
            {
                return(NtStatus.STATUS_INVALID_ACL.CreateResultFromError <IEnumerable <SecurityDescriptorInheritanceSource> >(throw_on_error));
            }

            using (var list = new DisposableList())
            {
                SafeGuidArrayBuffer guids = SafeGuidArrayBuffer.Null;
                if (object_types?.Length > 0)
                {
                    guids = list.AddResource(new SafeGuidArrayBuffer(object_types));
                }

                NtType native_type = GetNativeType(type);

                INHERITED_FROM[] inherited_from = new INHERITED_FROM[acl.Count];
                NtStatus         status         = NtStatus.STATUS_INVALID_PARAMETER;
                try
                {
                    status = Win32NativeMethods.GetInheritanceSource(name, type, sacl ? SecurityInformation.Sacl : SecurityInformation.Dacl,
                                                                     container, guids, guids.Count, acl.ToByteArray(), IntPtr.Zero, ref generic_mapping, inherited_from).MapDosErrorToStatus();
                    return(status.CreateResult(throw_on_error, () => (IEnumerable <SecurityDescriptorInheritanceSource>)inherited_from
                                               .Select((s, i) => new SecurityDescriptorInheritanceSource(acl[i], s, type,
                                                                                                         native_type, container, query_security, sacl)).Where(s => s.Depth != -1).ToArray()));
                }
                finally
                {
                    if (status.IsSuccess())
                    {
                        Win32NativeMethods.FreeInheritedFromArray(inherited_from, (ushort)inherited_from.Length, IntPtr.Zero);
                    }
                }
            }
        }
コード例 #3
0
        private static SECURITY_ATTRIBUTES CreateSecurityAttributes(SecurityDescriptor sd, bool inherit, DisposableList <IDisposable> resources)
        {
            if (sd == null && !inherit)
            {
                return(null);
            }
            var ret = new SECURITY_ATTRIBUTES()
            {
                bInheritHandle = inherit
            };

            if (sd != null)
            {
                ret.lpSecurityDescriptor = resources.AddResource(sd.ToSafeBuffer());
            }
            return(ret);
        }
コード例 #4
0
        /// <summary>
        /// Perform an Access Check.
        /// </summary>
        /// <param name="sd">The security descriptor for the check.</param>
        /// <param name="optional_sd">Optional list of security descriptors to merge.</param>
        /// <param name="desired_access">The desired access.</param>
        /// <param name="principal">Optional Principal SID.</param>
        /// <param name="object_types">Optional list of object types.</param>
        /// <param name="type">NT Type for access checking.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The list of access check results.</returns>
        public NtResult <AuthZAccessCheckResult[]> AccessCheck(SecurityDescriptor sd, IEnumerable <SecurityDescriptor> optional_sd,
                                                               AccessMask desired_access, Sid principal, IEnumerable <ObjectTypeEntry> object_types, NtType type,
                                                               bool throw_on_error)
        {
            if (sd is null)
            {
                throw new ArgumentNullException(nameof(sd));
            }

            using (var list = new DisposableList())
            {
                AUTHZ_ACCESS_REQUEST request = new AUTHZ_ACCESS_REQUEST();
                request.DesiredAccess = desired_access;
                if (principal != null)
                {
                    request.PrincipalSelfSid = list.AddResource(principal.ToSafeBuffer()).DangerousGetHandle();
                }

                int result_count = 1;
                var object_list  = NtSecurity.ConvertObjectTypes(object_types, list);
                if (object_list?.Length > 0)
                {
                    result_count                 = object_list.Length;
                    request.ObjectTypeList       = list.AddResource(object_list.ToBuffer()).DangerousGetHandle();
                    request.ObjectTypeListLength = object_list.Length;
                }
                var      sd_buffer           = list.AddResource(sd.ToSafeBuffer());
                int      optional_sd_count   = optional_sd?.Count() ?? 0;
                IntPtr[] optional_sd_buffers = null;
                if (optional_sd_count > 0)
                {
                    optional_sd_buffers = optional_sd.Select(s => list.AddResource(s.ToSafeBuffer()).DangerousGetHandle()).ToArray();
                }
                AUTHZ_ACCESS_REPLY reply = new AUTHZ_ACCESS_REPLY();
                reply.ResultListLength = result_count;
                var error_buffer = list.AddResource(new int[result_count].ToBuffer());
                reply.Error = error_buffer.DangerousGetHandle();
                var access_buffer = list.AddResource(new AccessMask[result_count].ToBuffer());
                reply.GrantedAccessMask = access_buffer.DangerousGetHandle();
                var audit_buffer = list.AddResource(new int[result_count].ToBuffer());
                reply.SaclEvaluationResults = audit_buffer.DangerousGetHandle();

                return(SecurityNativeMethods.AuthzAccessCheck(AuthZAccessCheckFlags.None, _handle,
                                                              ref request, IntPtr.Zero, sd_buffer, optional_sd_buffers, optional_sd_count,
                                                              ref reply, IntPtr.Zero).CreateWin32Result(throw_on_error,
                                                                                                        () => CreateResult(result_count, error_buffer, access_buffer, object_types?.ToArray(), type)));
            }
        }
        private SafeHGlobalBuffer GetAttributes(DisposableList <IDisposable> resources)
        {
            int count = GetAttributeCount();

            if (count == 0)
            {
                return(SafeHGlobalBuffer.Null);
            }

            var attr_list = resources.AddResource(new SafeProcThreadAttributeListBuffer(count));

            if (ParentProcess != null)
            {
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeParentProcess, ParentProcess.Handle.DangerousGetHandle());
            }

            if (MitigationOptions2 != ProcessMitigationOptions2.None)
            {
                MemoryStream stm    = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(stm);

                writer.Write((ulong)MitigationOptions);
                writer.Write((ulong)MitigationOptions2);
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, stm.ToArray());
            }
            else if (MitigationOptions != ProcessMitigationOptions.None)
            {
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, (ulong)MitigationOptions);
            }

            if (Win32kFilterFlags != Win32kFilterFlags.None)
            {
                Win32kFilterAttribute filter = new Win32kFilterAttribute();
                filter.Flags       = Win32kFilterFlags;
                filter.FilterLevel = Win32kFilterLevel;
                attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeWin32kFilter, resources.AddResource(filter.ToBuffer()));
            }

            if ((CreationFlags & CreateProcessFlags.ProtectedProcess) != 0)
            {
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeProtectionLevel, (int)ProtectionLevel);
            }

            return(attr_list);
        }
コード例 #6
0
        public void UpdateProcessList(ProcessAccessRights desired_access, bool require_token, bool filter_native)
        {
            NtToken.EnableDebugPrivilege();
            ClearListView();
            using (var ps = NtProcess.GetProcesses(ProcessAccessRights.QueryLimitedInformation | desired_access, true).ToDisposableList())
            {
                foreach (var p in ps.OrderBy(p => p.ProcessId))
                {
                    if (p.Is64Bit && !Environment.Is64BitProcess && filter_native)
                    {
                        continue;
                    }

                    using (var result = NtToken.OpenProcessToken(p, TokenAccessRights.Query, false))
                    {
                        if (!result.IsSuccess && require_token)
                        {
                            continue;
                        }

                        ListViewItem item = listViewProcesses.Items.Add(p.ProcessId.ToString());
                        item.SubItems.Add(p.Name);
                        item.SubItems.Add(COMUtilities.FormatBitness(p.Is64Bit));
                        if (result.IsSuccess)
                        {
                            NtToken token = result.Result;
                            item.SubItems.Add(p.User.Name);
                            item.SubItems.Add(token.IntegrityLevel.ToString());
                        }
                        item.Tag = _processes.AddResource(p.Duplicate());
                    }
                }
            }
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewProcesses.ListViewItemSorter = new ListItemComparer(0);
        }
コード例 #7
0
        internal override SafeBuffer ToBuffer(DisposableList list, string package)
        {
            if (!AuthenticationPackage.CheckSChannel(package) &&
                !AuthenticationPackage.CheckCredSSP(package))
            {
                throw new ArgumentException("Can only use SchannelCredentials for the Schannel or CredSSP package.", nameof(package));
            }
            SCHANNEL_CRED creds = new SCHANNEL_CRED
            {
                dwVersion         = SCHANNEL_CRED.SCHANNEL_CRED_VERSION,
                dwSessionLifespan = SessionLifespan,
                dwFlags           = Flags
            };

            if (_certs.Count > 0)
            {
                IntPtr[] cred_handles = _certs.Select(c => c.Handle).ToArray();
                var      array_buffer = list.AddResource(cred_handles.ToBuffer());
                creds.cCreds = cred_handles.Length;
                creds.paCred = array_buffer.DangerousGetHandle();
            }

            return(creds.ToBuffer());
        }
コード例 #8
0
ファイル: AppContainerProfile.cs プロジェクト: codehz/winsilo
 /// <summary>
 /// Create a new AppContainerProfile.
 /// </summary>
 /// <param name="appcontainer_name">The name of the AppContainer.</param>
 /// <param name="display_name">A display name.</param>
 /// <param name="description">An optional description.</param>
 /// <param name="capabilities">An optional list of capability SIDs.</param>
 /// <param name="throw_on_error">True to throw on error.</param>
 /// <returns>The created AppContainer profile.</returns>
 /// <remarks>If the profile already exists then it'll be opened instead.</remarks>
 public static NtResult <AppContainerProfile> Create(
     string appcontainer_name,
     string display_name,
     string description,
     IEnumerable <Sid> capabilities,
     bool throw_on_error)
 {
     using (var resources = new DisposableList()) {
         var      caps   = resources.CreateSidAndAttributes(capabilities);
         NtStatus status = Win32NativeMethods.CreateAppContainerProfile(appcontainer_name, display_name, description,
                                                                        caps.Length > 0 ? caps : null, caps.Length, out SafeSidBufferHandle sid);
         if (status == NtObjectUtils.MapDosErrorToStatus(Win32Error.ERROR_ALREADY_EXISTS))
         {
             return(new AppContainerProfile(appcontainer_name).CreateResult());
         }
         resources.AddResource(sid);
         return(status.CreateResult(throw_on_error, () => {
             using (sid) {
                 return new AppContainerProfile(appcontainer_name, sid.ToSid(),
                                                capabilities, display_name, description);
             }
         }));
     }
 }
コード例 #9
0
        /// <summary>
        /// Create a remote thread.
        /// </summary>
        /// <param name="process">The process to create the thread in.</param>
        /// <param name="security_descriptor">The thread security descriptor.</param>
        /// <param name="inherit_handle">Whether the handle should be inherited.</param>
        /// <param name="stack_size">The size of the stack. 0 for default.</param>
        /// <param name="start_address">Start address for the thread.</param>
        /// <param name="parameter">Parameter to pass to the thread.</param>
        /// <param name="flags">The flags for the thread creation.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The created thread.</returns>
        /// <exception cref="NtException">Thrown on error.</exception>
        public static NtResult <NtThread> CreateRemoteThread(
            NtProcess process,
            SecurityDescriptor security_descriptor,
            bool inherit_handle,
            long stack_size,
            long start_address,
            long parameter,
            CreateThreadFlags flags,
            bool throw_on_error)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            using (var resources = new DisposableList()) {
                SECURITY_ATTRIBUTES sec_attr = null;
                if (security_descriptor != null || inherit_handle)
                {
                    sec_attr = new SECURITY_ATTRIBUTES {
                        bInheritHandle       = inherit_handle,
                        lpSecurityDescriptor = security_descriptor == null ? SafeHGlobalBuffer.Null :
                                               resources.AddResource(security_descriptor.ToSafeBuffer())
                    };
                }

                var handle = Win32NativeMethods.CreateRemoteThreadEx(process.GetHandle(),
                                                                     sec_attr, new IntPtr(stack_size), new IntPtr(start_address),
                                                                     new IntPtr(parameter), flags, SafeHGlobalBuffer.Null, null);
                if (handle.IsInvalid)
                {
                    return(NtObjectUtils.CreateResultFromDosError <NtThread>(throw_on_error));
                }
                return(new NtThread(handle).CreateResult());
            }
        }
コード例 #10
0
        static void Main(string[] args)
        {
            try
            {
                if (!Environment.Is64BitProcess && Environment.Is64BitOperatingSystem)
                {
                    Console.WriteLine("Must run as x64 binary on this OS");
                    return;
                }

                if (args.Length < 2)
                {
                    Console.WriteLine("Usage: PID PathToDll [optional argument]");
                    return;
                }

                int    pid     = int.Parse(args[0]);
                string dllpath = Path.GetFullPath(args[1]);
                string argstr  = args.Length > 2 ? args[2] : string.Empty;
                Console.WriteLine("Loading {0} into pid {1}", dllpath, pid);

                FixupDbgView();

                using (var list = new DisposableList())
                {
                    long handle_ptr       = GetHandleAddress();
                    var  proc             = list.AddResource(NtProcess.Open(pid, ProcessAccessRights.AllAccess));
                    var  old_handle_value = proc.ReadMemory <IntPtr>(handle_ptr);
                    var  lib         = list.AddResource(SafeLoadLibraryHandle.LoadLibrary(dllpath));
                    var  entry_point = lib.GetProcAddress(ENTRYPOINT);
                    if (entry_point == IntPtr.Zero)
                    {
                        throw new ArgumentException($"Can't find {ENTRYPOINT} export.");
                    }

                    var dir           = list.AddResource(CreateDirectory());
                    var image_section = list.AddResource(CreateSection(dllpath, FAKEDLLNAME, dir));

                    IntPtr handle_value = dir.DuplicateTo(proc);
                    var    dllname_ptr  = WriteString(proc, FAKEDLLNAME);
                    var    kernel32     = SafeLoadLibraryHandle.GetModuleHandle("kernelbase.dll");
                    var    load_lib     = kernel32.GetProcAddress("LoadLibraryW");

                    proc.WriteMemory(handle_ptr, handle_value);
                    try
                    {
                        // Call LoadLibraryW with the path to the fake DLL name.
                        CallMethod(proc, load_lib, dllname_ptr);
                        // Call the DLL entry point.
                        CallMethod(proc, entry_point, WriteString(proc, argstr));
                    }
                    finally
                    {
                        // Restore the handle value.
                        proc.WriteMemory(handle_ptr, old_handle_value);
                    }
                    Console.WriteLine("Done");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
コード例 #11
0
 public void AddAttribute <T>(IntPtr attribute, T value) where T : struct
 {
     AddAttributeBuffer(attribute, _values.AddResource(value.ToBuffer()));
 }
コード例 #12
0
 public static SecBuffer Create(SecurityBufferType type, byte[] data, DisposableList list)
 {
     return(new SecBuffer(type, list.AddResource(new SafeHGlobalBuffer(data))));
 }
コード例 #13
0
 internal static List <SecBuffer> ToBufferList(this IEnumerable <SecurityBuffer> buffers, DisposableList list)
 {
     return(buffers.Select(b => list.AddResource(b.ToBuffer())).ToList());
 }
コード例 #14
0
        private SafeHGlobalBuffer GetAttributes(DisposableList <IDisposable> resources)
        {
            int count = GetAttributeCount();

            if (count == 0)
            {
                return(SafeHGlobalBuffer.Null);
            }

            var attr_list = resources.AddResource(new SafeProcThreadAttributeListBuffer(count));

            if (ParentProcess != null)
            {
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeParentProcess, ParentProcess.Handle.DangerousGetHandle());
            }

            if (MitigationOptions2 != ProcessMitigationOptions2.None)
            {
                MemoryStream stm    = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(stm);

                writer.Write((ulong)MitigationOptions);
                writer.Write((ulong)MitigationOptions2);
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeMitigationPolicy, stm.ToArray());
            }
            else if (MitigationOptions != ProcessMitigationOptions.None)
            {
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeMitigationPolicy, (ulong)MitigationOptions);
            }

            if (Win32kFilterFlags != Win32kFilterFlags.None)
            {
                Win32kFilterAttribute filter = new Win32kFilterAttribute
                {
                    Flags       = Win32kFilterFlags,
                    FilterLevel = Win32kFilterLevel
                };
                attr_list.AddAttributeBuffer(Win32ProcessAttributes.ProcThreadAttributeWin32kFilter, resources.AddResource(filter.ToBuffer()));
            }

            if ((CreationFlags & CreateProcessFlags.ProtectedProcess) != 0 && ProtectionLevel != ProtectionLevel.None)
            {
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeProtectionLevel, (int)ProtectionLevel);
            }

            if (InheritHandleList.Count > 0)
            {
                int total_size  = IntPtr.Size * InheritHandleList.Count;
                var handle_list = resources.AddResource(new SafeHGlobalBuffer(total_size));
                handle_list.WriteArray(0, InheritHandleList.ToArray(), 0, InheritHandleList.Count);
                attr_list.AddAttributeBuffer(Win32ProcessAttributes.ProcThreadAttributeHandleList, handle_list);
            }

            if (AppContainerSid != null)
            {
                SECURITY_CAPABILITIES caps = new SECURITY_CAPABILITIES
                {
                    AppContainerSid = resources.AddResource(AppContainerSid.ToSafeBuffer()).DangerousGetHandle()
                };

                if (Capabilities.Count > 0)
                {
                    SidAndAttributes[] cap_sids = new SidAndAttributes[Capabilities.Count];
                    for (int i = 0; i < Capabilities.Count; ++i)
                    {
                        cap_sids[i] = new SidAndAttributes()
                        {
                            Sid        = resources.AddResource(Capabilities[i].ToSafeBuffer()).DangerousGetHandle(),
                            Attributes = GroupAttributes.Enabled
                        };
                    }
                    SafeHGlobalBuffer cap_buffer = resources.AddResource(new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SidAndAttributes)) * Capabilities.Count));
                    cap_buffer.WriteArray(0, cap_sids, 0, cap_sids.Length);
                    caps.Capabilities    = cap_buffer.DangerousGetHandle();
                    caps.CapabilityCount = cap_sids.Length;
                }
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeSecurityCapabilities, caps);
            }

            if (LowPrivilegeAppContainer)
            {
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeAllApplicationPackagesPolicy, 1);
            }

            if (RestrictChildProcessCreation || OverrideChildProcessCreation)
            {
                int flags = RestrictChildProcessCreation ? 1 : 0;
                flags |= OverrideChildProcessCreation ? 2 : 0;

                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeChildProcessPolicy, flags);
            }

            if (DesktopAppBreakaway != ProcessDesktopAppBreakawayFlags.None)
            {
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeDesktopAppPolicy, (int)DesktopAppBreakaway);
            }

            if (!string.IsNullOrWhiteSpace(PackageName))
            {
                byte[] str_bytes     = Encoding.Unicode.GetBytes(PackageName);
                var    string_buffer = resources.AddResource(new SafeHGlobalBuffer(str_bytes));
                attr_list.AddAttributeBuffer(Win32ProcessAttributes.ProcThreadAttributePackageName, string_buffer);
            }

            if (PseudoConsole != IntPtr.Zero)
            {
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributePseudoConsole, PseudoConsole);
            }

            if (!string.IsNullOrEmpty(BnoIsolationPrefix))
            {
                var prefix = new BnoIsolationAttribute()
                {
                    IsolationEnabled = 1, IsolationPrefix = BnoIsolationPrefix
                };
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeBnoIsolation, prefix);
            }

            if (SafeOpenPromptOriginClaim != null)
            {
                var bytes = (byte[])SafeOpenPromptOriginClaim.Clone();
                Array.Resize(ref bytes, 524);
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeSafeOpenPromptOriginClaim, bytes);
            }

            if (ExtendedFlags != ProcessExtendedFlags.None)
            {
                attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeExtendedFlags, (int)ExtendedFlags);
            }

            return(attr_list);
        }
        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();
        }
        /// <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);
        }
コード例 #17
0
 internal static SafeAlpcMessageAttributesBuffer GetAttributesBuffer(this DisposableList list, IMessageAttributes attrs)
 {
     return(attrs == null ? SafeAlpcMessageAttributesBuffer.Null : list.AddResource(attrs.ToSafeBuffer()));
 }
コード例 #18
0
        private SafeHGlobalBuffer GetAttributes(DisposableList <IDisposable> resources)
        {
            int count = GetAttributeCount();

            if (count == 0)
            {
                return(SafeHGlobalBuffer.Null);
            }

            var attr_list = resources.AddResource(new SafeProcThreadAttributeListBuffer(count));

            if (ParentProcess != null)
            {
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeParentProcess, ParentProcess.Handle.DangerousGetHandle());
            }

            if (MitigationOptions2 != ProcessMitigationOptions2.None)
            {
                MemoryStream stm    = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(stm);

                writer.Write((ulong)MitigationOptions);
                writer.Write((ulong)MitigationOptions2);
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, stm.ToArray());
            }
            else if (MitigationOptions != ProcessMitigationOptions.None)
            {
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, (ulong)MitigationOptions);
            }

            if (Win32kFilterFlags != Win32kFilterFlags.None)
            {
                Win32kFilterAttribute filter = new Win32kFilterAttribute();
                filter.Flags       = Win32kFilterFlags;
                filter.FilterLevel = Win32kFilterLevel;
                attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeWin32kFilter, resources.AddResource(filter.ToBuffer()));
            }

            if ((CreationFlags & CreateProcessFlags.ProtectedProcess) != 0)
            {
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeProtectionLevel, (int)ProtectionLevel);
            }

            if (InheritHandleList.Count > 0)
            {
                int total_size  = IntPtr.Size * InheritHandleList.Count;
                var handle_list = resources.AddResource(new SafeHGlobalBuffer(total_size));
                handle_list.WriteArray(0, InheritHandleList.ToArray(), 0, InheritHandleList.Count);
                attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeHandleList, handle_list);
            }

            if (AppContainerSid != null)
            {
                SECURITY_CAPABILITIES caps = new SECURITY_CAPABILITIES();
                caps.AppContainerSid = resources.AddResource(AppContainerSid.ToSafeBuffer()).DangerousGetHandle();

                if (Capabilities.Count > 0)
                {
                    SidAndAttributes[] cap_sids = new SidAndAttributes[Capabilities.Count];
                    for (int i = 0; i < Capabilities.Count; ++i)
                    {
                        cap_sids[i] = new SidAndAttributes()
                        {
                            Sid        = resources.AddResource(Capabilities[i].ToSafeBuffer()).DangerousGetHandle(),
                            Attributes = GroupAttributes.Enabled
                        };
                    }
                    SafeHGlobalBuffer cap_buffer = resources.AddResource(new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SidAndAttributes)) * Capabilities.Count));
                    cap_buffer.WriteArray(0, cap_sids, 0, cap_sids.Length);
                    caps.Capabilities    = cap_buffer.DangerousGetHandle();
                    caps.CapabilityCount = cap_sids.Length;
                }
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeSecurityCapabilities, caps);
            }

            if (LowPrivilegeAppContainer)
            {
                attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeAllApplicationPackagesPolicy, 1);
            }

            return(attr_list);
        }
コード例 #19
0
 internal static SecBufferDesc ToDesc(this List <SecBuffer> buffers, DisposableList list)
 {
     return(list.AddResource(new SecBufferDesc(buffers.ToArray())));
 }