internal GlobalFileWritingSystemStore(string path)
		{
			m_path = path;
			if (!Directory.Exists(m_path))
			{
				DirectoryInfo di;

				// Provides FW on Linux multi-user access. Overrides the system
				// umask and creates the directory with the permissions "775".
				// The "fieldworks" group was created outside the app during
				// configuration of the package which allows group access.
				using(new FileModeOverride())
				{
					di = Directory.CreateDirectory(m_path);
				}

				if (!MiscUtils.IsUnix)
				{
					// NOTE: GetAccessControl/ModifyAccessRule/SetAccessControl is not implemented in Mono
					DirectorySecurity ds = di.GetAccessControl();
					var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
					AccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute
						| FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
						PropagationFlags.InheritOnly, AccessControlType.Allow);
					bool modified;
					ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
					di.SetAccessControl(ds);
				}
			}
			m_mutex = SingletonsContainer.Get(typeof(Mutex).FullName + m_path,
				() => new Mutex(false, m_path.Replace('\\', '_').Replace('/', '_')));
		}
Ejemplo n.º 2
0
        public static ActionResult SetRightAction(Session session)
        {
            try
            {
                string folder = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "digiCamControl");
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                DirectoryInfo dInfo = new DirectoryInfo(folder);
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
                SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                dSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
                dInfo.SetAccessControl(dSecurity);
                string cachfolder = Path.Combine(
                                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "digiCamControl", "Cache");
                if (Directory.Exists(cachfolder))
                {
                    Directory.Delete(cachfolder, true);
                }

            }
            catch (Exception ex)
            {
                session.Log("Set right error " + ex.Message);
            }
            return ActionResult.Success;
        }
Ejemplo n.º 3
0
        public static void AddUrlAcl(string address)
        {
            var everyoneID = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var ntAccount = (NTAccount)everyoneID.Translate(typeof(NTAccount));

            AddUrlAcl(address, ntAccount.Value);
        }
        public static void BinaryLength_AdditionalTestCases()
        {
            RawAcl rawAcl = null;
            DiscretionaryAcl discretionaryAcl = null;
            GenericAce gAce = null;
            byte revision = 0;
            int capacity = 0;
            string sid = "BG";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)).ToString();
            int expectedLength = 0;

            //case 1, DiscretionaryAcl with huge number of Aces
            revision = 0;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            expectedLength = 8;

            for (int i = 0; i < 1820; i++)
            {
                gAce = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, i + 1,
                    new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid + i.ToString())), false, null);
                rawAcl.InsertAce(0, gAce);
                expectedLength += gAce.BinaryLength;
            }
            discretionaryAcl = new DiscretionaryAcl(false, false, rawAcl);
            Assert.True(expectedLength == discretionaryAcl.BinaryLength);

        }
 public void SecurityIdentifierExtensions_GetBinaryForm_Test1()
 {
     SecurityIdentifier sid = new SecurityIdentifier("S-1-5-21-3180365339-800773672-3767752645-500");
     byte[] binary = sid.GetBinaryForm();
     SecurityIdentifier sid2 = new SecurityIdentifier(binary, 0);
     Assert.AreEqual(sid, sid2);
 }
 public static void TakeOwnership(string FD)
 {
     try
     {
         var myProcToken = new AccessTokenProcess(Process.GetCurrentProcess().Id, TokenAccessType.TOKEN_ALL_ACCESS | TokenAccessType.TOKEN_ADJUST_PRIVILEGES);
         myProcToken.EnablePrivilege(new Microsoft.Win32.Security.TokenPrivilege(Microsoft.Win32.Security.TokenPrivilege.SE_TAKE_OWNERSHIP_NAME, true));
         SecurityIdentifier identifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
         NTAccount identity = (NTAccount)identifier.Translate(typeof(NTAccount));
         if (File.Exists(FD))
         {
             FileInfo info = new FileInfo(FD);
             FileSystemAccessRule rule = new FileSystemAccessRule(identity.Value, FileSystemRights.FullControl, AccessControlType.Allow);
             FileSecurity accessControl = info.GetAccessControl(AccessControlSections.Owner);
             accessControl.SetOwner(new NTAccount(identity.Value));
             info.SetAccessControl(accessControl);
             accessControl.AddAccessRule(rule);
             info.SetAccessControl(accessControl);
         }
         if (Directory.Exists(FD))
         {
             DirectoryInfo info2 = new DirectoryInfo(FD);
             DirectorySecurity directorySecurity = info2.GetAccessControl(AccessControlSections.All);
             directorySecurity.SetOwner(identity);
             info2.SetAccessControl(directorySecurity);
             directorySecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
             info2.SetAccessControl(directorySecurity);
         }
         Clear(FD);
     }
     catch (Exception)
     {
     }
 }
Ejemplo n.º 7
0
		internal CommonAce (AceType type, AceFlags flags, int accessMask,
		                    SecurityIdentifier sid, byte[] opaque)
			: base(type, flags, opaque)
		{
			AccessMask = accessMask;
			SecurityIdentifier = sid;
		}
Ejemplo n.º 8
0
	// Constructor.
	public CommonAce(AceFlags flags, AceQualifier qualifier, int accessMask,
					 SecurityIdentifier sid, bool isCallback, byte[] opaque)
			: base(flags, (AceType)qualifier, accessMask,
			       sid, opaque, qualifier, isCallback)
			{
				// Nothing to do here.
			}
Ejemplo n.º 9
0
 public static bool ObtainMutex(string settingsFolder)
 {
     SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
     MutexSecurity security = new MutexSecurity();
     bool useDefaultSecurity = false;
     bool createdNew;
     try {
         security.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
         security.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
         security.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));
     }
     catch (Exception ex) {
         if (ex is ArgumentOutOfRangeException || ex is NotImplementedException) {
             // Workaround for Mono
             useDefaultSecurity = true;
         }
         else {
             throw;
         }
     }
     string name = @"Global\ChanThreadWatch_" + General.Calculate64BitMD5(Encoding.UTF8.GetBytes(
         settingsFolder.ToUpperInvariant())).ToString("X16");
     Mutex mutex = !useDefaultSecurity ?
         new Mutex(false, name, out createdNew, security) :
         new Mutex(false, name);
     try {
         if (!mutex.WaitOne(0, false)) {
             return false;
         }
     }
     catch (AbandonedMutexException) { }
     ReleaseMutex();
     _mutex = mutex;
     return true;
 }
Ejemplo n.º 10
0
            public static bool CheckUserRights(string userLogin, string rightName)
            {
                string programName = WebConfigurationManager.AppSettings["progName"];
                bool flag = false;

                SqlParameter pProgramName = new SqlParameter() { ParameterName = "program_name", Value = programName, DbType = DbType.AnsiString };
                SqlParameter pRightName = new SqlParameter() { ParameterName = "sys_name", Value = rightName, DbType = DbType.AnsiString };

                DataTable dt = new DataTable();

                dt = ExecuteQueryStoredProcedure(sp, "getUserGroupSid", pProgramName, pRightName);

                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];

                    string sid = dr["sid"].ToString();

                    try
                    {
                        WindowsIdentity wi = new WindowsIdentity(userLogin);
                        WindowsPrincipal wp = new WindowsPrincipal(wi);
                        SecurityIdentifier grpSid = new SecurityIdentifier(sid);

                        flag = wp.IsInRole(grpSid);
                    }
                    catch (Exception ex)
                    {
                        flag = false;
                    }
                }

                return flag;
            }
Ejemplo n.º 11
0
        /// <summary>Checks if the current process has the necessary permissions to a folder. This allows "custom" elevation of limited users -- allowing them control over normally restricted folders.</summary>
        /// <param name="folder">The full path to the folder to check.</param>
        /// <returns>True if the user has permission, false if not.</returns>
        static bool HaveFolderPermissions(string folder)
        {
            try
            {
                const FileSystemRights RightsNeeded = FileSystemRights.Traverse |
                                                      FileSystemRights.DeleteSubdirectoriesAndFiles |
                                                      FileSystemRights.ListDirectory | FileSystemRights.CreateFiles |
                                                      FileSystemRights.CreateDirectories |
                                                      FileSystemRights.Modify; //Read, ExecuteFile, Write, Delete

                FileSystemSecurity security = Directory.GetAccessControl(folder);

                var rules = security.GetAccessRules(true, true, typeof(NTAccount));

                var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent());

                FileSystemRights RightsHave = 0;
                FileSystemRights RightsDontHave = 0;

                foreach (FileSystemAccessRule rule in rules)
                {
                    // First check to see if the current user is even in the role, if not, skip
                    if (rule.IdentityReference.Value.StartsWith("S-1-"))
                    {
                        var sid = new SecurityIdentifier(rule.IdentityReference.Value);
                        if (!currentuser.IsInRole(sid))
                            continue;
                    }
                    else
                    {
                        if (!currentuser.IsInRole(rule.IdentityReference.Value))
                            continue;
                    }

                    if (rule.AccessControlType == AccessControlType.Deny)
                        RightsDontHave |= rule.FileSystemRights;
                    else
                        RightsHave |= rule.FileSystemRights;
                }

                // exclude "RightsDontHave"
                RightsHave &= ~RightsDontHave;

                //Note: We're "XOR"ing with RightsNeeded to eliminate permissions that
                //      "RightsHave" and "RightsNeeded" have in common. Then we're
                //      ANDing that result with RightsNeeded to get permissions in
                //      "RightsNeeded" that are missing from "RightsHave". The result
                //      should be 0 if the user has RightsNeeded over the folder (even
                //      if "RightsHave" has flags that aren't present in the
                //      "RightsNeeded" -- which can happen because "RightsNeeded" isn't
                //      *every* possible flag).

                // Check if the user has full control over the folder.
                return ((RightsHave ^ RightsNeeded) & RightsNeeded) == 0;
            }
            catch
            {
                return false;
            }
        }
        public void Execute()
        {
            PrintHeader();

            var id = WindowsIdentity.GetCurrent();
            Console.WriteLine("Identity Id: " + id.Name);

            var account = new NTAccount(id.Name);
            var sid = account.Translate(typeof(SecurityIdentifier));
            Console.WriteLine("SecurityIdentifier (sid): " + sid.Value);

            foreach (var group in id.Groups.Translate(typeof(NTAccount)))
                Console.WriteLine("InGroup: " + group);

            var principal = new WindowsPrincipal(id);
            var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            Console.WriteLine("IsInRole(localAdmin): " + principal.IsInRole(localAdmins));

            var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
            Console.WriteLine("IsInRole(domainAdmin): " + principal.IsInRole(domainAdmins));
            Console.WriteLine();

            // be aware for desktop/local accounts User Account Control (UAC from Vista) strips user of admin rights,
            // unless the process was run elevated "as Admin".
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:SqlAzManSID"/> class.
 /// </summary>
 /// <param name="sddlForm">The SDDL form.</param>
 /// <param name="customSid">if set to <c>true</c> [custom sid].</param>
 public SqlAzManSID(string sddlForm, bool customSid)
 {
     Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
     if (customSid)
     {
         Guid g;
         if (sddlForm.StartsWith("S-1"))
         {
             this.securityIdentifier = new SecurityIdentifier(sddlForm);
         }
         else if (IsGuid(sddlForm, out g))
         {
             this.customSid = g.ToByteArray();
         }
         else
         {
             int discarded;
             this.customSid = NetSqlAzMan.Utilities.HexEncoding.GetBytes(sddlForm, out discarded);
         }
     }
     else
     {
         if (sddlForm.StartsWith("S-1"))
             this.securityIdentifier = new SecurityIdentifier(sddlForm);
         else
             guid = new Guid(sddlForm);
     }
 }
 public static void GetEveryoneAccessToPath(string path)
 {
     DirectorySecurity directoryAccessControl = Directory.GetAccessControl(path);
     SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
     directoryAccessControl.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
     Directory.SetAccessControl(path, directoryAccessControl);
 }
Ejemplo n.º 15
0
		public void ChangeGroupToEveryone ()
		{
			string keyName = @"SOFTWARE\Mono RegistrySecurityTest ChangeGroupToEveryone";

			RegistrySecurity security;
			if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
				Assert.Ignore (); return;
			}

			try {
				using (RegistryKey key = Registry.CurrentUser.CreateSubKey (keyName)) {
					// Before we begin manipulating this, make sure we're in the right spot.
					Assert.AreEqual (key.Name, @"HKEY_CURRENT_USER\" + keyName);

					// Set the group to Everyone.
					SecurityIdentifier worldSid = new SecurityIdentifier ("WD");

					security = key.GetAccessControl ();
					security.SetGroup (worldSid);
					key.SetAccessControl (security);

					// Make sure it actually became Everyone.
					security = key.GetAccessControl ();
					Assert.AreEqual (worldSid, security.GetGroup (typeof(SecurityIdentifier)));
				}
			} finally {
				Registry.CurrentUser.DeleteSubKey (keyName);
			}
		}
Ejemplo n.º 16
0
        public static Mutex GrabMutex(string name)
        {
            var mutexName = "kalixLuceneSegmentMutex_" + name;
            try
            {
                return Mutex.OpenExisting(mutexName);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                var worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                var security = new MutexSecurity();
                var rule = new MutexAccessRule(worldSid, MutexRights.FullControl, AccessControlType.Allow);
                security.AddAccessRule(rule);
                var mutexIsNew = false;
                return new Mutex(false, mutexName, out mutexIsNew, security);
            }
            catch (UnauthorizedAccessException)
            {
                var m = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions);
                var security = m.GetAccessControl();
                var user = Environment.UserDomainName + "\\" + Environment.UserName;
                var rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow);
                security.AddAccessRule(rule);
                m.SetAccessControl(security);

                return Mutex.OpenExisting(mutexName);
            }
        }
 // Gets the login name of the Livelink user that the specified SharePoint user maps to.
 public string GetLoginName(SPUser user) {
     if (user == null)
         throw new ArgumentNullException("user");
     // SPUser.LoginName contains domain\user for web applications with the pure Windows
     // authentication but if the claim-based authentication is used it returns an encoded
     // claim that must be decoded to the actual user login name first.
     var claim = SPClaimProviderManager.Local.ConvertSPUserToClaim(user);
     string login;
     if (SPClaimTypes.Equals(claim.ClaimType, SPClaimTypes.UserLogonName) ||
         SPClaimTypes.Equals(claim.ClaimType,
             "http://schemas.microsoft.com/sharepoint/2009/08/claims/processidentitylogonname")) {
         login = claim.Value;
     } else if (SPClaimTypes.Equals(claim.ClaimType, SPClaimTypes.UserIdentifier) ||
          SPClaimTypes.Equals(claim.ClaimType,
              "http://schemas.microsoft.com/sharepoint/2009/08/claims/processidentitysid") ||
          SPClaimTypes.Equals(claim.ClaimType,
              "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid")) {
         var identifier = new SecurityIdentifier(claim.Value);
         login = identifier.Translate(typeof(NTAccount)).Value;
     } else {
         throw new ApplicationException(
             "No claim with either user name or SID was found to infer the login name from.");
     }
     // Here we assume either plain user name or a combination with the Windows domain.
     var parts = login.Split('\\');
     var name = parts.Length > 1 ? parts[1] : login;
     var domain = parts.Length > 1 ? parts[0] : "";
     return Pattern.ReplaceParameter("login", login).ReplaceParameter("user", name).
         ReplaceParameter("domain", domain);
 }
