Пример #1
0
 static void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow)
 {
     FileSecurity sec = File.GetAccessControl(filepath);
     SecurityIdentifier sid = new SecurityIdentifier(sidType, null);
     sec.PurgeAccessRules(sid); //remove existing
     sec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow));
     File.SetAccessControl(filepath, sec);
 }
Пример #2
0
		public static WellKnownAccount LookupByType (WellKnownSidType sidType)
		{
			foreach (var acct in accounts) {
				if (acct.WellKnownValue == sidType)
					return acct;
			}
			
			return null;
		}
 private static byte[] CreateWellKnownSid(WellKnownSidType sidType)
 {
     uint maxBinaryLength = (uint) SecurityIdentifier.MaxBinaryLength;
     byte[] resultSid = new byte[maxBinaryLength];
     if (System.Data.Common.UnsafeNativeMethods.CreateWellKnownSid((int) sidType, null, resultSid, ref maxBinaryLength) == 0)
     {
         IntegratedSecurityError(5);
     }
     return resultSid;
 }
        static private byte[] CreateWellKnownSid(WellKnownSidType sidType) {
            // Passing an array as big as it can ever be is a small price to pay for
            // not having to P/Invoke twice (once to get the buffer, once to get the data)

            uint length = ( uint )SecurityIdentifier.MaxBinaryLength;
            byte[] resultSid = new byte[ length ];

            // NOTE - We copied this code from System.Security.Principal.Win32.CreateWellKnownSid...

            if ( 0 == UnsafeNativeMethods.CreateWellKnownSid(( int )sidType, null, resultSid, ref length )) {
                IntegratedSecurityError(Win32_CreateWellKnownSid);
            }
            return resultSid;
        }
Пример #5
0
        public bool IsWellKnown(WellKnownSidType type)
        {
            WellKnownAccount acct = WellKnownAccount.LookupByType(type);

            if (acct == null)
            {
                return(false);
            }

            string sid = Value;

            if (acct.IsAbsolute)
            {
                return(sid == acct.Sid);
            }

            return(sid.StartsWith("S-1-5-21", StringComparison.OrdinalIgnoreCase) &&
                   sid.EndsWith("-" + acct.Rid, StringComparison.OrdinalIgnoreCase));
        }
Пример #6
0
        // ============ Part 5 – Put it all together ==========

        //private void ProtectProcess()
        //{
        //    // Get the current process handle
        //    IntPtr hProcess = GetCurrentProcess();

        //    // Read the DACL
        //    var dacl = GetProcessSecurityDescriptor(hProcess);

        //    // Insert the new ACE
        //    dacl.DiscretionaryAcl.InsertAce(
        //        0,
        //        new CommonAce(
        //            AceFlags.None,
        //            AceQualifier.AccessDenied,
        //            (int)ProcessAccessRights.PROCESS_ALL_ACCESS,
        //            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
        //            false,
        //            null
        //        )
        //    );
        //    // Save the DACL
        //    SetProcessSecurityDescriptor(hProcess, dacl);
        //}


        // ============ Additions: ==========

        public static void ProtectProcess(IntPtr hProcess, WellKnownSidType sid = WellKnownSidType.WorldSid)
        {
            // Read the DACL
            var dacl = GetProcessSecurityDescriptor(hProcess);

            // Insert the new ACE
            dacl.DiscretionaryAcl.InsertAce(
                0,
                new CommonAce(
                    AceFlags.None,
                    AceQualifier.AccessDenied,
                    (int)ProcessAccessRights.PROCESS_ALL_ACCESS,
                    new SecurityIdentifier(sid, null),
                    false,
                    null
                    )
                );

            // Save the DACL
            SetProcessSecurityDescriptor(hProcess, dacl);
        }
Пример #7
0
        public static void RemoveOUSecurityfromSid(string ouPath, WellKnownSidType UserSid, ActiveDirectoryRights rights, AccessControlType type, ActiveDirectorySecurityInheritance inheritance)
        {
            DirectoryEntry ou = GetADObject(ouPath);


            SecurityIdentifier identity = null;

            identity = new SecurityIdentifier(UserSid, null);

            ActiveDirectoryAccessRule ruleRead = new ActiveDirectoryAccessRule(
                identity,
                rights,
                type,
                inheritance
                );



            ou.ObjectSecurity.RemoveAccessRule(ruleRead);
            ou.CommitChanges();
            ou.Close();
        }
Пример #8
0
        private static NativeMethods.SECURITY_ATTRIBUTES CreateSecurityAttributes(WellKnownSidType sidType)
        {
            // Grant access to Network Service.
            SecurityIdentifier networkService = new SecurityIdentifier(sidType, null);
            DiscretionaryAcl   dacl           = new DiscretionaryAcl(false, false, 1);

            dacl.AddAccess(AccessControlType.Allow, networkService, -1, InheritanceFlags.None, PropagationFlags.None);
            CommonSecurityDescriptor csd = new CommonSecurityDescriptor(false, false, ControlFlags.DiscretionaryAclPresent | ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted, null, null, null, dacl);

            byte[] buffer = new byte[csd.BinaryLength];
            csd.GetBinaryForm(buffer, 0);

            IntPtr dest = Marshal.AllocHGlobal(buffer.Length);

            Marshal.Copy(buffer, 0, dest, buffer.Length);

            NativeMethods.SECURITY_ATTRIBUTES sa = new NativeMethods.SECURITY_ATTRIBUTES();
            sa.nLength = Marshal.SizeOf(sa);
            sa.lpSecurityDescriptor = dest;

            return(sa);
        }
