コード例 #1
0
 public NTStatus GetSecurityInformation(out SecurityDescriptor result, object handle, SecurityInformation securityInformation)
 {
     result = null;
     return(NTStatus.STATUS_NOT_SUPPORTED);
 }
        private void CheckAccess(TokenEntry token, ProcessDetails process, ThreadDetails thread, NtType type, AccessMask access_rights, SecurityDescriptor sd)
        {
            AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping);

            if (IsAccessGranted(granted_access, access_rights))
            {
                WriteAccessCheckResult(process, thread, granted_access, type.GenericMapping, sd, token.Information);
            }
        }
コード例 #3
0
 /// <summary>
 /// Display the edit security dialog.
 /// </summary>
 /// <param name="hwnd">Parent window handle.</param>
 /// <param name="name">The name of the object to display.</param>
 /// <param name="sd">The security descriptor to display.</param>
 /// <param name="type">The NT type of the object.</param>
 public static void EditSecurity(IntPtr hwnd, string name, SecurityDescriptor sd, NtType type)
 {
     EditSecurity(hwnd, name, sd, type.AccessRightsType, type.ValidAccess, type.GenericMapping);
 }
        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 <RunningService>    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(AccessRights);

                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);
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Set security using a named object.
 /// </summary>
 /// <param name="name">The name of the object.</param>
 /// <param name="type">The type of named object.</param>
 /// <param name="security_information">The security information to set.</param>
 /// <param name="security_descriptor">The security descriptor to set.</param>
 /// <returns>The Win32 Error Code.</returns>
 public static void SetSecurityInfo(string name, SeObjectType type,
                                    SecurityInformation security_information,
                                    SecurityDescriptor security_descriptor)
 {
     SetSecurityInfo(name, type, security_information, security_descriptor, true);
 }
 /// <summary>
 /// Set security using an object handle.
 /// </summary>
 /// <param name="obj">The handle of the object.</param>
 /// <param name="type">The type of object.</param>
 /// <param name="security_information">The security information to set.</param>
 /// <param name="security_descriptor">The security descriptor to set.</param>
 /// <param name="throw_on_error">True to throw on error.</param>
 /// <returns>The NT status code.</returns>
 public static NtStatus SetSecurityInfo(NtObject obj, SeObjectType type,
                                        SecurityInformation security_information,
                                        SecurityDescriptor security_descriptor, bool throw_on_error)
 {
     return(SetSecurityInfo(obj.Handle, type, security_information, security_descriptor, throw_on_error));
 }
 internal void WriteAccessCheckResult(string name, string type_name, AccessMask granted_access,
                                      GenericMapping generic_mapping, SecurityDescriptor sd, Type enum_type, bool is_directory, TokenInformation token_info)
 {
     WriteObject(new AccessCheckResult(name, type_name, granted_access, generic_mapping,
                                       sd, enum_type, is_directory, token_info));
 }
コード例 #8
0
 public void SetSecurityInformation(SecurityDescriptor securityDescriptor)
 {
     OutputBuffer = securityDescriptor.GetBytes();
 }
 /// <summary>
 /// Add a remote user ID security descriptor condition.
 /// </summary>
 /// <param name="match_type">The match type for the condition.</param>
 /// <param name="security_descriptor">The security descriptor.</param>
 public void AddRemoteUserId(FirewallMatchType match_type, SecurityDescriptor security_descriptor)
 {
     AddCondition(match_type, FirewallConditionGuids.FWPM_CONDITION_ALE_REMOTE_USER_ID,
                  FirewallValue.FromSecurityDescriptor(security_descriptor));
 }