Ejemplo n.º 18
0
 public void FromBytes(byte[] bytes)
 {
     using (var stream = new MemoryStream(bytes, false))
     using (var reader = new BinaryReader(stream))
     {
         Type = (WinBioIdentityType)reader.ReadInt32();
         switch (Type)
         {
             case WinBioIdentityType.Null:
                 Null = reader.ReadInt32();
                 break;
             case WinBioIdentityType.Wildcard:
                 Wildcard = reader.ReadInt32();
                 break;
             case WinBioIdentityType.GUID:
                 TemplateGuid = new Guid(reader.ReadBytes(16));
                 break;
             case WinBioIdentityType.SID:
                 AccountSidSize = reader.ReadInt32();
                 AccountSid = new SecurityIdentifier(reader.ReadBytes(AccountSidSize), 0);
                 break;
             default:
                 throw new ArgumentOutOfRangeException();
         }
     }
 }
Ejemplo n.º 19
0
 public SamDomain OpenDomain(SecurityIdentifier domainSid, SamDomainAccessMask accessMask)
 {
     SafeSamHandle domainHandle;
     NtStatus result = NativeMethods.SamOpenDomain(this.Handle, accessMask, domainSid, out domainHandle);
     Validator.AssertSuccess(result);
     return new SamDomain(domainHandle);
 }
Ejemplo n.º 20
0
        protected override void SetUp()
        {
            MsmqUtil.Delete(InputQueueName);

            _handlerActivator = new BuiltinHandlerActivator();

            _bus = Configure.With(_handlerActivator)
                .Logging(l => l.Console())
                .Transport(t =>
                {
                    t.UseMsmq(InputQueueName)
                        .OnCreated(queue =>
                        {
                            queue.ResetPermissions();

                            var user = new SecurityIdentifier(WellKnownSidType.WorldSid, null)
                                .Translate(typeof(NTAccount))
                                .ToString();

                            queue.SetPermissions(user, MessageQueueAccessRights.FullControl);
                        });
                })
                .Routing(r => r.TypeBased().Map<string>(InputQueueName))
                .Options(o => o.SetNumberOfWorkers(1))
                .Start();

            Using(_bus);
        }
Ejemplo n.º 21
0
      public static SecurityIdentifier GetSidFromClaim(string claimValue)
      {
         SecurityIdentifier sid = null;

         SPClaimProviderManager claimManager = SPClaimProviderManager.Local;
         if (claimManager == null)
         {
            throw new ApplicationException("Unable to access the claims provider manager.");
         }
         try
         {
            SPClaim claim = claimManager.DecodeClaim(claimValue);
            if (claim.OriginalIssuer.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
               if (claim.ClaimType.Equals(Microsoft.IdentityModel.Claims.ClaimTypes.GroupSid, StringComparison.OrdinalIgnoreCase))
               {
                  sid = new SecurityIdentifier(claim.Value);
               }
               else if (claim.ClaimType.Equals(Microsoft.SharePoint.Administration.Claims.SPClaimTypes.UserLogonName, StringComparison.OrdinalIgnoreCase))
               {
                  NTAccount userAccount = new NTAccount(claim.Value);
                  sid = (SecurityIdentifier)userAccount.Translate(typeof(SecurityIdentifier));
               }
            }
         }
         catch (ArgumentException currentException)
         {
            GlymaSearchLogger.WriteTrace(LogCategoryId.Security, TraceSeverity.Unexpected, "The following exception occured when attempting to decode the claim, " + claimValue + " : " + currentException.ToString());
         }

         return sid;
      }
Ejemplo n.º 22
0
        public static void GetUser(SecurityIdentifier sid, StringBuilder sb, StringBuilder referencedDomainName, StringBuilder name)
        {
            try
            {
                if (sid == null)
                    return;
                sb.Append("; User=");
                referencedDomainName.Remove(0, referencedDomainName.Length);
                name.Remove(0, name.Length);

                var b = new byte[sid.BinaryLength];
                sid.GetBinaryForm(b, 0);
                var cchName = (uint)name.Capacity;
                var cchReferencedDomainName = (uint)referencedDomainName.Capacity;
                SidHelper.SidNameUse sidUse;
                if (SidHelper.LookupAccountSid(null, b, name, ref cchName, referencedDomainName,
                                               ref cchReferencedDomainName,
                                               out sidUse))
                {
                    if (referencedDomainName.Length > 0)
                        sb.Append(referencedDomainName).Append('\\');
                    sb.Append(name);
                    return;
                }
            }
            catch
            {
            }
            sb.Append(sid);
        }
Ejemplo n.º 23
0
        public static string GetProfileDir(SecurityIdentifier sid)
        {
            //"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-534125731-1308685933-1530606844-1000}"
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(ROOT_PROFILE_KEY))
            {
                if (key != null)
                {
                    foreach (string keyName in key.GetSubKeyNames())
                    {
                        if (keyName == sid.ToString())
                        {
                            using(RegistryKey subKey = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, keyName)))
                            {
                                return (string) subKey.GetValue("ProfileImagePath", null, RegistryValueOptions.None);
                            }
                        }
                    }

                    throw new KeyNotFoundException(string.Format("Unable to find value for: {0}", sid));
                }
                else
                {
                    throw new KeyNotFoundException(string.Format("Unable to open registry key"));
                }
            }
        }
Ejemplo n.º 24
0
 internal AppPool(string appPoolId, bool enabled, SecurityIdentifier securityIdentifier)
 {
     this.apps = new List<App>();
     this.appPoolId = appPoolId;
     this.enabled = enabled;
     this.securityIdentifier = securityIdentifier;
 }
Ejemplo n.º 25
0
		public RawSecurityDescriptor (byte[] binaryForm, int offset)
		{
			if (binaryForm == null)
				throw new ArgumentNullException("binaryForm");
			
			if (offset < 0 || offset > binaryForm.Length - 0x14)
				throw new ArgumentOutOfRangeException("offset", offset, "Offset out of range");
			
			if (binaryForm[offset] != 1)
				throw new ArgumentException("Unrecognized Security Descriptor revision.", "binaryForm");
			
			resourcemgr_control = binaryForm[offset + 0x01];
			control_flags = (ControlFlags)ReadUShort(binaryForm, offset + 0x02);
			
			int ownerPos = ReadInt(binaryForm, offset + 0x04);
			int groupPos = ReadInt(binaryForm, offset + 0x08);
			int saclPos = ReadInt(binaryForm, offset + 0x0C);
			int daclPos = ReadInt(binaryForm, offset + 0x10);
			
			if (ownerPos != 0)
				owner_sid = new SecurityIdentifier(binaryForm, ownerPos);
			
			if (groupPos != 0)
				group_sid = new SecurityIdentifier(binaryForm, groupPos);
			
			if (saclPos != 0)
				system_acl = new RawAcl(binaryForm, saclPos);
			
			if (daclPos != 0)
				discretionary_acl = new RawAcl(binaryForm, daclPos);
		}
