Пример #1
0
        public static List <string> Get_LocalUser(Args_Get_DomainUser args = null)
        {
            List <string> users = new List <string>();
            int           EntriesRead;
            int           TotalEntries;
            int           Resume;
            IntPtr        bufPtr;

            NetUserEnum(null, 0, 2, out bufPtr, -1, out EntriesRead, out TotalEntries, out Resume);

            if (EntriesRead > 0)
            {
                Logger.Write_Output("[Get-LocalUser] Found " + EntriesRead + " user.");
                USER_INFO_0[] Users = new USER_INFO_0[EntriesRead];
                IntPtr        iter  = bufPtr;
                for (int i = 0; i < EntriesRead; i++)
                {
                    Users[i] = (USER_INFO_0)Marshal.PtrToStructure(iter, typeof(USER_INFO_0));
                    iter     = (IntPtr)((int)iter + Marshal.SizeOf(typeof(USER_INFO_0)));
                    users.Add(Users[i].UserName);
                }
                NetApiBufferFree(bufPtr);
            }
            else
            {
                Logger.Write_Warning("[Get-LocalUser] Error, Cann't found any user.");
            }
            return(users);
        }
Пример #2
0
        public static IEnumerable <ForeignUser> Get_DomainForeignUser(Args_Get_DomainForeignUser args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainForeignUser();
            }

            var SearcherArguments = new Args_Get_DomainUser
            {
                LDAPFilter      = @"(memberof=*)",
                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 ForeignUsers = new List <ForeignUser>();
            var Results      = GetDomainUser.Get_DomainUser(SearcherArguments);

            foreach (LDAPProperty result in Results)
            {
                foreach (var Membership in result.memberof)
                {
                    var Index = Membership.IndexOf(@"DC=");
                    if (Index != 0)
                    {
                        var GroupDomain           = Membership.Substring(Index).Replace(@"DC=", @"").Replace(@",", @".");
                        var UserDistinguishedName = result.distinguishedname;
                        var UserIndex             = UserDistinguishedName.IndexOf(@"DC=");
                        var UserDomain            = result.distinguishedname.Substring(UserIndex).Replace(@"DC=", @"").Replace(@",", @".");

                        if (GroupDomain != UserDomain)
                        {
                            // if the group domain doesn't match the user domain, display it
                            var GroupName   = Membership.Split(',')[0].Split('=')[1];
                            var ForeignUser = new ForeignUser
                            {
                                UserDomain             = UserDomain,
                                UserName               = result.samaccountname,
                                UserDistinguishedName  = result.distinguishedname,
                                GroupDomain            = GroupDomain,
                                GroupName              = GroupName,
                                GroupDistinguishedName = Membership
                            };
                        }
                    }
                }
            }
            return(ForeignUsers);
        }