コード例 #10
0
        internal ServiceInformation(string machine_name, string name, SecurityDescriptor sd,
                                    IEnumerable <ServiceTriggerInformation> triggers, ServiceSidType sid_type,
                                    ServiceLaunchProtectedType launch_protected, IEnumerable <string> required_privileges,
                                    SafeStructureInOutBuffer <QUERY_SERVICE_CONFIG> config, bool delayed_auto_start)
        {
            Name = name;
            SecurityDescriptor = sd;
            Triggers           = triggers;
            SidType            = sid_type;
            LaunchProtected    = launch_protected;
            RequiredPrivileges = required_privileges;

            if (config == null)
            {
                BinaryPathName   = string.Empty;
                LoadOrderGroup   = string.Empty;
                Dependencies     = new string[0];
                DisplayName      = string.Empty;
                ServiceStartName = string.Empty;
                return;
            }

            var result = config.Result;

            ServiceType      = result.dwServiceType;
            StartType        = result.dwStartType;
            ErrorControl     = result.dwErrorControl;
            BinaryPathName   = result.lpBinaryPathName.GetString();
            LoadOrderGroup   = result.lpLoadOrderGroup.GetString();
            TagId            = result.dwTagId;
            Dependencies     = result.lpLoadOrderGroup.GetMultiString();
            DisplayName      = result.lpDisplayName.GetString();
            ServiceStartName = result.lpServiceStartName.GetString();
            DelayedAutoStart = delayed_auto_start;
            MachineName      = machine_name ?? string.Empty;
            ImagePath        = string.Empty;
            ServiceDll       = string.Empty;
            ServiceHostType  = string.Empty;
            ServiceMain      = string.Empty;

            // TODO: Maybe try and query using remote registry service?
            if (!string.IsNullOrEmpty(MachineName))
            {
                return;
            }
            ImagePath = Win32Utils.GetImagePathFromCommandLine(BinaryPathName);
            using (RegistryKey key = OpenKeySafe(Registry.LocalMachine, $@"SYSTEM\CurrentControlSet\Services\{Name}"))
            {
                if (key != null)
                {
                    UserName   = ReadStringFromKey(key, null, "ObjectName");
                    ServiceDll = ReadStringFromKey(key, "Parameters", "ServiceDll");
                    if (string.IsNullOrEmpty(ServiceDll))
                    {
                        ServiceDll = ReadStringFromKey(key, null, "ServiceDll");
                    }

                    if (!string.IsNullOrEmpty(ServiceDll))
                    {
                        string[] args = Win32Utils.ParseCommandLine(BinaryPathName);
                        for (int i = 0; i < args.Length - 1; ++i)
                        {
                            if (args[i] == "-k")
                            {
                                ServiceHostType = args[i + 1];
                                break;
                            }
                        }

                        ServiceMain = ReadStringFromKey(key, "Parameters", "ServiceMain");
                        if (string.IsNullOrEmpty(ServiceMain))
                        {
                            ServiceMain = "ServiceMain";
                        }
                    }

                    if (key.GetValue("SvcHostSplitDisable") is int disable)
                    {
                        SvcHostSplitDisabled = disable != 0;
                    }
                }
            }
        }
        /// <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);
        }
コード例 #12
0
 public NTStatus SetSecurityInformation(object handle, SecurityInformation securityInformation, SecurityDescriptor securityDescriptor)
 {
     // [MS-FSA] If the object store does not implement security, the operation MUST be failed with STATUS_INVALID_DEVICE_REQUEST.
     return(NTStatus.STATUS_INVALID_DEVICE_REQUEST);
 }
コード例 #13
0
 public NTStatus GetSecurityInformation(out SecurityDescriptor result, object handle, SecurityInformation securityInformation)
 {
     result = null;
     return(NTStatus.STATUS_INVALID_DEVICE_REQUEST);
 }
コード例 #14
0
ファイル: PipeServer.cs プロジェクト: uw-it-cte/fog-client
 private static extern bool SetSecurityDescriptorDacl(ref SecurityDescriptor sd, bool bDaclPresent, IntPtr dacl,
     bool bDaclDefaulted);