Пример #9
0
        public void SetPermissions(string filename, WellKnownSidType accountSid, FileSystemRights rights, AccessControlType controlType)
        {
            try
            {
                var sid = new SecurityIdentifier(accountSid, null);

                var directoryInfo     = new DirectoryInfo(filename);
                var directorySecurity = directoryInfo.GetAccessControl();

                var accessRule = new FileSystemAccessRule(sid, rights,
                                                          InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                          PropagationFlags.None, controlType);

                directorySecurity.AddAccessRule(accessRule);
                directoryInfo.SetAccessControl(directorySecurity);
            }
            catch (Exception e)
            {
                Logger.WarnException(string.Format("Couldn't set permission for {0}. account:{1} rights:{2} accessControlType:{3}", filename, accountSid, rights, controlType), e);
                throw;
            }
        }
        public static SecurityIdentifier FromWellKnown(WellKnownSidType type)
        {
            uint size      = MaxBinaryLength * sizeof(byte);
            var  resultSid = Marshal.AllocHGlobal((int)size);

            try
            {
                if (!NativeMethods.CreateWellKnownSid((int)type, IntPtr.Zero, resultSid, ref size))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                return(new SecurityIdentifier(resultSid));
            }
            finally
            {
                if (resultSid != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(resultSid);
                }
            }
        }
        public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
        {
            switch (sidType)
            {
                case WellKnownSidType.AccountComputersSid: //append 515
                    _sidStr = string.Concat(domainSid.Value, "-515");

                    break;

                case WellKnownSidType.AccountDomainUsersSid: //append 513
                    _sidStr = string.Concat(domainSid.Value, "-513");

                    break;

                default:
                    _sidStr = domainSid.Value;
                    // TODO
                    break;
            }
            _AccountDomainSid = domainSid.Value;
            _sidbytes = this.StringToBytes();
            _bytelength = _sidbytes.Length;
        }
Пример #12
0
        public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
        {
            switch (sidType)
            {
            case WellKnownSidType.AccountComputersSid:     //append 515
                _sidStr = string.Concat(domainSid.Value, "-515");

                break;

            case WellKnownSidType.AccountDomainUsersSid:     //append 513
                _sidStr = string.Concat(domainSid.Value, "-513");

                break;

            default:
                _sidStr = domainSid.Value;
                // TODO
                break;
            }
            _AccountDomainSid = domainSid.Value;
            _sidbytes         = this.StringToBytes();
            _bytelength       = _sidbytes.Length;
        }
Пример #13
0
        public void SetPermissions(string filename, WellKnownSidType accountSid, FileSystemRights rights, AccessControlType controlType)
        {
            try
            {
                var sid = new SecurityIdentifier(accountSid, null);

                var directoryInfo     = _fileSystem.DirectoryInfo.FromDirectoryName(filename);
                var directorySecurity = directoryInfo.GetAccessControl(AccessControlSections.Access);

                var rules = directorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));

                if (rules.OfType <FileSystemAccessRule>().Any(acl => acl.AccessControlType == controlType && (acl.FileSystemRights & rights) == rights && acl.IdentityReference.Equals(sid)))
                {
                    return;
                }

                var accessRule = new FileSystemAccessRule(sid,
                                                          rights,
                                                          InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                          PropagationFlags.InheritOnly,
                                                          controlType);

                bool modified;
                directorySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out modified);

                if (modified)
                {
                    directoryInfo.SetAccessControl(directorySecurity);
                }
            }
            catch (Exception e)
            {
                Logger.Warn(e, "Couldn't set permission for {0}. account:{1} rights:{2} accessControlType:{3}", filename, accountSid, rights, controlType);
                throw;
            }
        }