Ejemplo n.º 26
0
        private static bool TestAddAccess(DiscretionaryAcl discretionaryAcl, RawAcl rawAcl, AccessControlType accessControlType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
        {
            bool result = true;
            byte[] dAclBinaryForm = null;
            byte[] rAclBinaryForm = null;

            discretionaryAcl.AddAccess(accessControlType, sid, accessMask, inheritanceFlags, propagationFlags);
            if (discretionaryAcl.Count == rawAcl.Count &&
                discretionaryAcl.BinaryLength == rawAcl.BinaryLength)
            {

                dAclBinaryForm = new byte[discretionaryAcl.BinaryLength];
                rAclBinaryForm = new byte[rawAcl.BinaryLength];
                discretionaryAcl.GetBinaryForm(dAclBinaryForm, 0);
                rawAcl.GetBinaryForm(rAclBinaryForm, 0);
                if (!Utils.IsBinaryFormEqual(dAclBinaryForm, rAclBinaryForm))
                    result = false;

                //redundant index check

                for (int i = 0; i < discretionaryAcl.Count; i++)
                {
                    if (!Utils.IsAceEqual(discretionaryAcl[i], rawAcl[i]))
                    {

                        result = false;
                        break;
                    }
                }
            }
            else
                result = false;

            return result;
        }
Ejemplo n.º 27
0
        public SidWrapper FindSid(string account)
        {
            SecurityIdentifier sid = null;
            try
            {
                // first, let's try this as a sid (SDDL) string
                sid = new SecurityIdentifier(account);

                return new SidWrapper { Sid = sid};
            }
            catch
            {
            }

            try
            {
                // maybe it's an account/group name
                var name = new NTAccount(account);
                sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
                if (sid != null)
                {
                    return new SidWrapper { Sid = sid };
                }
            }
            catch
            {
            }

            return null;
        }
Ejemplo n.º 28
0
        private static bool TestRemoveAudit(SystemAcl systemAcl, RawAcl rawAcl, AuditFlags auditFlag, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, bool removePossible)
        {
            bool result = true;
            bool isRemoved = false;
            byte[] sAclBinaryForm = null;
            byte[] rAclBinaryForm = null;
            isRemoved = systemAcl.RemoveAudit(auditFlag, sid, accessMask, inheritanceFlags, propagationFlags);
            if ((isRemoved == removePossible) &&
                (systemAcl.Count == rawAcl.Count) &&
                (systemAcl.BinaryLength == rawAcl.BinaryLength))
            {
                sAclBinaryForm = new byte[systemAcl.BinaryLength];
                rAclBinaryForm = new byte[rawAcl.BinaryLength];
                systemAcl.GetBinaryForm(sAclBinaryForm, 0);
                rawAcl.GetBinaryForm(rAclBinaryForm, 0);

                if (!Utils.IsBinaryFormEqual(sAclBinaryForm, rAclBinaryForm))
                    result = false;
                //redundant index check
                for (int i = 0; i < systemAcl.Count; i++)
                {
                    if (!Utils.IsAceEqual(systemAcl[i], rawAcl[i]))
                    {
                        result = false;
                        break;
                    }
                }
            }
            else
                result = false;
            return result;
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            bool success = false;
            try
            {
                Sid = new SecurityIdentifier(textBoxSid.Text);
                success = true;
            }
            catch (Exception)
            {
            }

            if (!success)
            {
                try
                {
                    NTAccount acct = new NTAccount(textBoxSid.Text);
                    Sid = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
                    success = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (success)
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }
Ejemplo n.º 30
0
    private void _init() {
      var physicalApplicationPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
      physicalApplicationPath = Utl.NormalizeDir(Directory.GetParent(physicalApplicationPath).FullName);
      this.logFileName = physicalApplicationPath + "xlfrpt2_srvc.log";
      this.log_msg("*************************************** Инициализация \"Очереди отчетов\"... ***************************************************");
      this.log_msg("\tЗагрузка конфигурации...");
      this._cfg = CConfigSys.load(physicalApplicationPath, this.logFileName);
      this._cfg.msgLogWriter = this.log_msg;
      this._cfg.errLogWriter = this.log_err;
      this.log_msg("\tКонфигурация загружена.");

      this.log_msg("\tИнициализация сервера Ipc...");
      // Create the server channel.

      SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
      NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount;

      IDictionary channelProperties = new Hashtable();
      channelProperties["portName"] = "Bio.Handlers.XLFRpt2.CQueueRemoteControl.Ipc";
      channelProperties["exclusiveAddressUse"] = false;
      channelProperties["authorizedGroup"] = account.Value;
      channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
      IpcChannel serverChannel = new IpcChannel(channelProperties, null, null);
      ChannelServices.RegisterChannel(serverChannel, false);

      // Expose an object for remote calls.
      RemotingConfiguration.RegisterWellKnownServiceType(
              typeof(CQueueRemoteControl), "QueueRemoteControl.rem",
              WellKnownObjectMode.Singleton);

      this.log_msg("\tСервер Ipc инициализирован.");
      this.log_msg("*************************************** Инициализация \"Очереди отчетов\" выполнена. ***************************************************");
    }
Ejemplo n.º 31
0
    public List <string> GetNestedGroupMembershipsByTokenGroup(string userDN, string psenha)
    {
        List <string> nestedGroups = new List <string>();
        string        conexaoAD    = ConfigurationManager.AppSettings["StringLDAP"];

        DirectoryEntry userEnrty = new DirectoryEntry(conexaoAD, userDN, psenha);

        // Use RefreshCach para obter os tokenGroups do atributo construído.
        userEnrty.RefreshCache(new string[] { "tokenGroups" });

        foreach (byte[] sid in userEnrty.Properties["tokenGroups"])
        {
            string         groupSID  = new System.Security.Principal.SecurityIdentifier(sid, 0).ToString();
            DirectoryEntry grpuEnrty = new DirectoryEntry(conexaoAD, userDN, psenha);
            nestedGroups.Add(grpuEnrty.Properties["samAccountName"][0].ToString());
        }

        return(nestedGroups);
    }
        public static List <ADGroup> GetADGroups(IdentityReferenceCollection Groups)
        {
            List <ADGroup> aDGroups = new List <ADGroup>();

            try
            {
                foreach (IdentityReference g in Groups)
                {
                    string groupName = new System.Security.Principal.SecurityIdentifier(g.Value).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                    aDGroups.Add(new ADGroup()
                    {
                        Name        = groupName,
                        DisplayName = g.Value
                    }
                                 );
                }
            }
            catch (Exception ex)
            {
                //TODO: Log
            }

            return(aDGroups);
        }
Ejemplo n.º 33
0
        public static void Add_DomainObjectAcl(Args_Add_DomainObjectAcl args = null)
        {
            if (args == null)
            {
                args = new Args_Add_DomainObjectAcl();
            }

            var TargetSearcherArguments = new Args_Get_DomainObject
            {
                Properties      = new[] { "distinguishedname" },
                Raw             = true,
                Domain          = args.TargetDomain,
                LDAPFilter      = args.TargetLDAPFilter,
                SearchBase      = args.TargetSearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var PrincipalSearcherArguments = new Args_Get_DomainObject
            {
                Identity        = args.PrincipalIdentity,
                Properties      = new[] { "distinguishedname", "objectsid" },
                Domain          = args.PrincipalDomain,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };
            var Principals = GetDomainObject.Get_DomainObject(PrincipalSearcherArguments);

            if (Principals == null)
            {
                throw new Exception($@"Unable to resolve principal: {args.PrincipalIdentity}");
            }

            TargetSearcherArguments.Identity = args.TargetIdentity;
            var Targets = GetDomainObject.Get_DomainObject(TargetSearcherArguments);

            foreach (SearchResult TargetObject in Targets)
            {
                var InheritanceType = System.DirectoryServices.ActiveDirectorySecurityInheritance.None;
                var ControlType     = System.Security.AccessControl.AccessControlType.Allow;
                var ACEs            = new List <System.DirectoryServices.ActiveDirectoryAccessRule>();

                var GUIDs = new List <string>();
                if (args.RightsGUID != null)
                {
                    GUIDs.Add(args.RightsGUID.ToString());
                }
                else
                {
                    switch (args.Rights)
                    {
                    // ResetPassword doesn't need to know the user's current password
                    case Rights.ResetPassword:
                        GUIDs.Add("00299570-246d-11d0-a768-00aa006e0529");
                        break;

                    // allows for the modification of group membership
                    case Rights.WriteMembers:
                        GUIDs.Add("bf9679c0 -0de6-11d0-a285-00aa003049e2");
                        break;

                    // 'DS-Replication-Get-Changes' = 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2
                    // 'DS-Replication-Get-Changes-All' = 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2
                    // 'DS-Replication-Get-Changes-In-Filtered-Set' = 89e95b76-444d-4c62-991a-0facbeda640c
                    // when applied to a domain's ACL, allows for the use of DCSync
                    case Rights.DCSync:
                        GUIDs.Add("1131f6aa-9c07-11d1-f79f-00c04fc2dcd2");
                        GUIDs.Add("1131f6ad-9c07-11d1-f79f-00c04fc2dcd2");
                        GUIDs.Add("89e95b76-444d-4c62-991a-0facbeda640c");
                        break;
                    }
                }

                foreach (LDAPProperty PrincipalObject in Principals)
                {
                    Logger.Write_Verbose($@"[Add-DomainObjectAcl] Granting principal {PrincipalObject.distinguishedname} '{args.Rights}' on {TargetObject.Properties["distinguishedname"][0]}");

                    try
                    {
                        var Identity = new System.Security.Principal.SecurityIdentifier(PrincipalObject.objectsid[0]);

                        if (GUIDs != null)
                        {
                            foreach (var GUID in GUIDs)
                            {
                                var NewGUID  = new Guid(GUID);
                                var ADRights = System.DirectoryServices.ActiveDirectoryRights.ExtendedRight;
                                ACEs.Add(new System.DirectoryServices.ActiveDirectoryAccessRule(Identity, ADRights, ControlType, NewGUID, InheritanceType));
                            }
                        }
                        else
                        {
                            // deault to GenericAll rights
                            var ADRights = System.DirectoryServices.ActiveDirectoryRights.GenericAll;
                            ACEs.Add(new System.DirectoryServices.ActiveDirectoryAccessRule(Identity, ADRights, ControlType, InheritanceType));
                        }

                        // add all the new ACEs to the specified object directory entry
                        foreach (var ACE in ACEs)
                        {
                            Logger.Write_Verbose($@"[Add-DomainObjectAcl] Granting principal {PrincipalObject.distinguishedname} rights GUID '{ACE.ObjectType}' on {TargetObject.Properties["distinguishedname"][0]}");
                            var TargetEntry = TargetObject.GetDirectoryEntry();
                            TargetEntry.Options.SecurityMasks = SecurityMasks.Dacl;
                            TargetEntry.ObjectSecurity.AddAccessRule(ACE);
                            TargetEntry.CommitChanges();
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[Add-DomainObjectAcl] Error granting principal {PrincipalObject.distinguishedname} '{args.Rights}' on {TargetObject.Properties["distinguishedname"][0]}: {e}");
                    }
                }
            }
        }
Ejemplo n.º 34
0
        public static LDAPProperty Convert_LDAPProperty(System.DirectoryServices.ResultPropertyCollection Properties)
        {
            var ObjectProperties = new LDAPProperty();

            foreach (string propName in Properties.PropertyNames)
            {
                if (string.Compare(propName, @"adspath", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    if (string.Compare(propName, @"objectsid", StringComparison.OrdinalIgnoreCase) == 0 ||
                        string.Compare(propName, @"sidhistory", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // convert all listed sids (i.e. if multiple are listed in sidHistory)
                        var values = new List <string>();
                        foreach (var property in Properties[propName])
                        {
                            var sid = new System.Security.Principal.SecurityIdentifier(property as byte[], 0);
                            values.Add(sid.Value);
                        }
                        if (string.Compare(propName, @"objectsid", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.objectsid = values.ToArray();
                        }
                        else
                        {
                            ObjectProperties.sidhistory = values.ToArray();
                        }
                    }
                    else if (string.Compare(propName, @"grouptype", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.grouptype = (GroupType)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"samaccounttype", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.samaccounttype = (SamAccountType)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"objectguid", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // convert the GUID to a string
                        ObjectProperties.objectguid = new Guid(Properties[propName][0] as byte[]).ToString();
                    }
                    else if (string.Compare(propName, @"useraccountcontrol", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.useraccountcontrol = (UACEnumValue)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"ntsecuritydescriptor", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // $ObjectProperties[$_] = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0
                        var Descriptor = new System.Security.AccessControl.RawSecurityDescriptor(Properties[propName][0] as byte[], 0);
                        if (Descriptor.Owner != null)
                        {
                            ObjectProperties.Owner = Descriptor.Owner;
                        }
                        if (Descriptor.Group != null)
                        {
                            ObjectProperties.Group = Descriptor.Group;
                        }
                        if (Descriptor.DiscretionaryAcl != null)
                        {
                            ObjectProperties.DiscretionaryAcl = Descriptor.DiscretionaryAcl;
                        }
                        if (Descriptor.SystemAcl != null)
                        {
                            ObjectProperties.SystemAcl = Descriptor.SystemAcl;
                        }
                    }
                    else if (string.Compare(propName, @"accountexpires", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if ((long)Properties[propName][0] >= DateTime.MaxValue.Ticks)
                        {
                            ObjectProperties.accountexpires = "NEVER";
                        }
                        else
                        {
                            ObjectProperties.accountexpires = DateTime.FromFileTime((long)Properties[propName][0]);
                        }
                    }
                    else if (string.Compare(propName, @"lastlogon", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"lastlogontimestamp", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"pwdlastset", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"lastlogoff", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"badPasswordTime", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"whencreated", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"whenchanged", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        DateTime dt;
                        // convert timestamps
                        if (Properties[propName][0] is System.MarshalByRefObject)
                        {
                            // if we have a System.__ComObject
                            var Temp = Properties[propName][0];
                            var High = (Int32)Temp.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            var Low  = (Int32)Temp.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            dt = DateTime.FromFileTime(Int64.Parse(string.Format("0x{0:x8}{1:x8}", High, Low)));
                        }
                        if (Properties[propName][0] is System.DateTime)
                        {
                            dt = (DateTime)Properties[propName][0];
                        }
                        else
                        {
                            // otherwise just a string
                            dt = DateTime.FromFileTime((long)Properties[propName][0]);
                        }
                        if (string.Compare(propName, @"lastlogon", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.lastlogon = dt;
                        }
                        else if (string.Compare(propName, @"lastlogontimestamp", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.lastlogontimestamp = dt;
                        }
                        else if (string.Compare(propName, @"pwdlastset", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.pwdlastset = dt;
                        }
                        else if (string.Compare(propName, @"lastlogoff", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.lastlogoff = dt;
                        }
                        else if (string.Compare(propName, @"badPasswordTime", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.badPasswordTime = dt;
                        }
                        else if (string.Compare(propName, @"whencreated", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.whencreated = dt;
                        }
                        else if (string.Compare(propName, @"whenchanged", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.whenchanged = dt;
                        }
                    }
                    else if (string.Compare(propName, @"name", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.name = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"distinguishedname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.distinguishedname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"dnsrecord", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.dnsrecord = Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"samaccountname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.samaccountname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"member", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.member = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"memberof", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.memberof = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"cn", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.cn = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"objectclass", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.objectclass = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"managedby", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.managedby = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"siteobject", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.siteobject = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"ServicePrincipalName", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.ServicePrincipalName = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"dnshostname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.dnshostname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"gplink", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.gplink = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"gpoptions", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.gpoptions = (int)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"displayname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.displayname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"path", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.path = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"siteobjectbl", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.siteobjectbl = Properties[propName][0] as string;
                    }
                    else if (Properties[propName][0] is System.MarshalByRefObject)
                    {
                        // try to convert misc com objects
                        var Prop = Properties[propName];
                        try
                        {
                            var Temp = Properties[propName][0];
                            var High = (Int32)Temp.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            var Low  = (Int32)Temp.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            ObjectProperties.others.Add(propName, Int64.Parse(string.Format("0x{0:x8}{1:x8}", High, Low)));
                        }
                        catch (Exception e)
                        {
                            Logger.Write_Verbose($@"[Convert-LDAPProperty] error: {e}");
                            ObjectProperties.others.Add(propName, Prop[0]);
                        }
                    }
                    else if (Properties[propName].Count == 1)
                    {
                        ObjectProperties.others.Add(propName, Properties[propName][0]);
                    }
                    else
                    {
                        ObjectProperties.others.Add(propName, Properties[propName]);
                    }
                }
            }
            return(ObjectProperties);
        }
Ejemplo n.º 35
0
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

            //
            // Target type must be a subclass of IdentityReference
            //

            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            Contract.EndContractBlock();

            //
            // if the source collection is empty, just return an empty collection
            //
            if (Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }

            int SourceSidsCount       = 0;
            int SourceNTAccountsCount = 0;

            //
            // First, see how many of each of the source types we have.
            // The cases where source type == target type require no conversion.
            //

            for (int i = 0; i < Identities.Count; i++)
            {
                Type type = Identities[i].GetType();

                if (type == targetType)
                {
                    continue;
                }
                else if (type == typeof(SecurityIdentifier))
                {
                    SourceSidsCount += 1;
                }
                else if (type == typeof(NTAccount))
                {
                    SourceNTAccountsCount += 1;
                }
                else
                {
                    //
                    // Rare case that we have defined a type of identity reference and
                    // not included it in the code logic above (this is more like a


                    Contract.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                    throw new SystemException();
                }
            }

            bool Homogeneous = false;
            IdentityReferenceCollection SourceSids       = null;
            IdentityReferenceCollection SourceNTAccounts = null;

            if (SourceSidsCount == Count)
            {
                Homogeneous = true;
                SourceSids  = this;
            }
            else if (SourceSidsCount > 0)
            {
                SourceSids = new IdentityReferenceCollection(SourceSidsCount);
            }

            if (SourceNTAccountsCount == Count)
            {
                Homogeneous      = true;
                SourceNTAccounts = this;
            }
            else if (SourceNTAccountsCount > 0)
            {
                SourceNTAccounts = new IdentityReferenceCollection(SourceNTAccountsCount);
            }
            //
            // Repackage only if the source is not homogeneous (contains different source types)
            //

            IdentityReferenceCollection Result = null;

            if (!Homogeneous)
            {
                Result = new IdentityReferenceCollection(Identities.Count);

                for (int i = 0; i < Identities.Count; i++)
                {
                    IdentityReference id = this[i];

                    Type type = id.GetType();

                    if (type == targetType)
                    {
                        continue;
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        SourceSids.Add(id);
                    }
                    else if (type == typeof(NTAccount))
                    {
                        SourceNTAccounts.Add(id);
                    }
                    else
                    {
                        //
                        // Rare case that we have defined a type of identity reference and
                        // not included it in the code logic above (this is more like a


                        Contract.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                        throw new SystemException();
                    }
                }
            }

            bool someFailed = false;
            IdentityReferenceCollection TargetSids = null, TargetNTAccounts = null;

            if (SourceSidsCount > 0)
            {
                TargetSids = SecurityIdentifier.Translate(SourceSids, targetType, out someFailed);

                if (Homogeneous && !(forceSuccess && someFailed))
                {
                    Result = TargetSids;
                }
            }

            if (SourceNTAccountsCount > 0)
            {
                TargetNTAccounts = NTAccount.Translate(SourceNTAccounts, targetType, out someFailed);

                if (Homogeneous && !(forceSuccess && someFailed))
                {
                    Result = TargetNTAccounts;
                }
            }

            if (forceSuccess && someFailed)
            {
                //
                // Need to throw an exception here and provide information regarding
                // which identity references could not be translated to the target type
                //

                Result = new IdentityReferenceCollection();

                if (TargetSids != null)
                {
                    foreach (IdentityReference id in TargetSids)
                    {
                        if (id.GetType() != targetType)
                        {
                            Result.Add(id);
                        }
                    }
                }

                if (TargetNTAccounts != null)
                {
                    foreach (IdentityReference id in TargetNTAccounts)
                    {
                        if (id.GetType() != targetType)
                        {
                            Result.Add(id);
                        }
                    }
                }

                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), Result);
            }
            else if (!Homogeneous)
            {
                SourceSidsCount       = 0;
                SourceNTAccountsCount = 0;

                Result = new IdentityReferenceCollection(Identities.Count);

                for (int i = 0; i < Identities.Count; i++)
                {
                    IdentityReference id = this[i];

                    Type type = id.GetType();

                    if (type == targetType)
                    {
                        Result.Add(id);
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        Result.Add(TargetSids[SourceSidsCount++]);
                    }
                    else if (type == typeof(NTAccount))
                    {
                        Result.Add(TargetNTAccounts[SourceNTAccountsCount++]);
                    }
                    else
                    {
                        //
                        // Rare case that we have defined a type of identity reference and
                        // not included it in the code logic above (this is more like a


                        Contract.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                        throw new SystemException();
                    }
                }
            }

            return(Result);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Creates a collection of SID claims that represent the users groups.
        /// </summary>
        private void AddGroupSidClaims(List <Claim> instanceClaims)
        {
            // special case the anonymous identity.
            if (_safeTokenHandle.IsInvalid)
            {
                return;
            }

            SafeLocalAllocHandle safeAllocHandle             = SafeLocalAllocHandle.InvalidHandle;
            SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle;

            try
            {
                // Retrieve the primary group sid
                safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup);
                Interop.TOKEN_PRIMARY_GROUP primaryGroup    = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure <Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle());
                SecurityIdentifier          primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true);

                // only add one primary group sid
                bool foundPrimaryGroupSid = false;

                // Retrieve all group sids, primary group sid is one of them
                safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups);
                int    count             = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle());
                IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf <Interop.TOKEN_GROUPS>("Groups"));
                Claim  claim;
                for (int i = 0; i < count; ++i)
                {
                    Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure <Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes);
                    uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
                    SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true);

                    if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
                    {
                        if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
                        {
                            claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
                            claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
                            instanceClaims.Add(claim);
                            foundPrimaryGroupSid = true;
                        }
                        //Primary group sid generates both regular groupsid claim and primary groupsid claim
                        claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
                        claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
                        instanceClaims.Add(claim);
                    }
                    else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
                    {
                        if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
                        {
                            claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
                            claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
                            instanceClaims.Add(claim);
                            foundPrimaryGroupSid = true;
                        }
                        //Primary group sid generates both regular groupsid claim and primary groupsid claim
                        claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
                        claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
                        instanceClaims.Add(claim);
                    }
                    pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf <Interop.SID_AND_ATTRIBUTES>());
                }
            }
            finally
            {
                safeAllocHandle.Dispose();
                safeAllocHandlePrimaryGroup.Dispose();
            }
        }
Ejemplo n.º 37
0
 public SecurityIdentifierElement(System.Security.Principal.SecurityIdentifier sid) : this()
 {
     this.SecurityIdentifier = sid;
 }
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            if (this.Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }
            int num  = 0;
            int num2 = 0;

            for (int i = 0; i < this.Identities.Count; i++)
            {
                Type type = this.Identities[i].GetType();
                if (!(type == targetType))
                {
                    if (type == typeof(SecurityIdentifier))
                    {
                        num++;
                    }
                    else
                    {
                        if (!(type == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        num2++;
                    }
                }
            }
            bool flag = false;
            IdentityReferenceCollection identityReferenceCollection  = null;
            IdentityReferenceCollection identityReferenceCollection2 = null;

            if (num == this.Count)
            {
                flag = true;
                identityReferenceCollection = this;
            }
            else if (num > 0)
            {
                identityReferenceCollection = new IdentityReferenceCollection(num);
            }
            if (num2 == this.Count)
            {
                flag = true;
                identityReferenceCollection2 = this;
            }
            else if (num2 > 0)
            {
                identityReferenceCollection2 = new IdentityReferenceCollection(num2);
            }
            IdentityReferenceCollection identityReferenceCollection3 = null;

            if (!flag)
            {
                identityReferenceCollection3 = new IdentityReferenceCollection(this.Identities.Count);
                for (int j = 0; j < this.Identities.Count; j++)
                {
                    IdentityReference identityReference = this[j];
                    Type type2 = identityReference.GetType();
                    if (!(type2 == targetType))
                    {
                        if (type2 == typeof(SecurityIdentifier))
                        {
                            identityReferenceCollection.Add(identityReference);
                        }
                        else
                        {
                            if (!(type2 == typeof(NTAccount)))
                            {
                                throw new SystemException();
                            }
                            identityReferenceCollection2.Add(identityReference);
                        }
                    }
                }
            }
            bool flag2 = false;
            IdentityReferenceCollection identityReferenceCollection4 = null;
            IdentityReferenceCollection identityReferenceCollection5 = null;

            if (num > 0)
            {
                identityReferenceCollection4 = SecurityIdentifier.Translate(identityReferenceCollection, targetType, out flag2);
                if (flag && (!forceSuccess || !flag2))
                {
                    identityReferenceCollection3 = identityReferenceCollection4;
                }
            }
            if (num2 > 0)
            {
                identityReferenceCollection5 = NTAccount.Translate(identityReferenceCollection2, targetType, out flag2);
                if (flag && (!forceSuccess || !flag2))
                {
                    identityReferenceCollection3 = identityReferenceCollection5;
                }
            }
            if (forceSuccess && flag2)
            {
                identityReferenceCollection3 = new IdentityReferenceCollection();
                if (identityReferenceCollection4 != null)
                {
                    foreach (IdentityReference identityReference2 in identityReferenceCollection4)
                    {
                        if (identityReference2.GetType() != targetType)
                        {
                            identityReferenceCollection3.Add(identityReference2);
                        }
                    }
                }
                if (identityReferenceCollection5 != null)
                {
                    foreach (IdentityReference identityReference3 in identityReferenceCollection5)
                    {
                        if (identityReference3.GetType() != targetType)
                        {
                            identityReferenceCollection3.Add(identityReference3);
                        }
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), identityReferenceCollection3);
            }
            if (!flag)
            {
                num  = 0;
                num2 = 0;
                identityReferenceCollection3 = new IdentityReferenceCollection(this.Identities.Count);
                for (int k = 0; k < this.Identities.Count; k++)
                {
                    IdentityReference identityReference4 = this[k];
                    Type type3 = identityReference4.GetType();
                    if (type3 == targetType)
                    {
                        identityReferenceCollection3.Add(identityReference4);
                    }
                    else if (type3 == typeof(SecurityIdentifier))
                    {
                        identityReferenceCollection3.Add(identityReferenceCollection4[num++]);
                    }
                    else
                    {
                        if (!(type3 == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        identityReferenceCollection3.Add(identityReferenceCollection5[num2++]);
                    }
                }
            }
            return(identityReferenceCollection3);
        }
Ejemplo n.º 39
0
        static void Main(string[] args)
        {
            string ldapCookie = "adsync-cookie.dat";
            string str_dcName = "dc01.isengard.local";
            bool   firstRun   = true;

            _nullSids  = new ConcurrentDictionary <string, byte>();
            _guidMap   = new ConcurrentDictionary <string, string>();
            _baseGuids = new ConcurrentDictionary <string, string>();
            _baseGuids.TryAdd("user", "bf967aba-0de6-11d0-a285-00aa003049e2");
            _baseGuids.TryAdd("computer", "bf967a86-0de6-11d0-a285-00aa003049e2");
            _baseGuids.TryAdd("group", "bf967a9c-0de6-11d0-a285-00aa003049e2");
            _baseGuids.TryAdd("domain", "19195a5a-6da0-11d0-afd3-00c04fd930c9");
            _baseGuids.TryAdd("gpo", "f30e3bc2-9ff0-11d1-b603-0000f80367c1");

            System.DirectoryServices.DirectoryEntry rootDSE = new System.DirectoryServices.DirectoryEntry("LDAP://rootDSE");
            System.Net.NetworkCredential            cr      = new System.Net.NetworkCredential(@"Administrator", "1qazxsw2..", "isengard.local");
            LdapConnection connection = new LdapConnection(str_dcName);

            connection.Credential = cr;
            connection.Bind();

            DirectorySynchronization sync = new DirectorySynchronization();
            DirectorySearcher        src2 = new DirectorySearcher();

            if (File.Exists(ldapCookie))
            {
                byte[] byteCookie = File.ReadAllBytes(ldapCookie);
                sync.ResetDirectorySynchronizationCookie(byteCookie);

                firstRun = false;
            }
            src2.DirectorySynchronization = sync;

            foreach (SearchResult res in src2.FindAll())
            {
                ResultPropertyCollection fields = res.Properties;

                foreach (String ldapField in fields.PropertyNames)
                {
                    foreach (Object myCollection in fields[ldapField])
                    {
                        if (!firstRun)
                        {
                            if (ldapField == "distinguishedname")
                            {
                                Console.WriteLine(String.Format("[+] DN = {0}", myCollection));
                            }

                            if (ldapField == "ntsecuritydescriptor")
                            {
                                Console.WriteLine("[+] Detected ACL Change: ");
                                var aces          = new List <ACL>();
                                var newDescriptor = new ActiveDirectorySecurity();
                                newDescriptor.SetSecurityDescriptorBinaryForm((byte[])myCollection);
                                // todo add owner

                                foreach (ActiveDirectoryAccessRule ace in newDescriptor.GetAccessRules(true, true, typeof(SecurityIdentifier)))
                                {
                                    //Ignore null aces
                                    if (ace == null)
                                    {
                                        continue;
                                    }

                                    //Ignore Deny aces
                                    if (!ace.AccessControlType.Equals(AccessControlType.Allow))
                                    {
                                        continue;
                                    }

                                    //Resolve the principal in the ACE
                                    var    principal = GetAcePrincipal(ace, "isengard.local");
                                    string name      = new System.Security.Principal.SecurityIdentifier(principal).Translate(typeof(System.Security.Principal.NTAccount)).ToString();

                                    //If its null, we don't care so move on
                                    if (principal == null)
                                    {
                                        continue;
                                    }


                                    //Interesting Domain ACEs - GenericAll, WriteDacl, WriteOwner, Replication Rights, AllExtendedRights
                                    var rights        = ace.ActiveDirectoryRights;
                                    var objectAceType = ace.ObjectType.ToString();

                                    if (rights.HasFlag(ActiveDirectoryRights.GenericAll))
                                    {
                                        if (objectAceType == AllGuid || objectAceType == "")
                                        {
                                            aces.Add(new ACL
                                            {
                                                AceType       = "",
                                                RightName     = "GenericAll",
                                                PrincipalName = name,
                                                PrincipalType = principal
                                            });
                                        }
                                        //GenericAll includes every other flag, so continue here so we don't duplicate privs
                                        continue;
                                    }

                                    if (rights.HasFlag(ActiveDirectoryRights.WriteDacl))
                                    {
                                        aces.Add(new ACL
                                        {
                                            AceType       = "",
                                            RightName     = "WriteDacl",
                                            PrincipalName = name,
                                            PrincipalType = principal
                                        });
                                    }

                                    if (rights.HasFlag(ActiveDirectoryRights.WriteOwner))
                                    {
                                        aces.Add(new ACL
                                        {
                                            AceType       = "",
                                            RightName     = "WriteOwner",
                                            PrincipalName = name,
                                            PrincipalType = principal
                                        });
                                    }

                                    if (rights.HasFlag(ActiveDirectoryRights.ExtendedRight))
                                    {
                                        if (objectAceType == "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2")
                                        {
                                            aces.Add(new ACL
                                            {
                                                AceType       = "GetChanges",
                                                RightName     = "ExtendedRight",
                                                PrincipalName = name,
                                                PrincipalType = principal
                                            });
                                        }
                                        else if (objectAceType == "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2")
                                        {
                                            aces.Add(new ACL
                                            {
                                                AceType       = "GetChangesAll",
                                                RightName     = "ExtendedRight",
                                                PrincipalName = name,
                                                PrincipalType = principal
                                            });
                                        }
                                        else if (objectAceType == AllGuid || objectAceType == "")
                                        {
                                            aces.Add(new ACL
                                            {
                                                AceType       = "All",
                                                RightName     = "ExtendedRight",
                                                PrincipalName = name,
                                                PrincipalType = principal
                                            });
                                        }
                                    }
                                }


                                foreach (var ace in aces)
                                {
                                    Console.WriteLine(String.Format("[+] {0} has {1}", ace.PrincipalName, ace.RightName));
                                }
                                ;
                            }


                            if (ldapField == "useraccountcontrol")
                            {
                                Console.WriteLine(String.Format("[+] UAC edited: {0}", myCollection));
                            }
                        }
                    }
                }
            }

            File.WriteAllBytes(ldapCookie, sync.GetDirectorySynchronizationCookie());
        }
Ejemplo n.º 40
0
        public static IEnumerable <ACL> Get_DomainObjectAcl(Args_Get_DomainObjectAcl args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainObjectAcl();
            }

            var SearcherArguments = new Args_Get_DomainSearcher
            {
                Properties      = new[] { "samaccountname", "ntsecuritydescriptor", "distinguishedname", "objectsid" },
                SecurityMasks   = args.Sacl ? SecurityMasks.Sacl : SecurityMasks.Dacl,
                Domain          = args.Domain,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };
            var Searcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);

            var DomainGUIDMapArguments = new Args_Get_DomainGUIDMap
            {
                Domain          = args.Domain,
                Server          = args.Server,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Credential      = args.Credential
            };

            // get a GUID -> name mapping
            IDictionary <string, string> GUIDs = null;

            if (args.ResolveGUIDs)
            {
                GUIDs = GetDomainGUIDMap.Get_DomainGUIDMap(DomainGUIDMapArguments);
            }

            var ACLs = new List <ACL>();

            if (Searcher != null)
            {
                var IdentityFilter = "";
                var Filter         = "";
                if (args.Identity != null)
                {
                    foreach (var item in args.Identity)
                    {
                        var IdentityInstance = item.Replace(@"(", @"\28").Replace(@")", @"\29");
                        if (IdentityInstance.IsRegexMatch(@"^S-1-.*"))
                        {
                            IdentityFilter += $@"(objectsid={IdentityInstance})";
                        }
                        else if (IdentityInstance.IsRegexMatch(@"^(CN|OU|DC)=.*"))
                        {
                            IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                            if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                            {
                                // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                // and rebuild the domain searcher
                                var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf("DC=")).Replace("DC=", "").Replace(",", ".");
                                Logger.Write_Verbose($@"[Get-DomainObjectAcl] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                SearcherArguments.Domain = IdentityDomain;
                                Searcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                if (Searcher == null)
                                {
                                    Logger.Write_Warning($@"[Get-DomainObjectAcl] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                }
                            }
                        }
                        else if (IdentityInstance.IsRegexMatch(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$"))
                        {
                            var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                            IdentityFilter += $@"(objectguid={GuidByteString})";
                        }
                        else if (IdentityInstance.Contains('.'))
                        {
                            IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(dnshostname={IdentityInstance}))";
                        }
                        else
                        {
                            IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(displayname={IdentityInstance}))";
                        }
                    }
                }
                if (IdentityFilter != null && IdentityFilter.Trim() != "")
                {
                    Filter += $@"(|{IdentityFilter})";
                }

                if (args.LDAPFilter.IsNotNullOrEmpty())
                {
                    Logger.Write_Verbose($@"[Get-DomainObjectAcl] Using additional LDAP filter: {args.LDAPFilter}");
                    Filter += $@"{args.LDAPFilter}";
                }

                if (Filter.IsNotNullOrEmpty())
                {
                    Searcher.Filter = $@"(&{Filter})";
                }
                Logger.Write_Verbose($@"[Get-DomainObjectAcl] Get-DomainObjectAcl filter string: {Searcher.Filter}");

                var Results = Searcher.FindAll();
                foreach (SearchResult result in Results)
                {
                    var Object = result.Properties;

                    string ObjectSid = null;
                    if (Object["objectsid"] != null && Object["objectsid"].Count > 0 && Object["objectsid"][0] != null)
                    {
                        ObjectSid = new System.Security.Principal.SecurityIdentifier(Object["objectsid"][0] as byte[], 0).Value;
                    }
                    else
                    {
                        ObjectSid = null;
                    }

                    try
                    {
                        var rsd    = new System.Security.AccessControl.RawSecurityDescriptor(Object["ntsecuritydescriptor"][0] as byte[], 0);
                        var rawAcl = args.Sacl ? rsd.SystemAcl : rsd.DiscretionaryAcl;
                        foreach (var ace in rawAcl)
                        {
                            var acl = new ACL {
                                Ace = ace
                            };
                            bool Continue = false;
                            if (args.RightsFilter != null)
                            {
                                string GuidFilter = null;
                                switch (args.RightsFilter.Value)
                                {
                                case Rights.ResetPassword:
                                    GuidFilter = "00299570-246d-11d0-a768-00aa006e0529";
                                    break;

                                case Rights.WriteMembers:
                                    GuidFilter = "bf9679c0-0de6-11d0-a285-00aa003049e2";
                                    break;

                                default:
                                    GuidFilter = "00000000-0000-0000-0000-000000000000";
                                    break;
                                }
                                if (ace is System.Security.AccessControl.ObjectAccessRule)
                                {
                                    if (string.Compare(((object)ace as System.Security.AccessControl.ObjectAccessRule).ObjectType.ToString(), GuidFilter, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        acl.ObjectDN  = Object["distinguishedname"][0] as string;
                                        acl.ObjectSID = ObjectSid;
                                        Continue      = true;
                                    }
                                }
                            }
                            else
                            {
                                acl.ObjectDN  = Object["distinguishedname"][0] as string;
                                acl.ObjectSID = ObjectSid;
                                Continue      = true;
                            }
                            if (Continue)
                            {
                                if (ace is System.Security.AccessControl.KnownAce)
                                {
                                    acl.ActiveDirectoryRights = (System.DirectoryServices.ActiveDirectoryRights)(ace as System.Security.AccessControl.KnownAce).AccessMask;
                                }
                                if (GUIDs != null)
                                {
                                    // if we're resolving GUIDs, map them them to the resolved hash table
                                    if (ace is ObjectAce)
                                    {
                                        try { (acl.Ace as ObjectAce).ObjectAceType = new Guid(GUIDs[(ace as ObjectAce).ObjectAceType.ToString()]); }
                                        catch { }
                                        try { (acl.Ace as ObjectAce).InheritedObjectAceType = new Guid(GUIDs[(ace as ObjectAce).InheritedObjectAceType.ToString()]); }
                                        catch { }
                                    }
                                    else if (ace is ObjectAccessRule)
                                    {
                                        /*try { (acl.Ace as ObjectAccessRule).ObjectType = new Guid(GUIDs[(ace as ObjectAccessRule).ObjectType.ToString()]); }
                                         * catch { }
                                         * try { (acl.Ace as ObjectAccessRule).InheritedObjectType = new Guid(GUIDs[(ace as ObjectAccessRule).InheritedObjectType.ToString()]); }
                                         * catch { }*/
                                    }
                                }

                                ACLs.Add(acl);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[Get-DomainObjectAcl] Error: {e}");
                    }
                }
            }
            return(ACLs);
        }
Ejemplo n.º 41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SafePSID"/> class from a
 /// <see cref="System.Security.Principal.SecurityIdentifier"/> instance.
 /// </summary>
 /// <param name="si">The <see cref="System.Security.Principal.SecurityIdentifier"/> instance.</param>
 public SafePSID(System.Security.Principal.SecurityIdentifier si) : this(si is null ? null : GetBytes(si))
 {
 }
Ejemplo n.º 42
0
        public string Create(IIdentity identity, string audience, List <string> appGroupRegexes)
        {
            var nowUtc       = DateTime.UtcNow;
            var expires      = _settings.TokenExpiryMinutes > 0 ? nowUtc.AddMinutes(_settings.TokenExpiryMinutes) : nowUtc.AddDays(_settings.TokenExpiryDays);
            var centuryBegin = new DateTime(1970, 1, 1);
            var exp          = (long)(new TimeSpan(expires.Ticks - centuryBegin.Ticks).TotalSeconds);
            var now          = (long)(new TimeSpan(nowUtc.Ticks - centuryBegin.Ticks).TotalSeconds);
            var issuer       = _settings.Issuer ?? string.Empty;
            var payload      = new JwtPayload
            {
                { "sub", identity.Name },
                { "unique_name", identity.Name },
                { "iss", issuer },
                { "aud", audience },
                { "iat", now },
                { "nbf", now },
                { "exp", exp },
                { "jti", Guid.NewGuid().ToString("N") }
            };

            var windowsUser = identity as WindowsIdentity;

            // SId
            var claim = windowsUser.Claims.FirstOrDefault(c => c.Type == ClaimTypes.PrimarySid);

            if (claim != null)
            {
                payload.AddClaim(new Claim("sid", claim.Value));
            }

            // Group SId
            if (_settings.IncludeGroupSIdClaims)
            {
                var groupClaims = windowsUser.Claims.Where(c => c.Type == ClaimTypes.GroupSid);
                if (groupClaims != null)
                {
                    foreach (Claim c in groupClaims)
                    {
                        payload.AddClaim(new Claim(c.Type, c.Value));
                    }
                }
            }

            // Group Roles
            if (_settings.IncludeGroupRoleClaims)
            {
                var groupClaims = windowsUser.Claims.Where(c => c.Type == ClaimTypes.GroupSid);
                if (groupClaims != null)
                {
                    foreach (Claim c in groupClaims)
                    {
                        var role = new System.Security.Principal.SecurityIdentifier(c.Value).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                        foreach (var regex in appGroupRegexes)
                        {
                            if (Regex.IsMatch(role, regex))
                            {
                                payload.AddClaim(new Claim("role", role));
                            }
                        }
                    }
                }
            }

            var jwt = new JwtSecurityToken(_jwtHeader, payload);

            return(_jwtSecurityTokenHandler.WriteToken(jwt));
        }
Ejemplo n.º 43
0
        public static void EnumerateLogonSessions(uint currentLUID)
        {
            UInt64   count;
            IntPtr   pLuid;
            IntPtr   pLuidList    = IntPtr.Zero;
            uint     AccessDenied = 0xc0000022;
            DateTime systime      = new DateTime(1601, 1, 1, 0, 0, 0, 0);

            if (LsaEnumerateLogonSessions(out count, out pLuidList) != 0)
            {
                Console.WriteLine("[!] Error running LsaEnumerateLogonSessions()");
                Console.ReadLine();

                return;
            }

            // Sets pLuid to the first LUID structure in the list
            pLuid = pLuidList;

            // count stores number of LUIDs in the list
            for (ulong idx = 0; idx < count; idx++)
            {
                IntPtr pSessionData;
                uint   result = LsaGetLogonSessionData(pLuid, out pSessionData);
                if (result != 0)
                {
                    if (result == AccessDenied)
                    {
                        Console.WriteLine("[!] Access denied enumerating LogonId {0:X2}", pLuid);
                    }
                    else
                    {
                        Console.WriteLine("[!] Unknown error accessing session data for LogonId {0:X2}: {1}", pLuid, result);
                    }
                    continue;
                }

                SECURITY_LOGON_SESSION_DATA sessionData = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(pSessionData, typeof(SECURITY_LOGON_SESSION_DATA));

                if (pSessionData == IntPtr.Zero)
                {
                    // Not a valid logon session
                    continue;
                }

                // Marshal our data
                String username = Marshal.PtrToStringUni(sessionData.Username.buffer).Trim();
                String domain   = Marshal.PtrToStringUni(sessionData.DnsDomainName.buffer).Trim();
                String sid      = new System.Security.Principal.SecurityIdentifier(sessionData.PSiD).Value;
                String package  = Marshal.PtrToStringUni(sessionData.AuthenticationPackage.buffer).Trim();
                SECURITY_LOGON_TYPE logonType = (SECURITY_LOGON_TYPE)sessionData.LogonType;
                DateTime            logonTime = systime.AddTicks((long)sessionData.LoginTime);

                if (domain == "")
                {
                    domain = Marshal.PtrToStringUni(sessionData.LoginDomain.buffer).Trim();
                }

                // Write our data
                Console.WriteLine();
                if (currentLUID == sessionData.LoginID.LowPart)
                {
                    Console.WriteLine("***********Current Session***********");
                }
                Console.WriteLine("LogonID (LUID):     {0}", sessionData.LoginID.LowPart);
                Console.WriteLine("User:               {0}\\{1}", domain, username);
                Console.WriteLine("SID:                {0}", sid);
                Console.WriteLine("Auth Package:       {0}", package);
                Console.WriteLine("Logon Type:         {0}", logonType);
                Console.WriteLine("Logon Time:         {0}", logonTime);
                if (currentLUID == sessionData.LoginID.LowPart)
                {
                    Console.WriteLine("*************************************");
                }
                Console.WriteLine();

                // Bunch of typecasts to essentially move our pointer to the next LUID in the list
                pLuid = (IntPtr)((int)pLuid + Marshal.SizeOf(typeof(LUID)));
                LsaFreeReturnBuffer(pSessionData);
            }
            LsaFreeReturnBuffer(pLuid);
        }
Ejemplo n.º 44
0
 // Summary:
 //     Compares the current System.Security.Principal.SecurityIdentifier object
 //     with the specified System.Security.Principal.SecurityIdentifier object.
 //
 // Parameters:
 //   sid:
 //     The System.Security.Principal.SecurityIdentifier object with which to compare
 //     the current System.Security.Principal.SecurityIdentifier object.
 //
 // Returns:
 //     A signed number indicating the relative values of this instance and sid.Return
 //     Value Description Less than zero This instance is less than sid. Zero This
 //     instance is equal to sid. Greater than zero This instance is greater than
 //     sid.
 // public int CompareTo(SecurityIdentifier sid);
 //
 // Summary:
 //     Indicates whether the specified System.Security.Principal.SecurityIdentifier
 //     object is equal to the current System.Security.Principal.SecurityIdentifier
 //     object.
 //
 // Parameters:
 //   sid:
 //     The System.Security.Principal.SecurityIdentifier object to compare.
 //
 // Returns:
 //     true if the value of sid is equal to the value of the current System.Security.Principal.SecurityIdentifier
 //     object.
 extern public bool Equals(SecurityIdentifier sid);
Ejemplo n.º 45
0
 //
 // Summary:
 //     Returns a value that indicates whether the security identifier (SID) represented
 //     by this System.Security.Principal.SecurityIdentifier object is from the same
 //     domain as the specified SID.
 //
 // Parameters:
 //   sid:
 //     The SID to compare with this System.Security.Principal.SecurityIdentifier
 //     object.
 //
 // Returns:
 //     true if the SID represented by this System.Security.Principal.SecurityIdentifier
 //     object is in the same domain as the sid SID; otherwise, false.
 extern public bool IsEqualDomainSid(SecurityIdentifier sid);
Ejemplo n.º 46
0
 public virtual bool IsInRole(SecurityIdentifier sid)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 47
0
 //
 // 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);
 }
Ejemplo n.º 48
0
        private Paragraph PropParagraph(string name, System.Collections.ICollection props)
        {
            Paragraph p = new Paragraph();
            bool      appendSeparator = false;

            if (props != null)
            {
                foreach (dynamic value in props.Cast <object>().OrderBy(x => x.ToString()))
                {
                    if (appendSeparator)
                    {
                        p.Inlines.Add("\r\n");
                    }
                    else
                    {
                        appendSeparator = true;
                    }
                    string valueString = ((Object)value).ToString();
                    if (name == "userAccountControl:")
                    {
                        p.Inlines.Add(new Run(GetUserAccountControl(value)));
                    }
                    else if (valueString == "System.__ComObject")
                    {
                        try
                        {
                            // Try an ADSI Large Integer
                            Object o    = value;
                            Object low  = o.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, o, null);
                            Object high = o.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, o, null);

                            //long dateValue = (value.HighPart * &H100000000) + value.LowPart;
                            long     dateValue = ((long)((int)high) << 32) + (long)((int)low);
                            DateTime dt        = DateTime.FromFileTime(dateValue);
                            if (dt.ToString("dd-MMM-yyyy HH:mm") != "01-Jan-1601 11:00")
                            {
                                if (dt.Year == 1601)
                                {
                                    p.Inlines.Add(dt.ToString("HH:mm"));
                                }
                                else
                                {
                                    p.Inlines.Add(dt.ToString("dd-MMM-yyyy HH:mm"));
                                }
                            }
                        }
                        catch
                        {
                            p.Inlines.Add(valueString);
                        }
                    }
                    else if (valueString == "System.Byte[]")
                    {
                        byte[] bytes = value as byte[];
                        if (bytes.Length == 16)
                        {
                            Guid guid = new Guid(bytes);
                            p.Inlines.Add(guid.ToString("B"));
                        }
                        else if (bytes.Length == 28)
                        {
                            try
                            {
                                System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(bytes, 0);
                                p.Inlines.Add(sid.ToString());
                            }
                            catch
                            {
                                p.Inlines.Add(valueString);
                            }
                        }
                        else
                        {
                            System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
                            try
                            {
                                BitmapImage photoBitmap = new BitmapImage();
                                photoBitmap.BeginInit();
                                photoBitmap.StreamSource = ms;
                                photoBitmap.EndInit();
                                Image img = new Image();
                                img.Source  = photoBitmap;
                                img.Stretch = Stretch.None;
                                p.Inlines.Add(img);
                            }
                            catch
                            {
                                p.Inlines.Add(valueString);
                            }
                        }
                    }
                    else
                    {
                        if (valueString.StartsWith("CN=") || valueString.ToLower().StartsWith("http://"))
                        {
                            //string display = Regex.Match(valueString + ",", "CN=(.*?),").Groups[1].Captures[0].Value;
                            //Hyperlink h = new Hyperlink(new Run(display));
                            Hyperlink h = new Hyperlink(new Run(valueString));
                            h.NavigateUri = new Uri(valueString, valueString.ToLower().StartsWith("http://") ? UriKind.Absolute : UriKind.Relative);
                            h.Click      += new RoutedEventHandler(HyperlinkClicked);
                            //p.TextIndent = -20;
                            //p.Margin = new Thickness(20, p.Margin.Top, p.Margin.Right, p.Margin.Bottom);
                            p.Inlines.Add(h);
                        }
                        else
                        {
                            p.Inlines.Add(new Run(valueString));
                        }
                    }
                }
            }

            return(p);
        }
 public virtual new bool IsInRole(SecurityIdentifier sid)
 {
     return(default(bool));
 }
Ejemplo n.º 50
0
        public static IEnumerable <GroupMember> Get_DomainGroupMember(Args_Get_DomainGroupMember args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainGroupMember();
            }

            var SearcherArguments = new Args_Get_DomainSearcher()
            {
                Properties      = new string[] { @"member", @"samaccountname", @"distinguishedname" },
                Domain          = args.Domain,
                LDAPFilter      = args.LDAPFilter,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var ADNameArguments = new Args_Convert_ADName
            {
                Domain     = args.Domain,
                Server     = args.Server,
                Credential = args.Credential
            };

            var GroupMembers  = new List <GroupMember>();
            var GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);

            if (GroupSearcher != null)
            {
                string        GroupFoundDomain = null;
                string        GroupFoundName   = null;
                string        GroupFoundDN     = null;
                List <string> Members          = null;
                if (args.RecurseUsingMatchingRule)
                {
                    var GroupArguments = new Args_Get_DomainGroup()
                    {
                        Properties      = SearcherArguments.Properties,
                        Domain          = SearcherArguments.Domain,
                        LDAPFilter      = SearcherArguments.LDAPFilter,
                        SearchBase      = SearcherArguments.SearchBase,
                        Server          = SearcherArguments.Server,
                        SearchScope     = SearcherArguments.SearchScope,
                        ResultPageSize  = SearcherArguments.ResultPageSize,
                        ServerTimeLimit = SearcherArguments.ServerTimeLimit,
                        Tombstone       = SearcherArguments.Tombstone,
                        Credential      = SearcherArguments.Credential,
                        Identity        = args.Identity,
                        Raw             = true
                    };
                    var Groups = GetDomainGroup.Get_DomainGroup(GroupArguments);

                    if (Groups == null)
                    {
                        Logger.Write_Warning($@"[Get-DomainGroupMember] Error searching for group with identity: {args.Identity}");
                    }
                    else
                    {
                        var Group = Groups.First() as SearchResult;
                        GroupFoundName = Group.Properties[@"samaccountname"][0] as string;
                        GroupFoundDN   = Group.Properties[@"distinguishedname"][0] as string;
                        if (args.Domain.IsNotNullOrEmpty())
                        {
                            GroupFoundDomain = args.Domain;
                        }
                        else
                        {
                            // if a domain isn't passed, try to extract it from the found group distinguished name
                            if (GroupFoundDN.IsNotNullOrEmpty())
                            {
                                GroupFoundDomain = GroupFoundDN.Substring(GroupFoundDN.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                            }
                        }
                        Logger.Write_Verbose($@"[Get-DomainGroupMember] Using LDAP matching rule to recurse on '{GroupFoundDN}', only user accounts will be returned.");
                        GroupSearcher.Filter = $@"(&(samAccountType=805306368)(memberof:1.2.840.113556.1.4.1941:={GroupFoundDN}))";
                        GroupSearcher.PropertiesToLoad.AddRange(new string[] { @"distinguishedName" });
                        var Results = GroupSearcher.FindAll();
                        if (Results != null)
                        {
                            Members = new List <string>();
                            foreach (SearchResult result in Results)
                            {
                                Members.Add(result.Properties[@"distinguishedname"][0] as string);
                            }
                        }
                    }
                }
                else
                {
                    var IdentityFilter = @"";
                    var Filter         = @"";
                    if (args.Identity != null)
                    {
                        foreach (var item in args.Identity)
                        {
                            var IdentityInstance = item.Replace(@"(", @"\28").Replace(@")", @"\29");
                            if (new Regex(@"^S-1-").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(objectsid={IdentityInstance})";
                            }
                            else if (new Regex(@"^CN=").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                                if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                                {
                                    // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                    //   and rebuild the domain searcher
                                    var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"".Replace(@",", @"."));
                                    Logger.Write_Verbose($@"[Get-DomainGroupMember] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                    SearcherArguments.Domain = IdentityDomain;
                                    GroupSearcher            = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                    if (GroupSearcher == null)
                                    {
                                        Logger.Write_Warning($@"[Get-DomainGroupMember] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                    }
                                }
                            }
                            else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success)
                            {
                                var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                                IdentityFilter += $@"(objectguid={GuidByteString})";
                            }
                            else if (IdentityInstance.Contains(@"\"))
                            {
                                var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName
                                {
                                    OutputType = ADSNameType.Canonical,
                                    Identity   = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") }
                                });
                                if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any())
                                {
                                    var GroupDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/'));
                                    var GroupName   = IdentityInstance.Split(new char[] { '\\' })[1];
                                    IdentityFilter          += $@"(samAccountName={GroupName})";
                                    SearcherArguments.Domain = GroupDomain;
                                    Logger.Write_Verbose($@"[Get-DomainGroupMember] Extracted domain '{GroupDomain}' from '{IdentityInstance}'");
                                    GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                }
                            }
                            else
                            {
                                IdentityFilter += $@"(samAccountName={IdentityInstance})";
                            }
                        }
                    }

                    if (IdentityFilter != null && IdentityFilter.Trim() != @"")
                    {
                        Filter += $@"(|{IdentityFilter})";
                    }

                    if (args.LDAPFilter.IsNotNullOrEmpty())
                    {
                        Logger.Write_Verbose($@"[Get-DomainGroupMember] Using additional LDAP filter: {args.LDAPFilter}");
                        Filter += $@"{args.LDAPFilter}";
                    }

                    GroupSearcher.Filter = $@"(&(objectCategory=group){Filter})";
                    Logger.Write_Verbose($@"[Get-DomainGroupMember] Get-DomainGroupMember filter string: {GroupSearcher.Filter}");
                    SearchResult Result = null;
                    try
                    {
                        Result = GroupSearcher.FindOne();
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Warning($@"[Get-DomainGroupMember] Error searching for group with identity '{args.Identity}': {e}");
                        Members = new List <string>();
                    }

                    GroupFoundName = @"";
                    GroupFoundDN   = @"";

                    if (Result != null)
                    {
                        var tmpProperty = Result.Properties[@"member"];
                        var tmpValues   = new string[tmpProperty.Count];
                        tmpProperty.CopyTo(tmpValues, 0);
                        Members = tmpValues.ToList();
                        string RangedProperty = "";

                        if (Members.Count == 0)
                        {
                            // ranged searching, thanks @meatballs__ !
                            var Finished = false;
                            var Bottom   = 0;
                            var Top      = 0;

                            while (!Finished)
                            {
                                Top = Bottom + 1499;
                                var MemberRange = $@"member;range={Bottom}-{Top}";
                                Bottom += 1500;
                                GroupSearcher.PropertiesToLoad.Clear();
                                GroupSearcher.PropertiesToLoad.Add($@"{MemberRange}");
                                GroupSearcher.PropertiesToLoad.Add(@"samaccountname");
                                GroupSearcher.PropertiesToLoad.Add(@"distinguishedname");

                                try
                                {
                                    Result         = GroupSearcher.FindOne();
                                    RangedProperty = Result.Properties.PropertyNames.GetFirstMatch(@"member;range=*");
                                    tmpProperty    = Result.Properties[RangedProperty];
                                    tmpValues      = new string[tmpProperty.Count];
                                    tmpProperty.CopyTo(tmpValues, 0);
                                    Members.AddRange(tmpValues.ToList());
                                    GroupFoundName = Result.Properties[@"samaccountname"][0] as string;
                                    GroupFoundDN   = Result.Properties[@"distinguishedname"][0] as string;

                                    if (Members.Count == 0)
                                    {
                                        Finished = true;
                                    }
                                }
                                catch
                                {
                                    Finished = true;
                                }
                            }
                        }
                        else
                        {
                            GroupFoundName = Result.Properties[@"samaccountname"][0] as string;
                            GroupFoundDN   = Result.Properties[@"distinguishedname"][0] as string;
                            tmpProperty    = Result.Properties[RangedProperty];
                            tmpValues      = new string[tmpProperty.Count];
                            tmpProperty.CopyTo(tmpValues, 0);
                            Members.AddRange(tmpValues.ToList());
                        }

                        if (args.Domain.IsNotNullOrEmpty())
                        {
                            GroupFoundDomain = args.Domain;
                        }
                        else
                        {
                            // if a domain isn't passed, try to extract it from the found group distinguished name
                            if (GroupFoundDN.IsNotNullOrEmpty())
                            {
                                GroupFoundDomain = GroupFoundDN.Substring(GroupFoundDN.IndexOf(@"DC=")).Replace(@"DC=", @"".Replace(@",", @"."));
                            }
                        }
                    }

                    var    UseMatchingRule = false;
                    string MemberDomain    = null;
                    foreach (var Member in Members)
                    {
                        ResultPropertyCollection Properties = null;
                        if (args.Recurse && UseMatchingRule)
                        {
                            //$Properties = $_.Properties
                        }
                        else
                        {
                            var ObjectSearcherArguments = new Args_Get_DomainObject
                            {
                                ADSPath          = SearcherArguments.ADSPath,
                                Credential       = SearcherArguments.Credential,
                                Domain           = SearcherArguments.Domain,
                                DomainController = SearcherArguments.DomainController,
                                Filter           = SearcherArguments.Filter,
                                LDAPFilter       = SearcherArguments.LDAPFilter,
                                Properties       = SearcherArguments.Properties,
                                ResultPageSize   = SearcherArguments.ResultPageSize,
                                SearchBase       = SearcherArguments.SearchBase,
                                SearchScope      = SearcherArguments.SearchScope,
                                SecurityMasks    = SearcherArguments.SecurityMasks,
                                Server           = SearcherArguments.Server,
                                ServerTimeLimit  = SearcherArguments.ServerTimeLimit,
                                Tombstone        = SearcherArguments.Tombstone
                            };
                            ObjectSearcherArguments.Identity   = new string[] { Member };
                            ObjectSearcherArguments.Raw        = true;
                            ObjectSearcherArguments.Properties = new string[] { @"distinguishedname", @"cn", @"samaccountname", @"objectsid", @"objectclass" };
                            var Object = GetDomainObject.Get_DomainObject(ObjectSearcherArguments)?.FirstOrDefault() as SearchResult;
                            Properties = Object.Properties;
                        }

                        if (Properties != null)
                        {
                            var GroupMember = new GroupMember
                            {
                                GroupDomain            = GroupFoundDomain,
                                GroupName              = GroupFoundName,
                                GroupDistinguishedName = GroupFoundDN
                            };

                            string MemberSID = null;
                            if (Properties["objectsid"] != null)
                            {
                                MemberSID = new System.Security.Principal.SecurityIdentifier(Properties["objectsid"][0] as byte[], 0).Value;
                            }
                            else
                            {
                                MemberSID = null;
                            }

                            string MemberDN = null;
                            try
                            {
                                MemberDN = Properties["distinguishedname"][0].ToString();
                                if (MemberDN.IsRegexMatch(@"ForeignSecurityPrincipals|S-1-5-21"))
                                {
                                    try
                                    {
                                        if (MemberSID.IsNullOrEmpty())
                                        {
                                            MemberSID = Properties["cn"][0].ToString();
                                        }
                                        ADNameArguments.Identity   = new string[] { MemberSID };
                                        ADNameArguments.OutputType = ADSNameType.DomainSimple;
                                        var MemberSimpleName = ConvertADName.Convert_ADName(ADNameArguments);

                                        if (MemberSimpleName != null && MemberSimpleName.Any())
                                        {
                                            MemberDomain = MemberSimpleName.First().Split('@')[1];
                                        }
                                        else
                                        {
                                            Logger.Write_Warning($@"[Get-DomainGroupMember] Error converting {MemberDN}");
                                            MemberDomain = null;
                                        }
                                    }
                                    catch
                                    {
                                        Logger.Write_Warning($@"[Get-DomainGroupMember] Error converting {MemberDN}");
                                        MemberDomain = null;
                                    }
                                }
                                else
                                {
                                    // extract the FQDN from the Distinguished Name
                                    MemberDomain = MemberDN.Substring(MemberDN.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                                }
                            }
                            catch
                            {
                                MemberDN     = null;
                                MemberDomain = null;
                            }
                            string MemberName = null;
                            if (Properties["samaccountname"] != null)
                            {
                                // forest users have the samAccountName set
                                MemberName = Properties["samaccountname"][0].ToString();
                            }
                            else
                            {
                                // external trust users have a SID, so convert it
                                try
                                {
                                    MemberName = ConvertFromSID.ConvertFrom_SID(new Args_ConvertFrom_SID
                                    {
                                        ObjectSID  = new string[] { Properties["cn"][0].ToString() },
                                        Domain     = ADNameArguments.Domain,
                                        Server     = ADNameArguments.Server,
                                        Credential = ADNameArguments.Credential
                                    }).First();
                                }
                                catch
                                {
                                    // if there's a problem contacting the domain to resolve the SID
                                    MemberName = Properties["cn"][0].ToString();
                                }
                            }

                            string MemberObjectClass = null;
                            if (Properties["objectclass"].RegexContains(@"computer"))
                            {
                                MemberObjectClass = @"computer";
                            }
                            else if (Properties["objectclass"].RegexContains(@"group"))
                            {
                                MemberObjectClass = @"group";
                            }
                            else if (Properties["objectclass"].RegexContains(@"user"))
                            {
                                MemberObjectClass = @"user";
                            }
                            else
                            {
                                MemberObjectClass = null;
                            }
                            GroupMember.MemberDomain            = MemberDomain;
                            GroupMember.MemberName              = MemberName;
                            GroupMember.MemberDistinguishedName = MemberDN;
                            GroupMember.MemberObjectClass       = MemberObjectClass;
                            GroupMember.MemberSID = MemberSID;
                            GroupMembers.Add(GroupMember);

                            // if we're doing manual recursion
                            if (args.Recurse && MemberDN.IsNotNullOrEmpty() && MemberObjectClass.IsRegexMatch(@"group"))
                            {
                                Logger.Write_Verbose($@"[Get-DomainGroupMember] Manually recursing on group: {MemberDN}");
                                var GroupArguments = new Args_Get_DomainGroupMember()
                                {
                                    Domain          = SearcherArguments.Domain,
                                    LDAPFilter      = SearcherArguments.LDAPFilter,
                                    SearchBase      = SearcherArguments.SearchBase,
                                    Server          = SearcherArguments.Server,
                                    SearchScope     = SearcherArguments.SearchScope,
                                    ResultPageSize  = SearcherArguments.ResultPageSize,
                                    ServerTimeLimit = SearcherArguments.ServerTimeLimit,
                                    Tombstone       = SearcherArguments.Tombstone,
                                    Credential      = SearcherArguments.Credential,
                                    Identity        = new string[] { MemberDN }
                                };
                                GroupMembers.AddRange(Get_DomainGroupMember(GroupArguments));
                            }
                        }
                    }
                }
                GroupSearcher.Dispose();
            }
            return(GroupMembers);
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Called by a connection when it has received an intact and complete message in wire-format.
        /// Parses the supplied byte-array to generate a typed message for processing.
        /// On return from this routine the connection is free to overwrite the buffer contents.
        /// /// </summary>
        /// <param name="conn">Connection (think TCP to specific network agent) on which message arrived.</param>
        /// <param name="buff">Buffer encoding the message.</param>
        /// <param name="offset">Offset to start of message in the supplied buffer.</param>
        /// <param name="length">Length of message encoding in supplied buffer</param>
        public void ReceiveMessage(Connection conn, MessageTypes messageType, byte[] buff, int offset, int length)
        {
            switch (messageType)
            {
            case MessageTypes.MessageTypeRegister:
            {
                MessageRegister msgRegister = MessageRegister.CreateFromNetBytes(buff, offset);
                TenantId = msgRegister.TenantId;
                client.CallbackMessageRegister(conn, msgRegister.TenantId, msgRegister.AlertVec);
                MessageAck ack = new MessageAck(msgRegister.SeqNo,
                                                MessageTypes.MessageTypeRegisterAck,
                                                (uint)OktoResultCodes.OKTO_RESULT_SUCCESS);
                SendSynchronous(conn, ack.Serialize);
                conn.BeginReceive();
                break;
            }

            case MessageTypes.MessageTypeIoFlowCreate:
            {
                MessageIoFlowCreate msgFlowc = MessageIoFlowCreate.CreateFromNetBytes(buff, offset);
                lock (LockLocal)
                {
                    foreach (IoFlowMessageParams flowc in msgFlowc.ListParams)
                    {
                        Console.WriteLine("Agent MessageIoFlowCreate({0},{1})", flowc.FlowId, flowc.ParameterString);
                        if (DictFlowCreateParams.ContainsKey(flowc.FlowId))
                        {
                            throw new ArgumentOutOfRangeException(string.Format("Agent flowc dup FlowId {0}", flowc.FlowId));
                        }
                        DictFlowCreateParams.Add(flowc.FlowId, flowc);
                    }
                }
                MessageAck ack = new MessageAck(msgFlowc.SeqNo,
                                                MessageTypes.MessageTypeIoFlowCreateAck,
                                                (uint)OktoResultCodes.OKTO_RESULT_SUCCESS);
                SendSynchronous(conn, ack.Serialize);
                conn.BeginReceive();
                break;
            }

            case MessageTypes.MessageTypeRapFsCreate:
            {
                MessageRapFsCreate msgRapc = MessageRapFsCreate.CreateFromNetBytes(buff, offset);

                lock (LockLocal)
                {
                    foreach (MsgRapArg rapc in msgRapc.ListMsgRapArg)
                    {
                        Console.WriteLine("Agent MessageRapFsCreate({0},{1},{2})", rapc.FlowId, rapc.stringSid, rapc.ShareOrVolume);
                        if (!DictFlowCreateParams.ContainsKey(rapc.FlowId))
                        {
                            throw new ArgumentOutOfRangeException(string.Format("Agent rapc invalid FlowId {0}", rapc.FlowId));
                        }
                        if (DictRapCreateParams.ContainsKey(rapc.FlowId))
                        {
                            throw new ArgumentOutOfRangeException(string.Format("Agent rapc dup FlowId {0}", rapc.FlowId));
                        }
                        if (!DictFlowCreateParams.ContainsKey(rapc.FlowId))
                        {
                            throw new ArgumentOutOfRangeException(string.Format("Agent rapc unmatched FlowId {0}", rapc.FlowId));
                        }
                        DictRapCreateParams.Add(rapc.FlowId, rapc);
                    }
                }
                //
                // Params look reasonable and FlowCreate and RapCreate match up.
                // Now we can invite the client to create its IoFlows.
                //
                OktoResultCodes result = client.CallbackIoFlowCreate(DictFlowCreateParams, DictRapCreateParams);

                MessageAck ack = new MessageAck(msgRapc.SeqNo,
                                                MessageTypes.MessageTypeRapFsCreateAck,
                                                (uint)result);
                SendSynchronous(conn, ack.Serialize);
                conn.BeginReceive();
                break;
            }

            case MessageTypes.MessageTypeStatsZero:
            {
                MessageStatsZero msgZero = MessageStatsZero.CreateFromNetBytes(buff, offset);
                OktoResultCodes  result  = client.CallbackMessageStatsZero();
                MessageAck       ack     = new MessageAck(msgZero.SeqNo,
                                                          MessageTypes.MessageTypeStatsZeroAck,
                                                          (uint)result);
                SendSynchronous(conn, ack.Serialize);
                conn.BeginReceive();
                break;
            }

            case MessageTypes.MessageTypeIoFlowUpdate:
            {
                MessageIoFlowUpdate msgFlowc = MessageIoFlowUpdate.CreateFromNetBytes(buff, offset);
                lock (LockLocal)
                {
                    foreach (IoFlowMessageParams flowu in msgFlowc.ListParams)
                    {
                        if (!DictFlowCreateParams.ContainsKey(flowu.FlowId))
                        {
                            throw new ArgumentOutOfRangeException(string.Format("Agent flowu invalid FlowId {0}", flowu.FlowId));
                        }
                    }
                }
                OktoResultCodes result = client.CallbackMessageIoFlowUpdate(msgFlowc.ListParams);
                MessageAck      ack    = new MessageAck(msgFlowc.SeqNo,
                                                        MessageTypes.MessageTypeIoFlowUpdateAck,
                                                        (uint)result);
                SendSynchronous(conn, ack.Serialize);
                conn.BeginReceive();
                break;
            }

            case MessageTypes.MessageTypeTenantDelete:
            {
                MessageTenantDelete msgTend = MessageTenantDelete.CreateFromNetBytes(buff, offset);
                OktoResultCodes     result  = client.CallbackMessageTenantDelete();
                MessageAck          ack     = new MessageAck(msgTend.SeqNo,
                                                             MessageTypes.MessageTypeTenantDeleteAck,
                                                             (uint)result);
                SendSynchronous(conn, ack.Serialize);
                conn.BeginReceive();
                break;
            }

            case MessageTypes.MessageTypeIoFlowStatsQuery:
            {
                MessageIoFlowStatsQuery    msgStatsQ = MessageIoFlowStatsQuery.CreateFromNetBytes(buff, offset);
                List <IoFlowMessageParams> listStats = client.CallbackMessageIoFlowStatsQuery();
                lock (LockLocal)
                {
                    foreach (IoFlowMessageParams stats in listStats)
                    {
                        if (!DictFlowCreateParams.ContainsKey(stats.FlowId))
                        {
                            throw new ArgumentOutOfRangeException(string.Format("Stats reply invalid FlowId {0}", stats.FlowId));
                        }
                    }
                }
                MessageIoFlowStatsReply msgStatsReply = new MessageIoFlowStatsReply(msgStatsQ.SeqNo, listStats, TenantId);
                SendSynchronous(conn, msgStatsReply.Serialize);
                conn.BeginReceive();
                break;
            }

            case MessageTypes.MessageTypeNameToStringSidBatchQuery:
            {
                MessageNameToStringSidBatchQuery msgSidBatchQuery =
                    MessageNameToStringSidBatchQuery.CreateFromNetBytes(buff, offset);
                Dictionary <string, string> DictVmNameToSid      = new Dictionary <string, string>();
                System.Security.Principal.SecurityIdentifier sid = null;
                foreach (string vmName in msgSidBatchQuery.ListVmNames)
                {
                    //XXXET: following two lines are for account names of type europe\
                    sid = VmSID.GetVMnameSid(vmName);
                    if (sid == null)
                    {
                        try
                        {
                            NTAccount ntaccount = new NTAccount(vmName);
                            sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier));
                        }
                        catch (Exception e)
                        {
                            Debug.Assert(0 == 1, e.Message);
                        }
                    }

                    Console.WriteLine("MessageTypeNameToStringSidBatchQuery: {0} sid {1}", vmName, sid.ToString());
                    DictVmNameToSid.Add(vmName, sid.ToString());
                }
                MessageVmNameToStringSidBatchReply msgSidReply =
                    new MessageVmNameToStringSidBatchReply(msgSidBatchQuery.SeqNo,
                                                           (uint)OktoResultCodes.OKTO_RESULT_SUCCESS,
                                                           DictVmNameToSid);
                SendSynchronous(conn, msgSidReply.Serialize);
                conn.BeginReceive();
                break;
            }


            default:
            {
                string msg = string.Format("ReceiveMessage: unexpected message type {0}", messageType);
                throw new ApplicationException(msg);
            }
            } // switch
        }
Ejemplo n.º 52
0
        public static IEnumerable <object> Get_DomainGroup(Args_Get_DomainGroup args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainGroup();
            }

            var SearcherArguments = new Args_Get_DomainSearcher
            {
                Domain          = args.Domain,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                SecurityMasks   = args.SecurityMasks,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var ObjectArguments = new Args_Get_DomainObject
            {
                Domain          = args.Domain,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                SecurityMasks   = args.SecurityMasks,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
            var Groups        = new List <object>();

            if (GroupSearcher != null)
            {
                if (args.MemberIdentity != null)
                {
                    string[] OldProperties = null;
                    if (args.Properties != null)
                    {
                        OldProperties = SearcherArguments.Properties;
                    }

                    ObjectArguments.Identity = args.MemberIdentity;
                    ObjectArguments.Raw      = true;

                    var Objects = GetDomainObject.Get_DomainObject(ObjectArguments);
                    if (Objects != null)
                    {
                    }
                    foreach (SearchResult obj in Objects)
                    {
                        // convert the user/group to a directory entry
                        var ObjectDirectoryEntry = obj.GetDirectoryEntry();

                        // cause the cache to calculate the token groups for the user/group
                        ObjectDirectoryEntry.RefreshCache(new string[] { @"tokenGroups" });
                        foreach (byte[] tokenGroup in ObjectDirectoryEntry.Properties[@"tokenGroups"])
                        {
                            // convert the token group sid
                            var GroupSid = new System.Security.Principal.SecurityIdentifier(tokenGroup, 0).Value;

                            // ignore the built in groups
                            if (new Regex(@"^S-1-5-32-.*").Match(GroupSid).Success == false)
                            {
                                ObjectArguments.Identity = new string[] { GroupSid };
                                ObjectArguments.Raw      = false;
                                if (OldProperties != null)
                                {
                                    ObjectArguments.Properties = OldProperties;
                                }
                                var Group = GetDomainObject.Get_DomainObject(ObjectArguments);
                                if (Group != null)
                                {
                                    Groups.AddRange(Group);
                                }
                            }
                        }
                    }
                }
                else
                {
                    var IdentityFilter = "";
                    var Filter         = "";
                    if (args.Identity != null)
                    {
                        foreach (var samName in args.Identity)
                        {
                            var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29");
                            if (new Regex(@"^S-1-").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(objectsid={IdentityInstance})";
                            }
                            else if (new Regex(@"^CN=").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                                if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                                {
                                    // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                    // and rebuild the domain searcher
                                    var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                                    Logger.Write_Verbose($@"[Get-DomainGroup] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                    SearcherArguments.Domain = IdentityDomain;
                                    GroupSearcher            = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                    if (GroupSearcher == null)
                                    {
                                        Logger.Write_Warning($@"[Get-DomainGroup] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                    }
                                }
                            }
                            else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success)
                            {
                                var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                                IdentityFilter += $@"(objectguid={GuidByteString})";
                            }
                            else if (IdentityInstance.Contains(@"\"))
                            {
                                var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName
                                {
                                    OutputType = ADSNameType.Canonical,
                                    Identity   = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") }
                                });
                                if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any())
                                {
                                    var GroupDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/'));
                                    var GroupName   = IdentityInstance.Split(new char[] { '\\' })[1];
                                    IdentityFilter          += $@"(samAccountName={GroupName})";
                                    SearcherArguments.Domain = GroupDomain;
                                    Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{GroupDomain}' from '{IdentityInstance}'");
                                    GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                }
                            }
                            else
                            {
                                IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance}))";
                            }
                        }
                    }

                    if (IdentityFilter != null && IdentityFilter.Trim() != "")
                    {
                        Filter += $@"(|{IdentityFilter})";
                    }

                    if (args.AdminCount)
                    {
                        Logger.Write_Verbose(@"[Get-DomainGroup] Searching for adminCount=1");
                        Filter += "(admincount=1)";
                    }
                    if (args.GroupScope != null)
                    {
                        switch (args.GroupScope.Value)
                        {
                        case GroupScope.DomainLocal:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=4)";
                            break;

                        case GroupScope.NotDomainLocal:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=4))";
                            break;

                        case GroupScope.Global:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=2)";
                            break;

                        case GroupScope.NotGlobal:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=2))";
                            break;

                        case GroupScope.Universal:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=8)";
                            break;

                        case GroupScope.NotUniversal:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=8))";
                            break;

                        default:
                            break;
                        }
                        Logger.Write_Verbose($@"[Get-DomainGroup] Searching for group scope '{args.GroupScope.Value.ToString()}'");
                    }
                    if (args.GroupProperty != null)
                    {
                        switch (args.GroupProperty.Value)
                        {
                        case GroupProperty.Security:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=2147483648)";
                            break;

                        case GroupProperty.Distribution:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=2147483648))";
                            break;

                        case GroupProperty.CreatedBySystem:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=1)";
                            break;

                        case GroupProperty.NotCreatedBySystem:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=1))";
                            break;

                        default:
                            break;
                        }
                        Logger.Write_Verbose($@"[Get-DomainGroup] Searching for group property '{args.GroupProperty.Value.ToString()}'");
                    }
                    if (args.LDAPFilter.IsNotNullOrEmpty())
                    {
                        Logger.Write_Verbose($@"[Get-DomainGroup] Using additional LDAP filter: {args.LDAPFilter}");
                        Filter += $@"{args.LDAPFilter}";
                    }

                    GroupSearcher.Filter = $@"(&(objectCategory=group){Filter})";
                    Logger.Write_Verbose($@"[Get-DomainGroup] filter string: {GroupSearcher.Filter}");

                    if (args.FindOne)
                    {
                        var result = GroupSearcher.FindOne();
                        if (args.Raw)
                        {
                            // return raw result objects
                            Groups.Add(result);
                        }
                        else
                        {
                            Groups.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                        }
                    }
                    else
                    {
                        var Results = GroupSearcher.FindAll();
                        foreach (SearchResult result in Results)
                        {
                            if (args.Raw)
                            {
                                // return raw result objects
                                Groups.Add(result);
                            }
                            else
                            {
                                Groups.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                            }
                        }
                        if (Results != null)
                        {
                            try { Results.Dispose(); }
                            catch (Exception e)
                            {
                                Logger.Write_Verbose($@"[Get-DomainGroup] Error disposing of the Results object: {e}");
                            }
                        }
                    }
                    GroupSearcher.Dispose();
                }
            }
            return(Groups);
        }