コード例 #15
0
 internal TokenAccessCheckResult(NtToken token, string process_name, string image_path, int process_id,
                                 string command_line, AccessMask granted_access, SecurityDescriptor sd,
                                 TokenInformation token_info) : base(token.ToString(), token.NtType.Name, granted_access, token.NtType.GenericMapping, sd,
                                                                     token.NtType.AccessRightsType, false, token_info)
 {
     ProcessName        = process_name;
     ProcessImagePath   = image_path;
     ProcessId          = process_id;
     ProcessCommandLine = command_line;
     ProcessTokenInfo   = new TokenInformation(token);
 }
コード例 #16
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());
        }
コード例 #17
0
 internal ServiceInformation(string name, SecurityDescriptor sd, IEnumerable <ServiceTriggerInformation> triggers)
 {
     Name = name;
     SecurityDescriptor = sd;
     Triggers           = triggers;
 }
コード例 #18
0
ファイル: EntryPoint.cs プロジェクト: wgwjifeng/oleviewdotnet
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static void Main(string[] args)
        {
            string                      database_file            = null;
            string                      save_file                = null;
            bool                        do_enum                  = false;
            bool                        enum_clsid               = false;
            bool                        enum_runtime             = false;
            bool                        show_help                = false;
            bool                        query_interfaces         = false;
            int                         concurrent_queries       = Environment.ProcessorCount;
            bool                        refresh_interfaces       = false;
            bool                        enable_activation_filter = false;
            string                      symbol_dir               = null;
            bool                        delete_database          = false;
            string                      view_access_sd           = null;
            string                      view_launch_sd           = null;
            string                      view_name                = null;
            COMRegistryMode             mode         = COMRegistryMode.Merged;
            IEnumerable <COMServerType> server_types = new COMServerType[] { COMServerType.InProcHandler32, COMServerType.InProcServer32, COMServerType.LocalServer32 };

            OptionSet opts = new OptionSet()
            {
                { "i|in=", "Open a database file.", v => database_file = v },
                { "o|out=", "Save database and exit.", v => save_file = v },
                { "e|enum", "Enumerate the provided CLSID (GUID).", v => enum_clsid = v != null },
                { "r|rt", "Enumerate the provided Runtime Class.", v => enum_runtime = v != null },
                { "q|query", "Query all interfaces for database", v => query_interfaces = v != null },
                { "c|conn=", "Number of concurrent interface queries", v => concurrent_queries = int.Parse(v) },
                { "s|server=", "Specify server types for query", v => server_types = ParseServerTypes(v) },
                { "refresh", "Refresh interfaces in query", v => refresh_interfaces = v != null },
                { "m", "Loading mode is machine only.", v => mode = COMRegistryMode.MachineOnly },
                { "u", "Loading mode is user only.", v => mode = COMRegistryMode.UserOnly },
                { "a", "Enable activation filter.", v => enable_activation_filter = v != null },
                { "g=", "Generate a symbol file in the specified directory.", v => symbol_dir = v },
                { "d", "Delete the input database once loaded", v => delete_database = v != null },
                { "v=", "View a COM access security descriptor (specify the SDDL)", v => view_access_sd = v },
                { "l=", "View a COM launch security descriptor (specify the SDDL)", v => view_launch_sd = v },
                { "n=", "Name any simple form display such as security descriptor", v => view_name = v },
                { "h|help", "Show this message and exit.", v => show_help = v != null },
            };

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

            try
            {
                additional_args = opts.Parse(args);
            }
            catch
            {
                show_help = true;
            }

            do_enum = enum_clsid || enum_runtime;

            if (show_help || (do_enum && additional_args.Count < 4) || (symbol_dir != null && !Directory.Exists(symbol_dir)))
            {
                StringWriter writer = new StringWriter();
                writer.WriteLine("Usage: OleViewDotNet [options] [enum args]");
                writer.WriteLine();
                writer.WriteLine("Options:");
                opts.WriteOptionDescriptions(writer);
                MessageBox.Show(writer.ToString(), "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Environment.Exit(1);
            }

            if (do_enum)
            {
                try
                {
                    Environment.Exit(EnumInterfaces(new Queue <string>(additional_args), enum_runtime));
                }
                catch
                {
                    Environment.Exit(42);
                }
            }
            else if (symbol_dir != null)
            {
                try
                {
                    COMUtilities.GenerateSymbolFile(symbol_dir,
                                                    Environment.Is64BitProcess ? Properties.Settings.Default.DbgHelpPath64 : Properties.Settings.Default.DbgHelpPath32, Properties.Settings.Default.SymbolPath);
                    Environment.Exit(0);
                }
                catch (Exception)
                {
                    Environment.Exit(1);
                }
            }
            else
            {
                AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                try
                {
                    if (view_access_sd != null || view_launch_sd != null)
                    {
                        bool access                     = view_access_sd != null;
                        SecurityDescriptor sd           = new SecurityDescriptor(view_access_sd ?? view_launch_sd);
                        AccessMask         valid_access = access ? 0x7 : 0x1F;

                        SecurityDescriptorViewerControl control = new SecurityDescriptorViewerControl();
                        DocumentForm frm   = new DocumentForm(control);
                        string       title = $"{(access ? "Access Security" : "Launch Security")}";
                        if (!string.IsNullOrWhiteSpace(view_name))
                        {
                            title = $"{view_name} {title}";
                        }
                        frm.Text = title;
                        control.SetSecurityDescriptor(sd, typeof(COMAccessRights), new GenericMapping()
                        {
                            GenericExecute = valid_access,
                            GenericRead    = valid_access,
                            GenericWrite   = valid_access,
                            GenericAll     = valid_access
                        }, valid_access);
                        Application.Run(frm);
                        return;
                    }

                    COMRegistry registry = database_file != null?COMUtilities.LoadRegistry(null, database_file)
                                               : COMUtilities.LoadRegistry(null, mode);

                    if (delete_database && database_file != null)
                    {
                        File.Delete(database_file);
                    }

                    if (query_interfaces)
                    {
                        if (!COMUtilities.QueryAllInterfaces(null, registry.Clsids.Values, server_types, concurrent_queries, refresh_interfaces))
                        {
                            Environment.Exit(1);
                        }
                    }

                    if (save_file != null)
                    {
                        registry.Save(save_file);
                        Environment.Exit(0);
                    }

                    _appContext = new MultiApplicationContext(new MainForm(registry));
                    if (enable_activation_filter)
                    {
                        COMUtilities.CoRegisterActivationFilter(new ActivationFilter());
                    }
                    Application.Run(_appContext);
                }
                catch (Exception ex)
                {
                    if (!(ex is OperationCanceledException))
                    {
                        ShowError(null, ex);
                    }
                }
            }
        }
コード例 #19
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>
 /// <returns>The list of access check results.</returns>
 /// <remarks>The list of object types is restricted to 256 entries for remote access checks.</remarks>
 public AuthZAccessCheckResult[] AccessCheck(SecurityDescriptor sd, IEnumerable <SecurityDescriptor> optional_sd,
                                             AccessMask desired_access, Sid principal, IEnumerable <ObjectTypeEntry> object_types, NtType type)
 {
     return(AccessCheck(sd, optional_sd, desired_access, principal, object_types, type, true).Result);
 }
 /// <summary>
 /// Set security using an object handle.
 /// </summary>
 /// <param name="handle">The handle of the object.</param>
 /// <param name="type">The type of object.</param>
 /// <param name="security_information">The security information to set.</param>
 /// <param name="security_descriptor">The security descriptor to set.</param>
 public static void SetSecurityInfo(SafeHandle handle, SeObjectType type,
                                    SecurityInformation security_information,
                                    SecurityDescriptor security_descriptor)
 {
     SetSecurityInfo(handle, type, security_information, security_descriptor, true);
 }
コード例 #21
0
 internal TokenAccessCheckResult(NtToken token, NtProcess process, AccessMask granted_access, SecurityDescriptor sd,
                                 TokenInformation token_info)
     : base($"{process.Name}:{process.ProcessId}", token.NtType.Name, granted_access, token.NtType.GenericMapping, sd,
            token.NtType.AccessRightsType, false, token_info)
 {
     ProcessTokenInfo = new ProcessTokenInformation(token, process);
 }
 /// <summary>
 /// Set security using an object handle.
 /// </summary>
 /// <param name="obj">The handle of the object.</param>
 /// <param name="type">The type of object.</param>
 /// <param name="security_information">The security information to set.</param>
 /// <param name="security_descriptor">The security descriptor to set.</param>
 public static void SetSecurityInfo(NtObject obj, SeObjectType type,
                                    SecurityInformation security_information,
                                    SecurityDescriptor security_descriptor)
 {
     SetSecurityInfo(obj, type, security_information, security_descriptor, true);
 }
コード例 #23
0
        private void CheckAccess(TokenEntry token, NtObject obj, NtType type, AccessMask access_rights, SecurityDescriptor sd)
        {
            AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping);

            if (IsAccessGranted(granted_access, access_rights))
            {
                WriteAccessCheckResult(ConvertPath(obj), type.Name, granted_access, type.GenericMapping,
                                       sd.ToSddl(), type.AccessRightsType, token.Information);
            }
        }
 private protected override void WriteAccessCheckResult(string name, string type_name, AccessMask granted_access, GenericMapping generic_mapping, SecurityDescriptor sd, Type enum_type, bool is_directory, TokenInformation token_info)
 {
     _cmdlet.WriteAccessCheckResult(name, type_name, granted_access, generic_mapping, sd, enum_type, is_directory, token_info);
 }
        private void CheckAccess(TokenEntry token, NtKey key, AccessMask access_rights, SecurityDescriptor sd)
        {
            NtType     type           = key.NtType;
            AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping);

            if (IsAccessGranted(granted_access, access_rights))
            {
                WriteAccessCheckResult(FormatWin32Path ? key.Win32Path : key.FullPath, type.Name, granted_access, type.GenericMapping,
                                       sd, typeof(KeyAccessRights), true, token.Information);
            }
        }