Пример #14
0
        public InjectionEntryPoint(EasyHook.RemoteHooking.IContext contex, string channelName)
        {
            /// IPC Client   客户端可以发消息到服务端
            /// ------------------------------------------------------
            _serverInterface = EasyHook.RemoteHooking.IpcConnectClient <ServerInterface>(channelName);
            _serverInterface.Ping();
            /// ------------------------------------------------------

            /// IPC Server  启动一个Server端,用于接入控制台发送的指令
            /// security identifiers (SIDs)
            /// ------------------------------------------------------
            WellKnownSidType[] InAllowedClientSIDs = new WellKnownSidType[] { WellKnownSidType.WorldSid };
            string             channelNameDll      = "CommandChannela";

            _commandInterface = new CommandInterface();

            EasyHook.RemoteHooking.IpcCreateServer(
                ref channelNameDll,
                System.Runtime.Remoting.WellKnownObjectMode.Singleton,
                _commandInterface,
                InAllowedClientSIDs
                );
            /// ------------------------------------------------------
        }
        /// <summary> Grants the user FullControl for the file, returns true if modified, false if already present </summary>
        public static bool GrantFullControlForFile(string filepath, WellKnownSidType sidType, SecurityIdentifier domain)
        {
            FileSecurity       sec = File.GetAccessControl(filepath);
            SecurityIdentifier sid = new SecurityIdentifier(sidType, domain);
            bool found             = false;

            List <FileSystemAccessRule> toremove = new List <FileSystemAccessRule>();

            foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, false, typeof(SecurityIdentifier)))
            {
                if (sid.Value == rule.IdentityReference.Value)
                {
                    if (rule.AccessControlType != AccessControlType.Allow || rule.FileSystemRights != FileSystemRights.FullControl)
                    {
                        toremove.Add(rule);
                    }
                    else
                    {
                        found = true;
                    }
                }
            }
            if (!found || toremove.Count > 0)
            {
                foreach (FileSystemAccessRule bad in toremove)
                {
                    sec.RemoveAccessRule(bad);
                }

                sec.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow));
                File.SetAccessControl(filepath, sec);
                return(true);
            }

            return(false);
        }
Пример #16
0
        public SecurityIdentifier(WellKnownSidType sidType,
                                  SecurityIdentifier domainSid)
        {
            WellKnownAccount acct = WellKnownAccount.LookupByType(sidType);

            if (acct == null)
            {
                throw new ArgumentException("Unable to convert SID type: " + sidType);
            }

            if (acct.IsAbsolute)
            {
                buffer = ParseSddlForm(acct.Sid);
            }
            else
            {
                if (domainSid == null)
                {
                    throw new ArgumentNullException("domainSid");
                }

                buffer = ParseSddlForm(domainSid.Value + "-" + acct.Rid);
            }
        }
Пример #17
0
 public static SecurityIdentifier CreateWellKnownSid(WellKnownSidType sidType)
 {
     return(CreateWellKnownSid(sidType, GetLocalMachineAuthoritySid()));
 }
Пример #18
0
		private void CheckWellKnownSidLookup (WellKnownSidType wellKnownSidType, string name)
		{
			Assert.AreEqual (name, ((NTAccount)new SecurityIdentifier (wellKnownSidType, null).Translate (typeof(NTAccount))).Value);
		}
Пример #19
0
        private void CheckQualifiedWellKnownSid(WellKnownSidType type, SecurityIdentifier domain, string sddl)
        {
            SecurityIdentifier sid = new SecurityIdentifier(type, domain);

            Assert.AreEqual(sddl, sid.Value, "Bad SID for type: " + type);
        }
 //
 // Summary:
 //     Initializes a new instance of the System.Security.Principal.SecurityIdentifier
 //     class by using the specified well known security identifier (SID) type and
 //     domain SID.
 //
 // Parameters:
 //   sidType:
 //     A System.Security.Principal.WellKnownSidType value.This value must not be
 //     System.Security.Principal.WellKnownSidType.WinLogonIdsSid.
 //
 //   domainSid:
 //     The domain SID. This value is required for the following System.Security.Principal.WellKnownSidType
 //     values. This parameter is ignored for any other System.Security.Principal.WellKnownSidType
 //     values.System.Security.Principal.WellKnownSidType.WinAccountAdministratorSidSystem.Security.Principal.WellKnownSidType.WinAccountGuestSidSystem.Security.Principal.WellKnownSidType.WinAccountKrbtgtSidSystem.Security.Principal.WellKnownSidType.WinAccountDomainAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountDomainUsersSidSystem.Security.Principal.WellKnownSidType.WinAccountDomainGuestsSidSystem.Security.Principal.WellKnownSidType.WinAccountComputersSidSystem.Security.Principal.WellKnownSidType.WinAccountControllersSidSystem.Security.Principal.WellKnownSidType.WinAccountCertAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountSchemaAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountEnterpriseAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountPolicyAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountRasAndIasServersSid
 public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
 {
   Contract.Requires(sidType != WellKnownSidType.LogonIdsSid);
   Contract.Requires(sidType >= WellKnownSidType.NullSid);
   Contract.Requires(sidType <= WellKnownSidType.WinBuiltinTerminalServerLicenseServersSid);
 }