Пример #3
0
        public static IEnumerable <object> Find_DomainUserEvent(Args_Find_DomainUserEvent args = null)
        {
            if (args == null)
            {
                args = new Args_Find_DomainUserEvent();
            }

            var UserSearcherArguments = new Args_Get_DomainUser
            {
                Properties      = new[] { "samaccountname" },
                Identity        = args.UserIdentity,
                Domain          = args.UserDomain,
                LDAPFilter      = args.UserLDAPFilter,
                SearchBase      = args.UserSearchBase,
                AdminCount      = args.UserAdminCount,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            string[] TargetUsers = null;
            if (args.UserIdentity != null || !string.IsNullOrEmpty(args.UserLDAPFilter) || !string.IsNullOrEmpty(args.UserSearchBase) || args.UserAdminCount)
            {
                TargetUsers = GetDomainUser.Get_DomainUser(UserSearcherArguments).Select(x => (x as LDAPProperty).samaccountname).ToArray();
            }
            else if (args.UserGroupIdentity != null || (args.Filter == null))
            {
                // otherwise we're querying a specific group
                var GroupSearcherArguments = new Args_Get_DomainGroupMember
                {
                    Identity        = args.UserGroupIdentity,
                    Recurse         = true,
                    Domain          = args.UserDomain,
                    SearchBase      = args.UserSearchBase,
                    Server          = args.Server,
                    SearchScope     = args.SearchScope,
                    ResultPageSize  = args.ResultPageSize,
                    ServerTimeLimit = args.ServerTimeLimit,
                    Tombstone       = args.Tombstone,
                    Credential      = args.Credential
                };
                Logger.Write_Verbose($@"UserGroupIdentity: {args.UserGroupIdentity.ToJoinedString()}");
                TargetUsers = GetDomainGroupMember.Get_DomainGroupMember(GroupSearcherArguments).Select(x => x.MemberName).ToArray();
            }

            // build the set of computers to enumerate
            string[] TargetComputers = null;
            if (args.ComputerName != null)
            {
                TargetComputers = args.ComputerName;
            }
            else
            {
                // if not -ComputerName is passed, query the current (or target) domain for domain controllers
                var DCSearcherArguments = new Args_Get_DomainController
                {
                    LDAP       = true,
                    Domain     = args.Domain,
                    Server     = args.Server,
                    Credential = args.Credential
                };
                Logger.Write_Verbose($@"[Find-DomainUserEvent] Querying for domain controllers in domain: {args.Domain}");
                TargetComputers = GetDomainController.Get_DomainController(DCSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
            }
            Logger.Write_Verbose($@"[Find-DomainUserEvent] TargetComputers length: {TargetComputers.Count()}");
            Logger.Write_Verbose($@"[Find-DomainUserEvent] TargetComputers {TargetComputers.ToJoinedString()}");
            if (TargetComputers == null || TargetComputers.Length == 0)
            {
                throw new Exception("[Find-DomainUserEvent] No hosts found to enumerate");
            }

            var rets = new List <IWinEvent>();

            // only ignore threading if -Delay is passed
            if (args.Delay != 0 || args.StopOnSuccess)
            {
                Logger.Write_Verbose($@"[Find-DomainUserEvent] TargetComputers length: {TargetComputers.Length}");
                Logger.Write_Verbose($@"[Find-DomainUserEvent] Delay: {args.Delay}, Jitter: {args.Jitter}");
                var Counter = 0;
                var RandNo  = new System.Random();

                foreach (var TargetComputer in TargetComputers)
                {
                    Counter = Counter + 1;

                    // sleep for our semi-randomized interval
                    System.Threading.Thread.Sleep(RandNo.Next((int)((1 - args.Jitter) * args.Delay), (int)((1 + args.Jitter) * args.Delay)) * 1000);

                    Logger.Write_Verbose($@"[Find-DomainUserEvent] Enumerating server {TargetComputer} ({Counter} of {TargetComputers.Count()})");
                    var Result = _Find_DomainUserEvent(new[] { TargetComputer }, args.StartTime, args.EndTime, args.MaxEvents, TargetUsers, args.Filter, args.Credential);
                    if (Result != null)
                    {
                        rets.AddRange(Result);
                    }

                    if (Result != null && args.StopOnSuccess)
                    {
                        Logger.Write_Verbose("[Find-DomainUserEvent] Target user found, returning early");
                        return(rets);
                    }
                }
            }
            else
            {
                Logger.Write_Verbose($@"[Find-DomainUserEvent] Using threading with threads: {args.Threads}");

                // if we're using threading, kick off the script block with New-ThreadedFunction
                // if we're using threading, kick off the script block with New-ThreadedFunction using the $HostEnumBlock + params
                System.Threading.Tasks.Parallel.ForEach(
                    TargetComputers,
                    TargetComputer =>
                {
                    var Result = _Find_DomainUserEvent(new[] { TargetComputer }, args.StartTime, args.EndTime, args.MaxEvents, TargetUsers, args.Filter, args.Credential);
                    lock (rets)
                    {
                        if (Result != null)
                        {
                            rets.AddRange(Result);
                        }
                    }
                });
            }

            return(rets);
        }
Пример #4
0
        public static IEnumerable <UserProcess> Find_DomainProcess(Args_Find_DomainProcess args = null)
        {
            if (args == null)
            {
                args = new Args_Find_DomainProcess();
            }

            var ComputerSearcherArguments = new Args_Get_DomainComputer
            {
                Properties      = new[] { "dnshostname" },
                Domain          = args.Domain,
                LDAPFilter      = args.ComputerLDAPFilter,
                SearchBase      = args.ComputerSearchBase,
                Unconstrained   = args.Unconstrained,
                OperatingSystem = args.OperatingSystem,
                ServicePack     = args.ServicePack,
                SiteName        = args.SiteName,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            if (!string.IsNullOrEmpty(args.ComputerDomain))
            {
                ComputerSearcherArguments.Domain = args.ComputerDomain;
            }

            var UserSearcherArguments = new Args_Get_DomainUser
            {
                Properties      = new[] { "samaccountname" },
                Identity        = args.UserIdentity,
                Domain          = args.Domain,
                LDAPFilter      = args.UserLDAPFilter,
                SearchBase      = args.UserSearchBase,
                AdminCount      = args.UserAdminCount,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            if (!string.IsNullOrEmpty(args.UserDomain))
            {
                UserSearcherArguments.Domain = args.UserDomain;
            }

            // first, build the set of computers to enumerate
            string[] TargetComputers = null;
            if (args.ComputerName != null)
            {
                TargetComputers = args.ComputerName;
            }
            else
            {
                Logger.Write_Verbose(@"[Find-DomainProcess] Querying computers in the domain");
                TargetComputers = GetDomainComputer.Get_DomainComputer(ComputerSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
            }
            if (TargetComputers == null || TargetComputers.Length == 0)
            {
                throw new Exception("[Find-DomainProcess] No hosts found to enumerate");
            }
            Logger.Write_Verbose($@"[Find-DomainProcess] TargetComputers length: {TargetComputers.Length}");

            // now build the user target set
            List <string> TargetProcessName = null;

            string[] TargetUsers = null;
            if (args.ProcessName != null)
            {
                TargetProcessName = new List <string>();
                foreach (var T in args.ProcessName)
                {
                    TargetProcessName.AddRange(T.Split(','));
                }
            }
            else if (args.UserIdentity != null || args.UserLDAPFilter != null || args.UserSearchBase != null || args.UserAdminCount /* || args.UserAllowDelegation*/)
            {
                TargetUsers = GetDomainUser.Get_DomainUser(UserSearcherArguments).Select(x => (x as LDAPProperty).samaccountname).ToArray();
            }
            else
            {
                var GroupSearcherArguments = new Args_Get_DomainGroupMember
                {
                    Identity        = args.UserGroupIdentity,
                    Recurse         = true,
                    Domain          = args.UserDomain,
                    SearchBase      = args.UserSearchBase,
                    Server          = args.Server,
                    SearchScope     = args.SearchScope,
                    ResultPageSize  = args.ResultPageSize,
                    ServerTimeLimit = args.ServerTimeLimit,
                    Tombstone       = args.Tombstone,
                    Credential      = args.Credential
                };
                TargetUsers = GetDomainGroupMember.Get_DomainGroupMember(GroupSearcherArguments).Select(x => x.MemberName).ToArray();
            }

            var rets = new List <UserProcess>();

            // only ignore threading if -Delay is passed
            if (args.Delay != 0 || args.StopOnSuccess)
            {
                Logger.Write_Verbose($@"[Find-DomainProcess] Total number of hosts: {TargetComputers.Count()}");
                Logger.Write_Verbose($@"[Find-DomainProcess] Delay: {args.Delay}, Jitter: {args.Jitter}");
                var Counter = 0;
                var RandNo  = new System.Random();

                foreach (var TargetComputer in TargetComputers)
                {
                    Counter = Counter + 1;

                    // sleep for our semi-randomized interval
                    System.Threading.Thread.Sleep(RandNo.Next((int)((1 - args.Jitter) * args.Delay), (int)((1 + args.Jitter) * args.Delay)) * 1000);

                    Logger.Write_Verbose($@"[Find-DomainProcess] Enumerating server {TargetComputer} ({Counter} of {TargetComputers.Count()})");
                    var Result = _Find_DomainProcess(new[] { TargetComputer }, TargetProcessName?.ToArray(), TargetUsers, args.Credential);
                    if (Result != null)
                    {
                        rets.AddRange(Result);
                    }

                    if (Result != null && args.StopOnSuccess)
                    {
                        Logger.Write_Verbose("[Find-DomainProcess] Target user found, returning early");
                        return(rets);
                    }
                }
            }
            else
            {
                Logger.Write_Verbose($@"[Find-DomainProcess] Using threading with threads: {args.Threads}");

                // if we're using threading, kick off the script block with New-ThreadedFunction
                // if we're using threading, kick off the script block with New-ThreadedFunction using the $HostEnumBlock + params
                System.Threading.Tasks.Parallel.ForEach(
                    TargetComputers,
                    TargetComputer =>
                {
                    var Result = _Find_DomainProcess(new[] { TargetComputer }, TargetProcessName?.ToArray(), TargetUsers, args.Credential);
                    lock (rets)
                    {
                        if (Result != null)
                        {
                            rets.AddRange(Result);
                        }
                    }
                });
            }

            return(rets);
        }
        public static IEnumerable <PropertyOutlier> Find_DomainObjectPropertyOutlier(Args_Find_DomainObjectPropertyOutlier args = null)
        {
            if (args == null)
            {
                args = new Args_Find_DomainObjectPropertyOutlier();
            }

            var UserReferencePropertySet = new[] { "admincount", "accountexpires", "badpasswordtime", "badpwdcount", "cn", "codepage", "countrycode", "description", "displayname", "distinguishedname", "dscorepropagationdata", "givenname", "instancetype", "iscriticalsystemobject", "lastlogoff", "lastlogon", "lastlogontimestamp", "lockouttime", "logoncount", "memberof", "msds-supportedencryptiontypes", "name", "objectcategory", "objectclass", "objectguid", "objectsid", "primarygroupid", "pwdlastset", "samaccountname", "samaccounttype", "sn", "useraccountcontrol", "userprincipalname", "usnchanged", "usncreated", "whenchanged", "whencreated" };

            var GroupReferencePropertySet = new[] { "admincount", "cn", "description", "distinguishedname", "dscorepropagationdata", "grouptype", "instancetype", "iscriticalsystemobject", "member", "memberof", "name", "objectcategory", "objectclass", "objectguid", "objectsid", "samaccountname", "samaccounttype", "systemflags", "usnchanged", "usncreated", "whenchanged", "whencreated" };

            var ComputerReferencePropertySet = new[] { "accountexpires", "badpasswordtime", "badpwdcount", "cn", "codepage", "countrycode", "distinguishedname", "dnshostname", "dscorepropagationdata", "instancetype", "iscriticalsystemobject", "lastlogoff", "lastlogon", "lastlogontimestamp", "localpolicyflags", "logoncount", "msds-supportedencryptiontypes", "name", "objectcategory", "objectclass", "objectguid", "objectsid", "operatingsystem", "operatingsystemservicepack", "operatingsystemversion", "primarygroupid", "pwdlastset", "samaccountname", "samaccounttype", "serviceprincipalname", "useraccountcontrol", "usnchanged", "usncreated", "whenchanged", "whencreated" };

            var SearcherArgumentsForUser = new Args_Get_DomainUser
            {
                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 SearcherArgumentsForGroup = new Args_Get_DomainGroup
            {
                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 SearcherArgumentsForComputer = new Args_Get_DomainComputer
            {
                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
            };

            // Domain / Credential
            var TargetForest = string.Empty;

            if (!args.Domain.IsNullOrEmpty())
            {
                if (args.Credential != null)
                {
                    TargetForest = GetDomain.Get_Domain(new Args_Get_Domain {
                        Domain = args.Domain
                    }).Forest.Name;
                }
                else
                {
                    TargetForest = GetDomain.Get_Domain(new Args_Get_Domain {
                        Domain = args.Domain, Credential = args.Credential
                    }).Forest.Name;
                }
                Logger.Write_Verbose($@"[Find-DomainObjectPropertyOutlier] Enumerated forest '{TargetForest}' for target domain '{args.Domain}'");
            }

            var SchemaArguments = new
            {
                Credential = args.Credential,
                Forest     = TargetForest
            };

            string[]  ReferenceObjectProperties = null;
            ClassType?ReferenceObjectClass      = null;

            if (args.ReferencePropertySet != null)
            {
                Logger.Write_Verbose(@"[Find-DomainObjectPropertyOutlier] Using specified -ReferencePropertySet");
                ReferenceObjectProperties = args.ReferencePropertySet;
            }
            else if (args.ReferenceObject != null)
            {
                Logger.Write_Verbose(@"[Find-DomainObjectPropertyOutlier] Extracting property names from -ReferenceObject to use as the reference property set");
                ReferenceObjectProperties = args.ReferenceObject.GetType().GetProperties().Select(x => x.Name).ToArray();
                ReferenceObjectClass      = args.ReferenceObject.GetPropValue <ClassType>("objectclass");
                Logger.Write_Verbose($@"[Find-DomainObjectPropertyOutlier] Calculated ReferenceObjectClass : {ReferenceObjectClass}");
            }
            else
            {
                Logger.Write_Verbose($@"[Find-DomainObjectPropertyOutlier] Using the default reference property set for the object class '{args.ClassName}'");
            }

            IEnumerable <object> Objects;

            if ((args.ClassName == ClassType.User) || (ReferenceObjectClass == ClassType.User))
            {
                Objects = GetDomainUser.Get_DomainUser(SearcherArgumentsForUser);
                if (ReferenceObjectProperties == null)
                {
                    ReferenceObjectProperties = UserReferencePropertySet;
                }
            }
            else if ((args.ClassName == ClassType.Group) || (ReferenceObjectClass == ClassType.Group))
            {
                Objects = GetDomainGroup.Get_DomainGroup(SearcherArgumentsForGroup);
                if (ReferenceObjectProperties == null)
                {
                    ReferenceObjectProperties = GroupReferencePropertySet;
                }
            }
            else if ((args.ClassName == ClassType.Computer) || (ReferenceObjectClass == ClassType.Computer))
            {
                Objects = GetDomainComputer.Get_DomainComputer(SearcherArgumentsForComputer);
                if (ReferenceObjectProperties == null)
                {
                    ReferenceObjectProperties = ComputerReferencePropertySet;
                }
            }
            else
            {
                throw new Exception($@"[Find-DomainObjectPropertyOutlier] Invalid class: {args.ClassName}");
            }

            var PropertyOutliers = new List <PropertyOutlier>();

            foreach (LDAPProperty Object in Objects)
            {
                var ObjectProperties = Object.GetType().GetProperties().Select(x => x.Name).ToArray();
                foreach (var ObjectProperty in ObjectProperties)
                {
                    var val = Object.GetPropValue <object>(ObjectProperty);
                    if (val is Dictionary <string, object> )
                    {
                        var dic = val as Dictionary <string, object>;
                        foreach (var ObjectProperty1 in dic.Keys)
                        {
                            if (!ReferenceObjectProperties.ContainsNoCase(ObjectProperty1))
                            {
                                var Out = new PropertyOutlier
                                {
                                    SamAccountName = Object.samaccountname,
                                    Property       = ObjectProperty1,
                                    Value          = dic[ObjectProperty1]
                                };
                                PropertyOutliers.Add(Out);
                            }
                        }
                    }
                    else if (val != null && !ReferenceObjectProperties.ContainsNoCase(ObjectProperty))
                    {
                        var Out = new PropertyOutlier
                        {
                            SamAccountName = Object.samaccountname,
                            Property       = ObjectProperty,
                            Value          = Object.GetPropValue <object>(ObjectProperty)
                        };
                        PropertyOutliers.Add(Out);
                    }
                }
            }

            return(PropertyOutliers);
        }
Пример #6
0
        public static IEnumerable <object> Get_DomainUser(Args_Get_DomainUser args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainUser();
            }

            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 UserSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
            var Users        = new List <object>();

            if (UserSearcher != null)
            {
                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-DomainUser] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                SearcherArguments.Domain = IdentityDomain;
                                UserSearcher             = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                if (UserSearcher == null)
                                {
                                    Logger.Write_Warning($@"[Get-DomainUser] 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 UserDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/'));
                                var UserName   = IdentityInstance.Split(new char[] { '\\' })[1];
                                IdentityFilter          += $@"(samAccountName={UserName})";
                                SearcherArguments.Domain = UserDomain;
                                Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{UserDomain}' from '{IdentityInstance}'");
                                UserSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                            }
                        }
                        else
                        {
                            IdentityFilter += $@"(samAccountName={IdentityInstance})";
                        }
                    }
                }

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

                if (args.SPN)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for non-null service principal names");
                    Filter += "(servicePrincipalName=*)";
                }
                if (args.AllowDelegation)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for users who can be delegated");
                    // negation of "Accounts that are sensitive and not trusted for delegation"
                    Filter += "(!(userAccountControl:1.2.840.113556.1.4.803:=1048574))";
                }
                if (args.DisallowDelegation)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for users who are sensitive and not trusted for delegation");
                    Filter += "(userAccountControl:1.2.840.113556.1.4.803:=1048574)";
                }
                if (args.AdminCount)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for adminCount=1");
                    Filter += "(admincount=1)";
                }
                if (args.TrustedToAuth)
                {
                    Logger.Write_Verbose("[Get-DomainUser] Searching for users that are trusted to authenticate for other principals");
                    Filter += "(msds-allowedtodelegateto=*)";
                }
                if (args.PreauthNotRequired)
                {
                    Logger.Write_Verbose("[Get-DomainUser] Searching for user accounts that do not require kerberos preauthenticate");
                    Filter += "(userAccountControl:1.2.840.113556.1.4.803:=4194304)";
                }
                if (args.LDAPFilter.IsNotNullOrEmpty())
                {
                    Logger.Write_Verbose($@"[Get-DomainUser] Using additional LDAP filter: {args.LDAPFilter}");
                    Filter += $@"{args.LDAPFilter}";
                }

                // build the LDAP filter for the dynamic UAC filter value
                var uacs = args.UACFilter.ExtractValues();
                foreach (var uac in uacs)
                {
                    if (uac.IsNot())
                    {
                        Filter += $@"(!(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()}))";
                    }
                    else
                    {
                        Filter += $@"(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()})";
                    }
                }

                UserSearcher.Filter = $@"(&(samAccountType=805306368){Filter})";
                Logger.Write_Verbose($@"[Get-DomainUser] filter string: {UserSearcher.Filter}");

                if (args.FindOne)
                {
                    var result = UserSearcher.FindOne();
                    if (args.Raw)
                    {
                        // return raw result objects
                        Users.Add(result);
                    }
                    else
                    {
                        Users.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                    }
                }
                else
                {
                    var Results = UserSearcher.FindAll();
                    foreach (SearchResult result in Results)
                    {
                        if (args.Raw)
                        {
                            // return raw result objects
                            Users.Add(result);
                        }
                        else
                        {
                            Users.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                        }
                    }
                    if (Results != null)
                    {
                        try { Results.Dispose(); }
                        catch (Exception e)
                        {
                            Logger.Write_Verbose($@"[Get-DomainUser] Error disposing of the Results object: {e}");
                        }
                    }
                }
                UserSearcher.Dispose();
            }
            return(Users);
        }
Пример #7
0
 public static IEnumerable <object> Get_NetUser(Args_Get_DomainUser args = null)
 {
     return(GetDomainUser.Get_DomainUser(args));
 }
Пример #8
0
        public static IEnumerable <UserLocation> Find_DomainUserLocation(Args_Find_DomainUserLocation args = null)
        {
            if (args == null)
            {
                args = new Args_Find_DomainUserLocation();
            }

            var ComputerSearcherArguments = new Args_Get_DomainComputer
            {
                Properties      = new[] { "dnshostname" },
                Domain          = args.Domain,
                LDAPFilter      = args.ComputerLDAPFilter,
                SearchBase      = args.ComputerSearchBase,
                Unconstrained   = args.Unconstrained,
                OperatingSystem = args.OperatingSystem,
                ServicePack     = args.ServicePack,
                SiteName        = args.SiteName,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            if (!string.IsNullOrEmpty(args.ComputerDomain))
            {
                ComputerSearcherArguments.Domain = args.ComputerDomain;
            }

            var UserSearcherArguments = new Args_Get_DomainUser
            {
                Properties      = new[] { "samaccountname" },
                Identity        = args.UserIdentity,
                Domain          = args.Domain,
                LDAPFilter      = args.UserLDAPFilter,
                SearchBase      = args.UserSearchBase,
                AdminCount      = args.UserAdminCount,
                AllowDelegation = args.AllowDelegation,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            if (!string.IsNullOrEmpty(args.UserDomain))
            {
                UserSearcherArguments.Domain = args.UserDomain;
            }

            string[] TargetComputers = null;

            // first, build the set of computers to enumerate
            if (args.ComputerName != null)
            {
                TargetComputers = args.ComputerName;
            }
            else
            {
                if (args.Stealth)
                {
                    Logger.Write_Verbose($@"[Find-DomainUserLocation] Stealth enumeration using source: {args.StealthSource}");
                    var TargetComputerArrayList = new System.Collections.ArrayList();

                    if (args.StealthSource.ToString().IsRegexMatch("File|All"))
                    {
                        Logger.Write_Verbose("[Find-DomainUserLocation] Querying for file servers");
                        var FileServerSearcherArguments = new Args_Get_DomainFileServer
                        {
                            Domain          = new[] { args.Domain },
                            SearchBase      = args.ComputerSearchBase,
                            Server          = args.Server,
                            SearchScope     = args.SearchScope,
                            ResultPageSize  = args.ResultPageSize,
                            ServerTimeLimit = args.ServerTimeLimit,
                            Tombstone       = args.Tombstone,
                            Credential      = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            FileServerSearcherArguments.Domain = new[] { args.ComputerDomain }
                        }
                        ;
                        var FileServers = GetDomainFileServer.Get_DomainFileServer(FileServerSearcherArguments);
                        TargetComputerArrayList.AddRange(FileServers);
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DFS|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for DFS servers");
                        // { TODO: fix the passed parameters to Get-DomainDFSShare
                        // $ComputerName += Get-DomainDFSShare -Domain $Domain -Server $DomainController | ForEach-Object {$_.RemoteServerName}
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DC|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for domain controllers");
                        var DCSearcherArguments = new Args_Get_DomainController
                        {
                            LDAP       = true,
                            Domain     = args.Domain,
                            Server     = args.Server,
                            Credential = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            DCSearcherArguments.Domain = args.ComputerDomain;
                        }
                        var DomainControllers = GetDomainController.Get_DomainController(DCSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
                        TargetComputerArrayList.AddRange(DomainControllers);
                    }
                    TargetComputers = TargetComputerArrayList.ToArray() as string[];
                }
            }
            if (args.ComputerName != null)
            {
                TargetComputers = args.ComputerName;
            }
            else
            {
                if (args.Stealth)
                {
                    Logger.Write_Verbose($@"[Find-DomainUserLocation] Stealth enumeration using source: {args.StealthSource}");
                    var TargetComputerArrayList = new System.Collections.ArrayList();

                    if (args.StealthSource.ToString().IsRegexMatch("File|All"))
                    {
                        Logger.Write_Verbose("[Find-DomainUserLocation] Querying for file servers");
                        var FileServerSearcherArguments = new Args_Get_DomainFileServer
                        {
                            Domain          = new[] { args.Domain },
                            SearchBase      = args.ComputerSearchBase,
                            Server          = args.Server,
                            SearchScope     = args.SearchScope,
                            ResultPageSize  = args.ResultPageSize,
                            ServerTimeLimit = args.ServerTimeLimit,
                            Tombstone       = args.Tombstone,
                            Credential      = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            FileServerSearcherArguments.Domain = new[] { args.ComputerDomain }
                        }
                        ;
                        var FileServers = GetDomainFileServer.Get_DomainFileServer(FileServerSearcherArguments);
                        TargetComputerArrayList.AddRange(FileServers);
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DFS|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for DFS servers");
                        // { TODO: fix the passed parameters to Get-DomainDFSShare
                        // $ComputerName += Get-DomainDFSShare -Domain $Domain -Server $DomainController | ForEach-Object {$_.RemoteServerName}
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DC|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for domain controllers");
                        var DCSearcherArguments = new Args_Get_DomainController
                        {
                            LDAP       = true,
                            Domain     = args.Domain,
                            Server     = args.Server,
                            Credential = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            DCSearcherArguments.Domain = args.ComputerDomain;
                        }
                        var DomainControllers = GetDomainController.Get_DomainController(DCSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
                        TargetComputerArrayList.AddRange(DomainControllers);
                    }
                    TargetComputers = TargetComputerArrayList.ToArray() as string[];
                }
                else
                {
                    Logger.Write_Verbose("[Find-DomainUserLocation] Querying for all computers in the domain");
                    TargetComputers = GetDomainComputer.Get_DomainComputer(ComputerSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
                }
            }
            Logger.Write_Verbose($@"[Find-DomainUserLocation] TargetComputers length: {TargetComputers.Length}");
            if (TargetComputers.Length == 0)
            {
                throw new Exception("[Find-DomainUserLocation] No hosts found to enumerate");
            }

            // get the current user so we can ignore it in the results
            string CurrentUser;

            if (args.Credential != null)
            {
                CurrentUser = args.Credential.UserName;
            }
            else
            {
                CurrentUser = Environment.UserName.ToLower();
            }

            // now build the user target set
            string[] TargetUsers = null;
            if (args.ShowAll)
            {
                TargetUsers = new string[] { };
            }
            else if (args.UserIdentity != null || args.UserLDAPFilter != null || args.UserSearchBase != null || args.UserAdminCount || args.UserAllowDelegation)
            {
                TargetUsers = GetDomainUser.Get_DomainUser(UserSearcherArguments).Select(x => (x as LDAPProperty).samaccountname).ToArray();
            }
            else
            {
                var GroupSearcherArguments = new Args_Get_DomainGroupMember
                {
                    Identity        = args.UserGroupIdentity,
                    Recurse         = true,
                    Domain          = args.UserDomain,
                    SearchBase      = args.UserSearchBase,
                    Server          = args.Server,
                    SearchScope     = args.SearchScope,
                    ResultPageSize  = args.ResultPageSize,
                    ServerTimeLimit = args.ServerTimeLimit,
                    Tombstone       = args.Tombstone,
                    Credential      = args.Credential
                };
                TargetUsers = GetDomainGroupMember.Get_DomainGroupMember(GroupSearcherArguments).Select(x => x.MemberName).ToArray();
            }

            Logger.Write_Verbose($@"[Find-DomainUserLocation] TargetUsers length: {TargetUsers.Length}");
            if ((!args.ShowAll) && (TargetUsers.Length == 0))
            {
                throw new Exception("[Find-DomainUserLocation] No users found to target");
            }

            var LogonToken = IntPtr.Zero;

            if (args.Credential != null)
            {
                if (args.Delay != 0 || args.StopOnSuccess)
                {
                    LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                    {
                        Credential = args.Credential
                    });
                }
                else
                {
                    LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                    {
                        Credential = args.Credential,
                        Quiet      = true
                    });
                }
            }

            var rets = new List <UserLocation>();

            // only ignore threading if -Delay is passed
            if (args.Delay != 0 /* || args.StopOnSuccess*/)
            {
                Logger.Write_Verbose($@"[Find-DomainUserLocation] Total number of hosts: {TargetComputers.Count()}");
                Logger.Write_Verbose($@"[Find-DomainUserLocation] Delay: {args.Delay}, Jitter: {args.Jitter}");

                var Counter = 0;
                var RandNo  = new System.Random();

                foreach (var TargetComputer in TargetComputers)
                {
                    Counter = Counter + 1;

                    // sleep for our semi-randomized interval
                    System.Threading.Thread.Sleep(RandNo.Next((int)((1 - args.Jitter) * args.Delay), (int)((1 + args.Jitter) * args.Delay)) * 1000);

                    Logger.Write_Verbose($@"[Find-DomainUserLocation] Enumerating server {TargetComputer} ({Counter} of {TargetComputers.Count()})");
                    var Result = _Find_DomainUserLocation(new[] { TargetComputer }, TargetUsers, CurrentUser, args.Stealth, args.CheckAccess, LogonToken);
                    if (Result != null)
                    {
                        rets.AddRange(Result);
                    }
                    if (Result != null && args.StopOnSuccess)
                    {
                        Logger.Write_Verbose("[Find-DomainUserLocation] Target user found, returning early");
                        return(rets);
                    }
                }
            }
            else
            {
                Logger.Write_Verbose($@"[Find-DomainUserLocation] Using threading with threads: {args.Threads}");
                Logger.Write_Verbose($@"[Find-DomainUserLocation] TargetComputers length: {TargetComputers.Length}");

                // if we're using threading, kick off the script block with New-ThreadedFunction
                // if we're using threading, kick off the script block with New-ThreadedFunction using the $HostEnumBlock + params
                System.Threading.Tasks.Parallel.ForEach(
                    TargetComputers,
                    TargetComputer =>
                {
                    var Result = _Find_DomainUserLocation(new[] { TargetComputer }, TargetUsers, CurrentUser, args.Stealth, args.CheckAccess, LogonToken);
                    lock (rets)
                    {
                        if (Result != null)
                        {
                            rets.AddRange(Result);
                        }
                    }
                });
            }

            if (LogonToken != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(rets);
        }