コード例 #26
0
 private object DoCreateObject(string path, AttributeFlags attributes, NtObject root, SecurityQualityOfService security_quality_of_service, SecurityDescriptor security_descriptor)
 {
     using (ObjectAttributes obja = new ObjectAttributes(path, attributes, root, security_quality_of_service, security_descriptor))
     {
         return(CreateObject(obja));
     }
 }
        private void CheckAccess(TokenEntry token, NtFile file, AccessMask access_rights, SecurityDescriptor sd, SecurityDescriptor parent_sd)
        {
            NtType     type           = file.NtType;
            AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping);

            // Determine if the parent gives additonal rights to this file.
            if (!granted_access.IsAllAccessGranted(FileDirectoryAccessRights.ListDirectory | FileDirectoryAccessRights.Delete) && parent_sd != null)
            {
                AccessMask parent_granted_access = NtSecurity.GetMaximumAccess(parent_sd, token.Token, type.GenericMapping);
                if (parent_granted_access.IsAccessGranted(FileDirectoryAccessRights.DeleteChild))
                {
                    granted_access |= FileAccessRights.Delete;
                }
                if (parent_granted_access.IsAccessGranted(FileDirectoryAccessRights.ListDirectory))
                {
                    granted_access |= FileAccessRights.ReadAttributes;
                }
            }

            if (IsAccessGranted(granted_access, access_rights))
            {
                bool is_directory = IsDirectoryNoThrow(file);
                WriteAccessCheckResult(FormatWin32Path ? file.Win32PathName : file.FullPath, type.Name, granted_access, type.GenericMapping,
                                       sd, is_directory ? typeof(FileDirectoryAccessRights) : typeof(FileAccessRights), is_directory, token.Information);
            }
        }