Пример #21
0
        //
        // Wrapper around advapi32.IsWellKnownSid
        //


        internal static bool IsWellKnownSid(
            SecurityIdentifier sid,
            WellKnownSidType type
            )
        {
            byte[] BinaryForm = new byte[sid.BinaryLength];
            sid.GetBinaryForm(BinaryForm, 0);

            if (FALSE == Interop.mincore.IsWellKnownSid(BinaryForm, (int)type))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
Пример #22
0
		/// <summary> Returns the rights assigned to the given SID for this file's ACL </summary>
		public static FileSystemRights GetPermissions(string filepath, WellKnownSidType sidType)
		{
			SecurityIdentifier domain = null;
			FileSecurity sec = File.GetAccessControl(filepath);
			SecurityIdentifier sid = new SecurityIdentifier(sidType, domain);

			FileSystemRights rights = 0;
			foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, false, typeof(SecurityIdentifier)))
			{
				if (sid.Value == rule.IdentityReference.Value)
				{
					if (rule.AccessControlType == AccessControlType.Allow)
						rights |= rule.FileSystemRights;
					else
						rights &= ~rule.FileSystemRights;
				}
			}

			return rights;
		}
        /// <summary>
        /// Check if user have all specified rights to the registry key.
        /// </summary>
        /// <param name="key">Registry key to check.</param>
        /// <param name="wksid">User to check.</param>
        /// <param name="rights">Rights to check.</param>
        /// <returns>True if user has rights, false if user don't have rights or rights not found.</returns>
        public static bool HasRights(RegistryKey key, WellKnownSidType wksid, RegistryRights rights)
        {
            var sid = new SecurityIdentifier(wksid, null);

            return(HasRights(key, rights, sid));
        }
Пример #24
0
		/// <summary>
		/// Attempt to populate a set of Windows access rules, calculated from a UNIX mode flags
		/// </summary>
		/// <param name="mode"></param>
		/// <returns></returns>
		static FileSystemAccessRule[] ResolveAccessRules(int mode)
		{
			//http://support.microsoft.com/kb/243330
			WellKnownSidType[] roles = new WellKnownSidType[] {
				WellKnownSidType.WorldSid,
				WellKnownSidType.CreatorGroupSid,
				WellKnownSidType.CreatorOwnerSid
			};

			//http://en.wikipedia.org/wiki/File_system_permissions#Octal_notation
			FileSystemRights[] permissions = new FileSystemRights[] {
				FileSystemRights.ReadAndExecute,
				FileSystemRights.Write,
				FileSystemRights.Read
			};

			var rules = new System.Collections.Generic.List<FileSystemAccessRule>();
			
			//Walk all combinations of roles and permissions
			for (int r = 0; r < roles.Length; r++) {
				WellKnownSidType role = roles[r];

				for (int p = 0; p < permissions.Length; p++) {
					rules.Add(GetAccessRule(role, permissions[p], ((mode >> (r * 3)) & (1 << p)) != 0));
				}
			}
			
			return rules.ToArray();
		}
Пример #25
0
 		/// <summary>
		/// Add or revoke specified permission for a given role
		/// </summary>
		/// <param name="role">an equivalent to UNIX's owner, group or public</param>
		/// <param name="permission">~ read, write, search</param>
		/// <param name="add"></param>
		static FileSystemAccessRule GetAccessRule(
				WellKnownSidType role,
				FileSystemRights permission,
				bool add)
		{
			//http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/dc841874-b71b-4e1c-9052-06eb4a87d08f
			IdentityReference identity = new SecurityIdentifier(role, null).Translate(typeof(NTAccount)) as IdentityReference;

			return new FileSystemAccessRule(
					identity,
					permission,
					add ? AccessControlType.Allow : AccessControlType.Deny);
		}
 public static string GetWellKnownWindowsAccountNameLocalized(WellKnownSidType accountSidType)
 {
     SecurityIdentifier sid = new SecurityIdentifier(accountSidType, null);
     return GetLocalizedWindowsAccountNameBySid(sid);
 }
Пример #27
0
        public void SetPermissions(string filename, WellKnownSidType accountSid, FileSystemRights rights, AccessControlType controlType)
        {
            try
            {
                var sid = new SecurityIdentifier(accountSid, null);

                var directoryInfo = new DirectoryInfo(filename);
                var directorySecurity = directoryInfo.GetAccessControl(AccessControlSections.Access);

                var rules = directorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));

                if (rules.OfType<FileSystemAccessRule>().Any(acl => acl.AccessControlType == controlType && (acl.FileSystemRights & rights) == rights && acl.IdentityReference.Equals(sid)))
                {
                    return;
                }

                var accessRule = new FileSystemAccessRule(sid, rights,
                                                          InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                          PropagationFlags.InheritOnly, controlType);

                bool modified;
                directorySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out modified);

                if (modified)
                {
                    directoryInfo.SetAccessControl(directorySecurity);
                }
            }
            catch (Exception e)
            {
                Logger.Warn(e, "Couldn't set permission for {0}. account:{1} rights:{2} accessControlType:{3}", filename, accountSid, rights, controlType);
                throw;
            }
        }