Ejemplo n.º 53
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }
            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            SafeLsaPolicyHandle         safeLsaPolicyHandle = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle       = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle2      = SafeLsaMemoryHandle.InvalidHandle;
            IdentityReferenceCollection result;

            try
            {
                Win32Native.UNICODE_STRING[] array = new Win32Native.UNICODE_STRING[sourceAccounts.Count];
                int num = 0;
                foreach (IdentityReference identityReference in sourceAccounts)
                {
                    NTAccount ntaccount = identityReference as NTAccount;
                    if (ntaccount == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }
                    array[num].Buffer = ntaccount.ToString();
                    if (array[num].Buffer.Length * 2 + 2 > 65535)
                    {
                        throw new SystemException();
                    }
                    array[num].Length        = (ushort)(array[num].Buffer.Length * 2);
                    array[num].MaximumLength = array[num].Length + 2;
                    num++;
                }
                safeLsaPolicyHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed          = false;
                uint num2;
                if (Win32.LsaLookupNames2Supported)
                {
                    num2 = Win32Native.LsaLookupNames2(safeLsaPolicyHandle, 0, sourceAccounts.Count, array, ref invalidHandle, ref invalidHandle2);
                }
                else
                {
                    num2 = Win32Native.LsaLookupNames(safeLsaPolicyHandle, sourceAccounts.Count, array, ref invalidHandle, ref invalidHandle2);
                }
                if (num2 == 3221225495U || num2 == 3221225626U)
                {
                    throw new OutOfMemoryException();
                }
                if (num2 == 3221225506U)
                {
                    throw new UnauthorizedAccessException();
                }
                if (num2 == 3221225587U || num2 == 263U)
                {
                    someFailed = true;
                }
                else if (num2 != 0U)
                {
                    int errorCode = Win32Native.LsaNtStatusToWinError((int)num2);
                    throw new SystemException(Win32Native.GetMessage(errorCode));
                }
                IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(sourceAccounts.Count);
                if (num2 == 0U || num2 == 263U)
                {
                    if (Win32.LsaLookupNames2Supported)
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        Win32.InitializeReferencedDomainsPointer(invalidHandle);
                        Win32Native.LSA_TRANSLATED_SID2[] array2 = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID2>(0UL, array2, 0, array2.Length);
                        int i = 0;
                        while (i < sourceAccounts.Count)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 lsa_TRANSLATED_SID = array2[i];
                            switch (lsa_TRANSLATED_SID.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                identityReferenceCollection.Add(new SecurityIdentifier(lsa_TRANSLATED_SID.Sid, true));
                                break;

                            case 3:
                            case 6:
                            case 7:
                            case 8:
                                goto IL_282;

                            default:
                                goto IL_282;
                            }
IL_294:
                            i++;
                            continue;
IL_282:
                            someFailed = true;
                            identityReferenceCollection.Add(sourceAccounts[i]);
                            goto IL_294;
                        }
                    }
                    else
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        Win32.InitializeReferencedDomainsPointer(invalidHandle);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST lsa_REFERENCED_DOMAIN_LIST = invalidHandle.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0UL);
                        SecurityIdentifier[] array3 = new SecurityIdentifier[lsa_REFERENCED_DOMAIN_LIST.Entries];
                        for (int j = 0; j < lsa_REFERENCED_DOMAIN_LIST.Entries; j++)
                        {
                            Win32Native.LSA_TRUST_INFORMATION lsa_TRUST_INFORMATION = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr((long)lsa_REFERENCED_DOMAIN_LIST.Domains + (long)(j * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                            array3[j] = new SecurityIdentifier(lsa_TRUST_INFORMATION.Sid, true);
                        }
                        Win32Native.LSA_TRANSLATED_SID[] array4 = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID>(0UL, array4, 0, array4.Length);
                        int k = 0;
                        while (k < sourceAccounts.Count)
                        {
                            Win32Native.LSA_TRANSLATED_SID lsa_TRANSLATED_SID2 = array4[k];
                            switch (lsa_TRANSLATED_SID2.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                identityReferenceCollection.Add(new SecurityIdentifier(array3[lsa_TRANSLATED_SID2.DomainIndex], lsa_TRANSLATED_SID2.Rid));
                                break;

                            case 3:
                            case 6:
                            case 7:
                            case 8:
                                goto IL_3C8;

                            default:
                                goto IL_3C8;
                            }
IL_3DA:
                            k++;
                            continue;
IL_3C8:
                            someFailed = true;
                            identityReferenceCollection.Add(sourceAccounts[k]);
                            goto IL_3DA;
                        }
                    }
                }
                else
                {
                    for (int l = 0; l < sourceAccounts.Count; l++)
                    {
                        identityReferenceCollection.Add(sourceAccounts[l]);
                    }
                }
                result = identityReferenceCollection;
            }
            finally
            {
                safeLsaPolicyHandle.Dispose();
                invalidHandle.Dispose();
                invalidHandle2.Dispose();
            }
            return(result);
        }