コード例 #28
0
 public NTStatus SetSecurityInformation(object handle, SecurityInformation securityInformation, SecurityDescriptor securityDescriptor)
 {
     return(NTStatus.STATUS_NOT_SUPPORTED);
 }
        private void DumpFile(IEnumerable <TokenEntry> tokens, AccessMask access_rights, AccessMask dir_access_rights, SecurityDescriptor parent_sd, NtFile file)
        {
            bool directory = IsDirectoryNoThrow(file);

            if (CheckMode != FileCheckMode.All)
            {
                if ((CheckMode == FileCheckMode.FilesOnly && directory) ||
                    (CheckMode == FileCheckMode.DirectoriesOnly && !directory))
                {
                    return;
                }
            }
            AccessMask desired_access = directory ? dir_access_rights : access_rights;

            var result = file.GetSecurityDescriptor(SecurityInformation.AllBasic, false);

            if (result.IsSuccess)
            {
                foreach (var token in tokens)
                {
                    CheckAccess(token, file, desired_access, result.Result, parent_sd);
                }
            }
            else
            {
                // If we can't read security descriptor then try opening the key.
                foreach (var token in tokens)
                {
                    CheckAccessUnderImpersonation(token, desired_access, file);
                }
            }
        }
コード例 #30
0
ファイル: PipeServer.cs プロジェクト: uw-it-cte/fog-client
 private static extern bool InitializeSecurityDescriptor(out SecurityDescriptor sd, int dwRevision);
 internal ScheduledTaskEntry(ITaskFolder folder)
 {
     Folder             = true;
     SecurityDescriptor = SecurityDescriptor.Parse(folder.GetSecurityDescriptor((int)SecurityInformation.AllBasic), false).GetResultOrDefault();
     Path = folder.Path;
 }