Пример #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NamedPipeServer" /> class.
 /// </summary>
 /// <param name="sidType">One of the enumeration of well known sid types, the value must not be
 /// <see cref="WellKnownSidType.LogonIdsSid" />.  This defines
 /// who can connect to the pipe.</param>
 /// <param name="domainSid"><para>The domain SID. This value is required for the following <see cref="WellKnownSidType" /> values.
 /// This parameter is ignored for any other <see cref="WellKnownSidType" /> values.</para>
 /// <list type="bullet">
 ///   <item>
 ///     <description>AccountAdministratorSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountGuestSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountKrbtgtSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountDomainAdminsSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountDomainUsersSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountDomainGuestsSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountComputersSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountControllersSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountCertAdminsSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountSchemaAdminsSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountEnterpriseAdminsSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountPolicyAdminsSid</description>
 ///   </item>
 ///   <item>
 ///     <description>AccountRasAndIasServersSid</description>
 ///   </item>
 /// </list></param>
 /// <param name="name">The pipe name.</param>
 /// <param name="maximumConnections">The maximum number of connections.</param>
 /// <param name="heartbeat">The heartbeat timespan, ensures a connection is always available, defaults to once every 5 seconds, specify a negative value to disable.</param>
 public ServerConfig(
     WellKnownSidType sidType,
     [CanBeNull] SecurityIdentifier domainSid = null,
     [CanBeNull] string name = null,
     int maximumConnections = 1,
     TimeSpan heartbeat = default(TimeSpan))
     : this(new SecurityIdentifier(sidType, domainSid), name, maximumConnections, heartbeat)
 {
 }
Пример #29
0
        /// <summary>
        /// Gets from an given SID the corresponding Accountname
        /// </summary>
        /// <param name="sid">The SID of the Account</param>
        /// <param name="domainSid">The SID of the Domain User</param>
        /// <returns>An System- or Useraccount Name.</returns>
        public static string GetAccountNameFromSid(WellKnownSidType sid, RemoteServerSettings serverSettings)
        {
            Log.WriteStart("GetAccountNameFromSid");

            SecurityIdentifier ident = null;

            if (sid == WellKnownSidType.AccountAdministratorSid
                || sid == WellKnownSidType.AccountGuestSid
                || sid == WellKnownSidType.AccountKrbtgtSid
                || sid == WellKnownSidType.AccountDomainAdminsSid
                || sid == WellKnownSidType.AccountDomainUsersSid
                || sid == WellKnownSidType.AccountDomainGuestsSid
                || sid == WellKnownSidType.AccountComputersSid
                || sid == WellKnownSidType.AccountControllersSid
                || sid == WellKnownSidType.AccountCertAdminsSid
                || sid == WellKnownSidType.AccountSchemaAdminsSid
                || sid == WellKnownSidType.AccountEnterpriseAdminsSid
                || sid == WellKnownSidType.AccountPolicyAdminsSid
                || sid == WellKnownSidType.AccountRasAndIasServersSid)
            {
                if (serverSettings.ADEnabled)
                {
                    // Determine Domains SID
                    SecurityIdentifier domainSid = null;
                    var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
                    var domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, domainName, serverSettings.ADUsername, serverSettings.ADPassword));

                    using (DirectoryEntry de = domain.GetDirectoryEntry())
                    {
                        byte[] domainSIdArray = (byte[])de.Properties["objectSid"].Value;
                        domainSid = new SecurityIdentifier(domainSIdArray, 0);
                    }

                    ident = new SecurityIdentifier(sid, domainSid);
                }
                else
                {
                    Log.WriteError("Please enable AD Auth for this Server. Thanks", new SecurityException("AD Auth missing"));
                }
            }
            else
            {
                ident = new SecurityIdentifier(sid, null);
            }

            var accountName = GetAccountNameFromSidInternal(ident, serverSettings);

            Log.WriteEnd("GetAccountNameFromSid");

            return accountName;
        }
        /// <summary>
        /// Check if user have all specified rights to the file or directory.
        /// </summary>
        /// <param name="path">The path to a file or directory.</param>
        /// <param name="rights">Rights to check.</param>
        /// <param name="wksid">User to check.</param>
        /// <returns>True if user has rights, false if user don't have rights or rights not found.</returns>
        public static bool HasRights(string path, FileSystemRights rights, WellKnownSidType wksid)
        {
            var sid = new SecurityIdentifier(wksid, null);

            return(HasRights(path, rights, sid));
        }
        /// <summary>
        ///     Adds an ACL entry on the specified file for the specified account.
        /// </summary>
        /// <param name="fileName"> File name. </param>
        /// <param name="account"> The sid for the account. </param>
        /// <param name="rights"> What rights to grant (e.g. read). </param>
        /// <param name="controlType"> Grant or deny? </param>
        public static void AddFileSecurity(string fileName, WellKnownSidType account,
                                           FileSystemRights rights, AccessControlType controlType)
        {
            // Get a FileSecurity object that represents the
            // current security settings.
            var fSecurity = File.GetAccessControl(fileName);

            // Added the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(account, null), rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);
        }