Ejemplo n.º 54
0
    public static string GetUserFromSID(string sid)
    {
        string account = new System.Security.Principal.SecurityIdentifier(sid).Translate(typeof(System.Security.Principal.NTAccount)).ToString();

        return(account);
    }
Ejemplo n.º 55
0
        [System.Security.SecurityCritical]  // auto-generated
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }

            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            Contract.EndContractBlock();

            SafeLsaPolicyHandle LsaHandle            = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle SidsPtr = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                //
                // Construct an array of unicode strings
                //

                Win32Native.UNICODE_STRING[] Names = new Win32Native.UNICODE_STRING[sourceAccounts.Count];

                int currentName = 0;
                foreach (IdentityReference id in sourceAccounts)
                {
                    NTAccount nta = id as NTAccount;

                    if (nta == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }

                    Names[currentName].Buffer = nta.ToString();

                    if (Names[currentName].Buffer.Length * 2 + 2 > ushort.MaxValue)
                    {
                        // this should never happen since we are already validating account name length in constructor and
                        // it is less than this limit
                        Contract.Assert(false, "NTAccount::TranslateToSids - source account name is too long.");
                        throw new SystemException();
                    }

                    Names[currentName].Length        = (ushort)(Names[currentName].Buffer.Length * 2);
                    Names[currentName].MaximumLength = (ushort)(Names[currentName].Length + 2);
                    currentName++;
                }

                //
                // Open LSA policy (for lookup requires it)
                //

                LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);

                //
                // Now perform the actual lookup
                //

                someFailed = false;
                uint ReturnCode;

                if (Win32.LsaLookupNames2Supported)
                {
                    ReturnCode = Win32Native.LsaLookupNames2(LsaHandle, 0, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr);
                }
                else
                {
                    ReturnCode = Win32Native.LsaLookupNames(LsaHandle, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr);
                }

                //
                // Make a decision regarding whether it makes sense to proceed
                // based on the return code and the value of the forceSuccess argument
                //

                if (ReturnCode == Win32Native.STATUS_NO_MEMORY ||
                    ReturnCode == Win32Native.STATUS_INSUFFICIENT_RESOURCES)
                {
                    throw new OutOfMemoryException();
                }
                else if (ReturnCode == Win32Native.STATUS_ACCESS_DENIED)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (ReturnCode == Win32Native.STATUS_NONE_MAPPED ||
                         ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED)
                {
                    someFailed = true;
                }
                else if (ReturnCode != 0)
                {
                    int win32ErrorCode = Win32Native.LsaNtStatusToWinError(unchecked ((int)ReturnCode));

                    if (win32ErrorCode != Win32Native.ERROR_TRUSTED_RELATIONSHIP_FAILURE)
                    {
                        Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32Native.LsaLookupNames(2) returned unrecognized error {0}", win32ErrorCode));
                    }

                    throw new SystemException(Win32Native.GetMessage(win32ErrorCode));
                }

                //
                // Interpret the results and generate SID objects
                //

                IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count);

                if (ReturnCode == 0 || ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED)
                {
                    if (Win32.LsaLookupNames2Supported)
                    {
                        SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
                        Win32Native.LSA_TRANSLATED_SID2[] translatedSids = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                        for (int i = 0; i < sourceAccounts.Count; i++)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 Lts = translatedSids[i];

                            //
                            // Only some names are recognized as NTAccount objects
                            //

                            switch ((SidNameUse)Lts.Use)
                            {
                            case SidNameUse.User:
                            case SidNameUse.Group:
                            case SidNameUse.Alias:
                            case SidNameUse.Computer:
                            case SidNameUse.WellKnownGroup:
                                Result.Add(new SecurityIdentifier(Lts.Sid, true));
                                break;

                            default:
                                someFailed = true;
                                Result.Add(sourceAccounts[i]);
                                break;
                            }
                        }
                    }
                    else
                    {
                        SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0);
                        SecurityIdentifier[] ReferencedDomains     = new SecurityIdentifier[rdl.Entries];

                        for (int i = 0; i < rdl.Entries; i++)
                        {
                            Win32Native.LSA_TRUST_INFORMATION ti = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr(( long )rdl.Domains + i * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION))), typeof(Win32Native.LSA_TRUST_INFORMATION));

                            ReferencedDomains[i] = new SecurityIdentifier(ti.Sid, true);
                        }

                        Win32Native.LSA_TRANSLATED_SID[] translatedSids = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                        for (int i = 0; i < sourceAccounts.Count; i++)
                        {
                            Win32Native.LSA_TRANSLATED_SID Lts = translatedSids[i];

                            switch ((SidNameUse)Lts.Use)
                            {
                            case SidNameUse.User:
                            case SidNameUse.Group:
                            case SidNameUse.Alias:
                            case SidNameUse.Computer:
                            case SidNameUse.WellKnownGroup:
                                Result.Add(new SecurityIdentifier(ReferencedDomains[Lts.DomainIndex], Lts.Rid));
                                break;

                            default:
                                someFailed = true;
                                Result.Add(sourceAccounts[i]);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sourceAccounts.Count; i++)
                    {
                        Result.Add(sourceAccounts[i]);
                    }
                }

                return(Result);
            }
            finally
            {
                LsaHandle.Dispose();
                ReferencedDomainsPtr.Dispose();
                SidsPtr.Dispose();
            }
        }