コード例 #32
0
ファイル: HttpApi.cs プロジェクト: garyjohnson/Remotive
        public void SetHttpNamespaceAcl(string urlPrefix, SecurityDescriptor acl)
        {
            HTTP_SERVICE_CONFIG_URLACL_SET urlAclConfig = new HTTP_SERVICE_CONFIG_URLACL_SET();
            urlAclConfig.KeyDesc.pUrlPrefix = urlPrefix;
            urlAclConfig.ParamDesc.pStringSecurityDescriptor = acl.ToString();

            IntPtr pUrlAclConfig = Marshal.AllocHGlobal(Marshal.SizeOf(urlAclConfig));

            Marshal.StructureToPtr(urlAclConfig, pUrlAclConfig, false);

            try
            {
                uint retval = HttpApi.HttpSetServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigUrlAclInfo, pUrlAclConfig, (uint)Marshal.SizeOf(urlAclConfig), IntPtr.Zero);

                if (retval != 0)
                {
                    throw new ExternalException("Error Setting Configuration: " + Util.GetErrorMessage(retval));
                }
            }
            finally
            {
                if (pUrlAclConfig != IntPtr.Zero)
                {
                    Marshal.DestroyStructure(pUrlAclConfig, typeof(HTTP_SERVICE_CONFIG_URLACL_SET));
                    Marshal.FreeHGlobal(pUrlAclConfig); ;
                }
            }
        }