Пример #32
0
        //
        // Constructs a well-known SID
        // The 'domainSid' parameter is optional and only used
        // by the well-known types that require it
        // NOTE: although there is a P/Invoke call involved in the implementation of this constructor,
        //       there is no security risk involved, so no security demand is being made.
        //


        public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
        {
            //
            // sidType must not be equal to LogonIdsSid
            //

            if (sidType == WellKnownSidType.LogonIdsSid)
            {
                throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, "sidType");
            }
            Contract.EndContractBlock();

            byte[] resultSid;
            int    Error;

            //
            // sidType should not exceed the max defined value
            //

            if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.MaxDefined))
            {
                throw new ArgumentException(SR.Argument_InvalidValue, "sidType");
            }

            //
            // for sidType between 38 to 50, the domainSid parameter must be specified
            //

            if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid))
            {
                if (domainSid == null)
                {
                    throw new ArgumentNullException("domainSid", SR.Format(SR.IdentityReference_DomainSidRequired, sidType));
                }

                //
                // verify that the domain sid is a valid windows domain sid
                // to do that we call GetAccountDomainSid and the return value should be the same as the domainSid
                //

                SecurityIdentifier resultDomainSid;
                int ErrorCode;

                ErrorCode = Win32.GetWindowsAccountDomainSid(domainSid, out resultDomainSid);

                if (ErrorCode == Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw new OutOfMemoryException();
                }
                else if (ErrorCode == Interop.mincore.Errors.ERROR_NON_ACCOUNT_SID)
                {
                    // this means that the domain sid is not valid
                    throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, "domainSid");
                }
                else if (ErrorCode != Interop.mincore.Errors.ERROR_SUCCESS)
                {
                    Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode));
                    throw new Win32Exception(ErrorCode);
                }

                //
                // if domainSid is passed in as S-1-5-21-3-4-5-6,  the above api will return S-1-5-21-3-4-5 as the domainSid
                // Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities)
                //
                if (resultDomainSid != domainSid)
                {
                    throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, "domainSid");
                }
            }


            Error = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid);

            if (Error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER)
            {
                throw new ArgumentException(new Win32Exception(Error).Message, "sidType/domainSid");
            }
            else if (Error != Interop.mincore.Errors.ERROR_SUCCESS)
            {
                Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error));
                throw new Win32Exception(Error);
            }

            CreateFromBinaryForm(resultSid, 0);
        }
Пример #33
0
        //
        // Constructs a well-known SID
        // The 'domainSid' parameter is optional and only used
        // by the well-known types that require it
        // NOTE: although there is a P/Invoke call involved in the implementation of this constructor,
        //       there is no security risk involved, so no security demand is being made.
        //


        public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier?domainSid)
        {
            //
            // sidType must not be equal to LogonIdsSid
            //

            if (sidType == WellKnownSidType.LogonIdsSid)
            {
                throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, nameof(sidType));
            }

            //
            // sidType should not exceed the max defined value
            //

            if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.WinCapabilityRemovableStorageSid))
            {
                throw new ArgumentException(SR.Argument_InvalidValue, nameof(sidType));
            }

            //
            // for sidType between 38 to 50, the domainSid parameter must be specified
            //
            int error;

            if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid))
            {
                if (domainSid == null)
                {
                    throw new ArgumentNullException(nameof(domainSid), SR.Format(SR.IdentityReference_DomainSidRequired, sidType));
                }

                //
                // verify that the domain sid is a valid windows domain sid
                // to do that we call GetAccountDomainSid and the return value should be the same as the domainSid
                //
                error = Win32.GetWindowsAccountDomainSid(domainSid, out SecurityIdentifier? resultDomainSid);

                if (error == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw new OutOfMemoryException();
                }
                else if (error == Interop.Errors.ERROR_NON_ACCOUNT_SID)
                {
                    // this means that the domain sid is not valid
                    throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid));
                }
                else if (error != Interop.Errors.ERROR_SUCCESS)
                {
                    Debug.Fail($"Win32.GetWindowsAccountDomainSid returned unrecognized error {error}");
                    throw new Win32Exception(error);
                }

                //
                // if domainSid is passed in as S-1-5-21-3-4-5-6,  the above api will return S-1-5-21-3-4-5 as the domainSid
                // Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities)
                //
                if (resultDomainSid != domainSid)
                {
                    throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid));
                }
            }


            error = Win32.CreateWellKnownSid(sidType, domainSid, out byte[]? resultSid);

            if (error == Interop.Errors.ERROR_INVALID_PARAMETER)
            {
#pragma warning disable CA2208 // Instantiate argument exceptions correctly, combination of arguments used
                throw new ArgumentException(new Win32Exception(error).Message, "sidType/domainSid");
#pragma warning restore CS2208
            }
            else if (error != Interop.Errors.ERROR_SUCCESS)
            {
                Debug.Fail($"Win32.CreateWellKnownSid returned unrecognized error {error}");
                throw new Win32Exception(error);
            }

            CreateFromBinaryForm(resultSid !, 0);
        }
        public void FileInfo_Create_FileSecurity_SpecificAccessRule(WellKnownSidType sid, FileSystemRights rights, AccessControlType controlType)
        {
            FileSecurity security = GetFileSecurity(sid, rights, controlType);

            VerifyFileSecurity(security);
        }
Пример #35
0
        //
        // Wrapper around advapi32.CreateWellKnownSid
        //


        internal static int CreateWellKnownSid(
            WellKnownSidType sidType,
            SecurityIdentifier domainSid,
            out byte[] resultSid
            )
        {
            //
            // Passing an array as big as it can ever be is a small price to pay for
            // not having to P/Invoke twice (once to get the buffer, once to get the data)
            //

            uint length = (uint)SecurityIdentifier.MaxBinaryLength;
            resultSid = new byte[length];

            if (FALSE != Interop.mincore.CreateWellKnownSid((int)sidType, domainSid == null ? null : domainSid.BinaryForm, resultSid, ref length))
            {
                return Interop.mincore.Errors.ERROR_SUCCESS;
            }
            else
            {
                resultSid = null;

                return Marshal.GetLastWin32Error();
            }
        }
Пример #36
0
 public static string GetWellKnownName(WellKnownSidType type)
 {
     return GetNameFromSID(GetWellknownSID(type));
 }
Пример #37
0
 internal static extern bool IsWellKnownSid(IntPtr sid, WellKnownSidType type);
Пример #38
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static int CreateWellKnownSid( 
            WellKnownSidType sidType, 
            SecurityIdentifier domainSid,
            out byte[] resultSid 
            )
        {

            // 
            // Check if the api is supported
            // 
            if (!WellKnownSidApisSupported) { 
                throw new PlatformNotSupportedException( Environment.GetResourceString( "PlatformNotSupported_RequiresW2kSP3" ));
            } 

            //
            // Passing an array as big as it can ever be is a small price to pay for
            // not having to P/Invoke twice (once to get the buffer, once to get the data) 
            //
 
            uint length = ( uint )SecurityIdentifier.MaxBinaryLength; 
            resultSid = new byte[ length ];
 
            if ( FALSE != Win32Native.CreateWellKnownSid(( int )sidType, domainSid == null ? null : domainSid.BinaryForm, resultSid, ref length ))
            {
                return Win32Native.ERROR_SUCCESS;
            } 
            else
            { 
                resultSid = null; 

                return Marshal.GetLastWin32Error(); 
            }
        }
 //
 // Summary:
 //     Returns a value that indicates whether the System.Security.Principal.SecurityIdentifier
 //     object matches the specified well known security identifier (SID) type.
 //
 // Parameters:
 //   type:
 //     A System.Security.Principal.WellKnownSidType value to compare with the System.Security.Principal.SecurityIdentifier
 //     object.
 //
 // Returns:
 //     true if type is the SID type for the System.Security.Principal.SecurityIdentifier
 //     object; otherwise, false.
 extern public bool IsWellKnown(WellKnownSidType type);
Пример #40
0
        public static void SetWindowsServiceCredentials(string serviceName, WellKnownSidType sidType)
        {
            var username = GetUserName(sidType);

            SetWindowsServiceCredentials(serviceName, username, null);
        }
Пример #41
0
 private void CheckWellKnownSidLookup(WellKnownSidType wellKnownSidType, string name)
 {
     Assert.AreEqual(name, ((NTAccount) new SecurityIdentifier(wellKnownSidType, null).Translate(typeof(NTAccount))).Value);
 }
Пример #42
0
		private void CheckQualifiedWellKnownSid (WellKnownSidType type, SecurityIdentifier domain, string sddl)
		{
			SecurityIdentifier sid = new SecurityIdentifier (type, domain);
			Assert.AreEqual (sddl, sid.Value, "Bad SID for type: " + type);
		}
Пример #43
0
        //
        // Determines whether this SID is a well-known SID of the specified type
        //
        // NOTE: although there is a P/Invoke call involved in the implementation of this method,
        //       there is no security risk involved, so no security demand is being made.
        //


        public bool IsWellKnown(WellKnownSidType type)
        {
            return(Win32.IsWellKnownSid(this, type));
        }
 internal static bool IsWellKnownSid(SecurityIdentifier sid, WellKnownSidType type)
 {
     if (!WellKnownSidApisSupported)
     {
         throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresW2kSP3"));
     }
     byte[] binaryForm = new byte[sid.BinaryLength];
     sid.GetBinaryForm(binaryForm, 0);
     if (Win32Native.IsWellKnownSid(binaryForm, (int) type) == 0)
     {
         return false;
     }
     return true;
 }
    public void CreatingSecurityIdentifierOutsideWellKnownSidTypeDefinedRangeThrowsException(WellKnownSidType sidType)
    {
        var currentDomainSid = WindowsIdentity.GetCurrent().Owner.AccountDomainSid;

        AssertExtensions.Throws <ArgumentException>("sidType", () => new SecurityIdentifier(sidType, currentDomainSid));
    }
 internal static int CreateWellKnownSid(WellKnownSidType sidType, SecurityIdentifier domainSid, out byte[] resultSid)
 {
     if (!WellKnownSidApisSupported)
     {
         throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresW2kSP3"));
     }
     uint maxBinaryLength = (uint) SecurityIdentifier.MaxBinaryLength;
     resultSid = new byte[maxBinaryLength];
     if (Win32Native.CreateWellKnownSid((int) sidType, (domainSid == null) ? null : domainSid.BinaryForm, resultSid, ref maxBinaryLength) != 0)
     {
         return 0;
     }
     resultSid = null;
     return Marshal.GetLastWin32Error();
 }
Пример #47
0
 public static SecurityIdentifier GetWellknownSID(WellKnownSidType type)
 {
     return new SecurityIdentifier(type, null);
 }
        private static IEnumerable <IdentityReference> WhenEmptyUse(IEnumerable <IdentityReference> acl, WellKnownSidType type)
        {
            var result = new List <IdentityReference>(acl ?? Enumerable.Empty <IdentityReference>());

            if (result.Count == 0)
            {
                result.Add(new SecurityIdentifier(type, null));
            }

            return(result);
        }
Пример #49
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static bool IsWellKnownSid( 
            SecurityIdentifier sid,
            WellKnownSidType type
            )
        { 
            //
            // Check if the api is supported 
            // 
            if (!WellKnownSidApisSupported) {
                throw new PlatformNotSupportedException( Environment.GetResourceString( "PlatformNotSupported_RequiresW2kSP3" )); 
            }

            byte[] BinaryForm = new byte[sid.BinaryLength];
            sid.GetBinaryForm( BinaryForm, 0 ); 

            if ( FALSE == Win32Native.IsWellKnownSid( BinaryForm, ( int )type )) 
            { 
                return false;
            } 
            else
            {
                return true;
            } 
        }
Пример #50
0
 static string GetGroupName(WellKnownSidType wellKnownSidType)
 {
     return(new SecurityIdentifier(wellKnownSidType, null)
            .Translate(typeof(NTAccount))
            .ToString());
 }
 static string GetGroupName(WellKnownSidType wellKnownSidType)
 {
     return new SecurityIdentifier(wellKnownSidType, null)
         .Translate(typeof(NTAccount))
         .ToString();
 }
Пример #52
0
 public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
 {
     throw new NotImplementedException();
 }
Пример #53
0
 private extern static bool CreateWellKnownSid(WellKnownSidType wellKnownSidType, IntPtr domainSid, IntPtr pSid, ref int cbSid);
Пример #54
0
		/// <summary> Grants the user FullControl for the file, returns true if modified, false if already present </summary>
		public static bool GrantFullControlForFile(string filepath, WellKnownSidType sidType, SecurityIdentifier domain)
		{
			FileSecurity sec = File.GetAccessControl(filepath);
			SecurityIdentifier sid = new SecurityIdentifier(sidType, domain);
			bool found = false;

			List<FileSystemAccessRule> toremove = new List<FileSystemAccessRule>();
			foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, false, typeof(SecurityIdentifier)))
			{
				if (sid.Value == rule.IdentityReference.Value)
				{
					if (rule.AccessControlType != AccessControlType.Allow || rule.FileSystemRights != FileSystemRights.FullControl)
						toremove.Add(rule);
					else
						found = true;
				}
			}
			if (!found || toremove.Count > 0)
			{
				foreach (FileSystemAccessRule bad in toremove)
					sec.RemoveAccessRule(bad);

				sec.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow));
				File.SetAccessControl(filepath, sec);
				return true;
			}

			return false;
		}
Пример #55
0
        public void SetPermissions(string filename, WellKnownSidType accountSid, FileSystemRights rights, AccessControlType controlType)
        {
            try
            {
                var sid = new SecurityIdentifier(accountSid, null);

                var directoryInfo = new DirectoryInfo(filename);
                var directorySecurity = directoryInfo.GetAccessControl();

                var accessRule = new FileSystemAccessRule(sid, rights,
                                                          InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                          PropagationFlags.None, controlType);

                directorySecurity.AddAccessRule(accessRule);
                directoryInfo.SetAccessControl(directorySecurity);
            }
            catch (Exception e)
            {
                Logger.WarnException(string.Format("Couldn't set permission for {0}. account:{1} rights:{2} accessControlType:{3}", filename, accountSid, rights, controlType), e);
                throw;
            }
        }
Пример #56
0
 internal static string GetNTAccountName(WellKnownSidType knownSid)
 {
     SecurityIdentifier sid = new SecurityIdentifier(knownSid, null);
     NTAccount account = (NTAccount)sid.Translate(typeof(NTAccount));
     return account.Value;
 }
Пример #57
0
 public bool IsWellKnown(WellKnownSidType type)
 {
     throw new NotImplementedException();
 }
Пример #58
0
        public void Should_warn_if_queue_has_public_access(MessageQueueAccessRights rights, WellKnownSidType sidType)
        {
            var groupName = new SecurityIdentifier(sidType, null).Translate(typeof(NTAccount)).ToString();

            using (var queue = MessageQueue.Create(@".\private$\" + testQueueName, false))
            {
                queue.SetPermissions(groupName, rights);
            }

            QueuePermissions.CheckQueue(testQueueName);
            Assert.That(logOutput.ToString(), Does.Contain("Consider setting appropriate permissions"));
        }
Пример #59
0
 public static extern bool CreateWellKnownSid([In] WellKnownSidType WellKnownSidType, [In] IntPtr DomainSid = default(IntPtr), [In] IntPtr pSid, [In][Out] ref int cbSid);
Пример #60
0
		/// <summary> Grants the user FullControl for the file, returns true if modified, false if already present </summary>
		public static bool GrantFullControlForFile(string filepath, WellKnownSidType sidType)
		{ return GrantFullControlForFile(filepath, sidType, null); }