コード例 #33
0
ファイル: CustomAction.cs プロジェクト: garyjohnson/Remotive
        public static ActionResult AddNamespace(Session session)
        {
            session.Log("Begin AddNamespace");
            HttpApi nsManager = null;
            try
            {
                nsManager = new HttpApi();
                List<SecurityIdentity> userList = new List<SecurityIdentity>();
                Dictionary<string, SecurityDescriptor> nsTable = nsManager.QueryHttpNamespaceAcls();

                string url = "http://+:8888/";

                SecurityDescriptor newSd = new SecurityDescriptor();
                newSd.DACL = new AccessControlList();
                foreach (AccessControlEntry ace in newSd.DACL)
                {
                    if (!userList.Contains(ace.AccountSID))
                    {
                        userList.Add(ace.AccountSID);
                    }
                }

                try
                {
                    SecurityIdentity sid = SecurityIdentity.SecurityIdentityFromWellKnownSid(WELL_KNOWN_SID_TYPE.WinWorldSid);
                    if (!userList.Contains(sid))
                    {
                        AccessControlEntry ace = new AccessControlEntry(sid);
                        ace.AceType = AceType.AccessAllowed;
                        ace.Add(AceRights.GenericAll);
                        ace.Add(AceRights.GenericExecute);
                        ace.Add(AceRights.GenericRead);
                        ace.Add(AceRights.GenericWrite);
                        newSd.DACL.Add(ace);
                        userList.Add(sid);
                    }
                }
                catch (Exception ex)
                {
                    session.Log("User or group name was not found. " + ex.Message);
                    return ActionResult.Failure;
                }

                // If entry already exists, rebuild it
                // as security settings could be wrong
                if (nsTable.ContainsKey(url))
                {
                    AccessControlList original = nsTable[url].DACL;
                    bool removed = false;

                    try
                    {
                        nsManager.RemoveHttpHamespaceAcl(url);
                        removed = true;
                        nsTable[url].DACL = newSd.DACL;
                        nsManager.SetHttpNamespaceAcl(url, nsTable[url]);
                    }
                    catch (Exception ex)
                    {
                        session.Log("Error Setting ACL. " + ex.Message);
                        if (removed)
                        {
                            try
                            {
                                nsTable[url].DACL = original;
                                nsManager.SetHttpNamespaceAcl(url, nsTable[url]);
                            }
                            catch (Exception ex2)
                            {
                                session.Log("Unable to Restore Original ACL, ACL may be corrupt. " + ex2.Message);
                                return ActionResult.Failure;
                            }
                        }

                        session.Log("Original ACL restored.");
                        return ActionResult.Failure;
                    }
                }
                else
                {
                    try
                    {
                        nsManager.SetHttpNamespaceAcl(url, newSd);
                        nsTable.Add(url, newSd);
                    }
                    catch (Exception ex)
                    {
                        session.Log("Error Adding ACL. " + ex.Message);
                        return ActionResult.Failure;
                    }
                }

                return ActionResult.Success;
            }
            finally
            {
                if (nsManager != null)
                {
                    nsManager.Dispose();
                }
            }
        }
コード例 #34
0
ファイル: ShareService.cs プロジェクト: KilianTarb/KNet
 /// <summary>
 /// Sets the share's info.
 /// </summary>
 /// <param name="ShareName"></param>
 /// <param name="MaximumAllowed"></param>
 /// <param name="Description"></param>
 /// <param name="Access"></param>
 public void SetShareInfo(string ShareName, uint MaximumAllowed, string Description, SecurityDescriptor Access)
 {
     ManagementBaseObject inParams = _shareClass.GetMethodParameters("SetShareInfo");
 }
コード例 #35
-1
ファイル: MainForm.cs プロジェクト: garyjohnson/Remotive
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty((string)listHttpNamespaces.SelectedItem))
            {
                Elevate(NamespaceManagerAction.Add, (string)listHttpNamespaces.SelectedItem);

                string url;

                InputBox.Show("Enter URL", "Enter the URL to add:", out url);

                if (!String.IsNullOrEmpty(url))
                {
                    SecurityDescriptor newSd = new SecurityDescriptor();
                    newSd.DACL = new AccessControlList();

                    AccessControlListDialog aclDlg = new AccessControlListDialog(url,
                        newSd.DACL,
                        new List<AceRights>(new AceRights[] { AceRights.GenericAll, AceRights.GenericExecute, AceRights.GenericRead, AceRights.GenericWrite }),
                        new List<AceType>(new AceType[] { AceType.AccessAllowed }));

                    if (aclDlg.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            this.nsManager.SetHttpNamespaceAcl(url, newSd);
                            this.nsTable.Add(url, newSd);
                            this.listHttpNamespaces.Items.Add(url);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error Adding ACL. " + ex.Message, "Error Adding ACL", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }