Esempio n. 1
0
        public static IEnumerable <object> Get_DomainController(Args_Get_DomainController args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainController();
            }

            var Arguments = new Args_Get_DomainComputer();

            if (args.Domain.IsNotNullOrEmpty())
            {
                Arguments.Domain = args.Domain;
            }
            if (args.Credential != null)
            {
                Arguments.Credential = args.Credential;
            }

            if (args.LDAP || args.Server.IsNotNullOrEmpty())
            {
                if (args.Server.IsNotNullOrEmpty())
                {
                    Arguments.Server = args.Server;
                }

                // UAC specification for domain controllers
                Arguments.LDAPFilter = @"(userAccountControl:1.2.840.113556.1.4.803:=8192)";

                return(GetDomainComputer.Get_DomainComputer(Arguments));
            }
            else
            {
                var FoundDomain = GetDomain.Get_Domain(new Args_Get_Domain
                {
                    Domain     = Arguments.Domain,
                    Credential = Arguments.Credential
                });
                if (FoundDomain != null)
                {
                    var controllers = new List <object>();
                    foreach (var controller in FoundDomain.DomainControllers)
                    {
                        controllers.Add(controller);
                    }
                    return(controllers);
                }
            }
            return(null);
        }
Esempio n. 2
0
        public static IEnumerable <IDomainTrust> Get_DomainTrust(Args_Get_DomainTrust args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainTrust();
            }

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

            Args_Get_DomainSID NetSearcherArguments = null;
            string             SourceDomain         = null;

            if (!args.API)
            {
                NetSearcherArguments = new Args_Get_DomainSID();
                if (args.Domain.IsNotNullOrEmpty() && args.Domain.Trim() != "")
                {
                    SourceDomain = args.Domain;
                }
                else
                {
                    if (args.Credential != null)
                    {
                        SourceDomain = GetDomain.Get_Domain(new Args_Get_Domain {
                            Credential = args.Credential
                        }).Name;
                    }
                    else
                    {
                        SourceDomain = GetDomain.Get_Domain().Name;
                    }
                }
            }
            else if (!args.NET)
            {
                if (args.Domain != null && args.Domain.Trim() != "")
                {
                    SourceDomain = args.Domain;
                }
                else
                {
                    SourceDomain = Environment.GetEnvironmentVariable("USERDNSDOMAIN");
                }
            }

            var DomainTrusts = new List <IDomainTrust>();

            if (!args.API && !args.NET)
            {
                // if we're searching for domain trusts through LDAP/ADSI
                var TrustSearcher = GetDomainSearcher.Get_DomainSearcher(LdapSearcherArguments);
                var SourceSID     = GetDomainSID.Get_DomainSID(NetSearcherArguments);

                if (TrustSearcher != null)
                {
                    TrustSearcher.Filter = @"(objectClass=trustedDomain)";

                    SearchResult[] Results = null;
                    if (args.FindOne)
                    {
                        Results = new SearchResult[] { TrustSearcher.FindOne() };
                    }
                    else
                    {
                        var items = TrustSearcher.FindAll();
                        if (items != null)
                        {
                            Results = new SearchResult[items.Count];
                            items.CopyTo(Results, 0);
                        }
                    }
                    if (Results != null)
                    {
                        foreach (var result in Results)
                        {
                            var Props       = result.Properties;
                            var DomainTrust = new LdapDomainTrust();

                            var TrustAttrib = (TrustAttribute)Props[@"trustattributes"][0];

                            var Direction = (TrustDirection)Props[@"trustdirection"][0];

                            var TrustType = (TrustType)Props[@"trusttype"][0];

                            var Distinguishedname = Props[@"distinguishedname"][0] as string;
                            var SourceNameIndex   = Distinguishedname.IndexOf(@"DC=");
                            if (SourceNameIndex != 0)
                            {
                                SourceDomain = Distinguishedname.Substring(SourceNameIndex).Replace(@"DC=", @"").Replace(@",", @".");
                            }
                            else
                            {
                                SourceDomain = @"";
                            }

                            var    TargetNameIndex = Distinguishedname.IndexOf(@",CN=System");
                            string TargetDomain    = null;
                            if (SourceNameIndex != 0)
                            {
                                TargetDomain = Distinguishedname.Substring(3, TargetNameIndex - 3);
                            }
                            else
                            {
                                TargetDomain = @"";
                            }

                            var ObjectGuid = new Guid(Props[@"objectguid"][0] as byte[]);
                            var TargetSID  = (new System.Security.Principal.SecurityIdentifier(Props[@"securityidentifier"][0] as byte[], 0)).Value;

                            DomainTrust = new LdapDomainTrust
                            {
                                SourceName      = SourceDomain,
                                TargetName      = Props[@"name"][0] as string,
                                TrustType       = TrustType,
                                TrustAttributes = TrustAttrib,
                                TrustDirection  = Direction,
                                WhenCreated     = Props[@"whencreated"][0],
                                WhenChanged     = Props[@"whenchanged"][0]
                            };
                            DomainTrusts.Add(DomainTrust);
                        }
                    }
                    TrustSearcher.Dispose();
                }
            }
            else if (args.API)
            {
                // if we're searching for domain trusts through Win32 API functions
                string TargetDC = null;
                if (args.Server.IsNotNullOrEmpty())
                {
                    TargetDC = args.Server;
                }
                else if (args.Domain != null && args.Domain.Trim() != @"")
                {
                    TargetDC = args.Domain;
                }
                else
                {
                    // see https://msdn.microsoft.com/en-us/library/ms675976(v=vs.85).aspx for default NULL behavior
                    TargetDC = null;
                }

                // arguments for DsEnumerateDomainTrusts
                var PtrInfo = IntPtr.Zero;

                // 63 = DS_DOMAIN_IN_FOREST + DS_DOMAIN_DIRECT_OUTBOUND + DS_DOMAIN_TREE_ROOT + DS_DOMAIN_PRIMARY + DS_DOMAIN_NATIVE_MODE + DS_DOMAIN_DIRECT_INBOUND
                uint Flags       = 63;
                uint DomainCount = 0;

                // get the trust information from the target server
                var Result = NativeMethods.DsEnumerateDomainTrusts(TargetDC, Flags, out PtrInfo, out DomainCount);

                // Locate the offset of the initial intPtr
                var Offset = PtrInfo.ToInt64();

                // 0 = success
                if (Result == 0 && Offset > 0)
                {
                    // Work out how much to increment the pointer by finding out the size of the structure
                    var Increment = Marshal.SizeOf(typeof(NativeMethods.DS_DOMAIN_TRUSTS));

                    // parse all the result structures
                    for (var i = 0; i < DomainCount; i++)
                    {
                        // create a new int ptr at the given offset and cast the pointer as our result structure
                        var NewIntPtr = new IntPtr(Offset);
                        var Info      = (NativeMethods.DS_DOMAIN_TRUSTS)Marshal.PtrToStructure(NewIntPtr, typeof(NativeMethods.DS_DOMAIN_TRUSTS));

                        Offset  = NewIntPtr.ToInt64();
                        Offset += Increment;

                        var  SidString = @"";
                        bool ret       = NativeMethods.ConvertSidToStringSid(Info.DomainSid, out SidString);
                        var  LastError = Marshal.GetLastWin32Error();

                        if (ret == false)
                        {
                            Logger.Write_Verbose($@"[Get-DomainTrust] Error: {new System.ComponentModel.Win32Exception(LastError).Message}");
                        }
                        else
                        {
                            var DomainTrust = new ApiDomainTrust
                            {
                                SourceName        = SourceDomain,
                                TargetName        = Info.DnsDomainName,
                                TargetNetbiosName = Info.NetbiosDomainName,
                                Flags             = Info.Flags,
                                ParentIndex       = Info.ParentIndex,
                                TrustType         = (NativeMethods.DS_DOMAIN_TRUST_TYPE)Info.TrustType,
                                TrustAttributes   = Info.TrustAttributes,
                                TargetSid         = SidString,
                                TargetGuid        = Info.DomainGuid
                            };
                            DomainTrusts.Add(DomainTrust);
                        }
                    }
                    // free up the result buffer
                    NativeMethods.NetApiBufferFree(PtrInfo);
                }
                else
                {
                    Logger.Write_Verbose($@"[Get-DomainTrust] Error: {new System.ComponentModel.Win32Exception((int)Result).Message}");
                }
            }
            else
            {
                // if we're searching for domain trusts through .NET methods
                var FoundDomain = GetDomain.Get_Domain(new Args_Get_Domain
                {
                    Domain     = NetSearcherArguments.Domain,
                    Credential = NetSearcherArguments.Credential
                });
                if (FoundDomain != null)
                {
                    var items = FoundDomain.GetAllTrustRelationships();
                    foreach (TrustRelationshipInformation item in items)
                    {
                        DomainTrusts.Add(new NetDomainTrust
                        {
                            SourceName     = item.SourceName,
                            TargetName     = item.TargetName,
                            TrustDirection = item.TrustDirection,
                            TrustType      = item.TrustType
                        });
                    }
                }
            }
            return(DomainTrusts);
        }
Esempio n. 3
0
        public static PrincipalContextEx Get_PrincipalContext(Args_Get_PrincipalContext args = null)
        {
            if (args == null)
            {
                args = new Args_Get_PrincipalContext();
            }

            try
            {
                var ConnectTarget  = string.Empty;
                var ObjectIdentity = string.Empty;
                System.DirectoryServices.AccountManagement.PrincipalContext Context = null;
                if (!string.IsNullOrEmpty(args.Domain) || args.Identity.IsRegexMatch(@".+\\.+"))
                {
                    if (args.Identity.IsRegexMatch(@".+\\.+"))
                    {
                        // DOMAIN\groupname
                        var ConvertedIdentity = ConvertADName.Convert_ADName(new Args_Convert_ADName {
                            Identity = new[] { args.Identity }
                        }).FirstOrDefault();
                        if (ConvertedIdentity != null)
                        {
                            ConnectTarget  = ConvertedIdentity.Substring(0, ConvertedIdentity.IndexOf('/'));
                            ObjectIdentity = args.Identity.Split('\\')[1];
                            Logger.Write_Verbose($@"[Get-PrincipalContext] Binding to domain '{ConnectTarget}'");
                        }
                    }
                    else
                    {
                        ObjectIdentity = args.Identity;
                        Logger.Write_Verbose($@"[Get-PrincipalContext] Binding to domain '{args.Domain}'");
                        ConnectTarget = args.Domain;
                    }

                    if (args.Credential != null)
                    {
                        Logger.Write_Verbose($@"[Get-PrincipalContext] Using alternate credentials");
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, ConnectTarget, args.Credential.UserName, args.Credential.Password);
                    }
                    else
                    {
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, ConnectTarget);
                    }
                }
                else
                {
                    if (args.Credential != null)
                    {
                        Logger.Write_Verbose($@"[Get-PrincipalContext] Using alternate credentials");
                        var DomainName = GetDomain.Get_Domain().Name;
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, DomainName, args.Credential.UserName, args.Credential.Password);
                    }
                    else
                    {
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain);
                    }
                    ObjectIdentity = args.Identity;
                }

                return(new PrincipalContextEx
                {
                    Context = Context,
                    Identity = ObjectIdentity
                });
            }
            catch (Exception e)
            {
                Logger.Write_Warning($@"[Get-PrincipalContext] Error creating binding for object ('{args.Identity}') context : {e}");
            }

            return(null);
        }
Esempio n. 4
0
        public static IEnumerable <IDomainTrust> Get_DomainTrustMapping(Args_Get_DomainTrustMapping args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainTrustMapping();
            }

            // keep track of domains seen so we don't hit infinite recursion
            var SeenDomains = new Dictionary <string, string>();

            // our domain status tracker
            var Domains = new System.Collections.Stack();

            var DomainTrustArguments = new Args_Get_DomainTrust
            {
                API             = args.API,
                NET             = args.NET,
                LDAPFilter      = args.LDAPFilter,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            // get the current domain and push it onto the stack
            string CurrentDomain = null;

            if (args.Credential != null)
            {
                CurrentDomain = GetDomain.Get_Domain(new Args_Get_Domain {
                    Credential = args.Credential
                }).Name;
            }
            else
            {
                CurrentDomain = GetDomain.Get_Domain().Name;
            }
            Domains.Push(CurrentDomain);

            var DomainTrustMappings = new List <IDomainTrust>();

            while (Domains.Count != 0)
            {
                string Domain = Domains.Pop() as string;

                // if we haven't seen this domain before
                if (Domain != null && Domain.Trim() != @"" && !SeenDomains.ContainsKey(Domain))
                {
                    Logger.Write_Verbose($@"[Get-DomainTrustMapping] Enumerating trusts for domain: '{Domain}'");

                    // mark it as seen in our list
                    SeenDomains.Add(Domain, "");

                    try
                    {
                        // get all the trusts for this domain
                        DomainTrustArguments.Domain = Domain;
                        var Trusts = GetDomainTrust.Get_DomainTrust(DomainTrustArguments);

                        // get any forest trusts, if they exist
                        if (args.NET)
                        {
                            var ForestTrustArguments = new Args_Get_Forest
                            {
                                Forest     = args.Forest,
                                Credential = args.Credential
                            };
                            Trusts.Union(GetForestTrust.Get_ForestTrust(ForestTrustArguments));
                        }

                        if (Trusts != null)
                        {
                            // enumerate each trust found
                            foreach (var Trust in Trusts)
                            {
                                if (Trust.SourceName.IsNotNullOrEmpty() && Trust.TargetName.IsNotNullOrEmpty())
                                {
                                    // make sure we process the target
                                    Domains.Push(Trust.TargetName);
                                    DomainTrustMappings.Add(Trust);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[Get-DomainTrustMapping] Error: {e}");
                    }
                }
            }
            return(DomainTrustMappings);
        }
        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);
        }
Esempio n. 6
0
        /* connect ldap server & create an searcher object */
        public static System.DirectoryServices.DirectorySearcher Get_DomainSearcher(Args_Get_DomainSearcher args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainSearcher();
            }

            string TargetDomain = null;
            string BindServer   = null;

            var userDnsDomain = Environment.GetEnvironmentVariable("USERDNSDOMAIN");

            if (args.Domain.IsNotNullOrEmpty())
            {
                TargetDomain = args.Domain;

                if (userDnsDomain != null && userDnsDomain.Trim() != "")
                {
                    // see if we can grab the user DNS logon domain from environment variables
                    var UserDomain  = userDnsDomain;
                    var logonServer = Environment.GetEnvironmentVariable("LOGONSERVER");
                    if (logonServer != null && logonServer.Trim() != "" && UserDomain.IsNotNullOrEmpty())
                    {
                        BindServer = $"{logonServer.Replace(@"\\", "")}.{UserDomain}";
                    }
                }
            }
            else if (args.Credential != null)
            {
                // if not -Domain is specified, but -Credential is, try to retrieve the current domain name with Get-Domain
                var DomainObject = GetDomain.Get_Domain(new Args_Get_Domain {
                    Credential = args.Credential
                });
                BindServer   = DomainObject.PdcRoleOwner.Name;
                TargetDomain = DomainObject.Name;
            }
            else if (userDnsDomain != null && userDnsDomain.Trim() != "")
            {
                // see if we can grab the user DNS logon domain from environment variables
                TargetDomain = userDnsDomain;
                var logonServer = Environment.GetEnvironmentVariable("LOGONSERVER");
                if (logonServer != null && logonServer.Trim() != "" && TargetDomain.IsNotNullOrEmpty())
                {
                    BindServer = $"{logonServer.Replace(@"\\", "")}.{TargetDomain}";
                }
            }
            else
            {
                // otherwise, resort to Get-Domain to retrieve the current domain object
                var DomainObject = GetDomain.Get_Domain();
                if (DomainObject == null)
                {
                    System.Environment.Exit(0);
                }
                BindServer   = DomainObject.PdcRoleOwner.Name;
                TargetDomain = DomainObject.Name;
            }

            if (args.Server.IsNotNullOrEmpty())
            {
                // if there's not a specified server to bind to, try to pull a logon server from ENV variables
                BindServer = args.Server;
            }

            var SearchString = "LDAP://";

            if (BindServer != null && BindServer.Trim() != "")
            {
                SearchString += BindServer;
                if (TargetDomain.IsNotNullOrEmpty())
                {
                    SearchString += '/';
                }
            }

            if (args.SearchBasePrefix.IsNotNullOrEmpty())
            {
                SearchString += args.SearchBasePrefix + @",";
            }

            var DN = string.Empty;

            if (args.SearchBase.IsNotNullOrEmpty())
            {
                if (new Regex(@"^GC://").Match(args.SearchBase).Success)
                {
                    // if we're searching the global catalog, get the path in the right format
                    DN           = args.SearchBase.ToUpper().Trim('/');
                    SearchString = string.Empty;
                }
                else
                {
                    if (new Regex(@"^LDAP://").Match(args.SearchBase).Success)
                    {
                        if (new Regex(@"LDAP://.+/.+").Match(args.SearchBase).Success)
                        {
                            SearchString = string.Empty;
                            DN           = args.SearchBase;
                        }
                        else
                        {
                            DN = args.SearchBase.Substring(7);
                        }
                    }
                    else
                    {
                        DN = args.SearchBase;
                    }
                }
            }
            else
            {
                // transform the target domain name into a distinguishedName if an ADS search base is not specified
                if (TargetDomain != null && TargetDomain.Trim() != "")
                {
                    DN = $"DC={TargetDomain.Replace(".", ",DC=")}";
                }
            }

            SearchString += DN;
            Logger.Write_Verbose($@"[Get-DomainSearcher] search base: {SearchString}");

            System.DirectoryServices.DirectorySearcher Searcher = null;
            if (args.Credential != null)
            {
                Logger.Write_Verbose(@"[Get-DomainSearcher] Using alternate credentials for LDAP connection");
                // bind to the inital search object using alternate credentials
                var DomainObject = new System.DirectoryServices.DirectoryEntry(SearchString, args.Credential.UserName, args.Credential.Password);
                Searcher = new System.DirectoryServices.DirectorySearcher(DomainObject);
            }
            else
            {
                // bind to the inital object using the current credentials
                //Searcher = new System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
                var DomainObject = new System.DirectoryServices.DirectoryEntry(SearchString);
                Searcher = new System.DirectoryServices.DirectorySearcher(DomainObject);
            }

            Searcher.PageSize        = args.ResultPageSize;
            Searcher.SearchScope     = args.SearchScope;
            Searcher.CacheResults    = false;
            Searcher.ReferralChasing = System.DirectoryServices.ReferralChasingOption.All;

            if (args.ServerTimeLimit != null)
            {
                Searcher.ServerTimeLimit = new TimeSpan(0, 0, args.ServerTimeLimit.Value);
            }

            if (args.Tombstone)
            {
                Searcher.Tombstone = true;
            }

            if (args.LDAPFilter.IsNotNullOrWhiteSpace())
            {
                Searcher.Filter = args.LDAPFilter;
            }

            if (args.SecurityMasks != null)
            {
                Searcher.SecurityMasks = args.SecurityMasks.Value;
            }

            if (args.Properties != null)
            {
                // handle an array of properties to load w/ the possibility of comma-separated strings
                var PropertiesToLoad = new List <string>();
                foreach (var item in args.Properties)
                {
                    PropertiesToLoad.AddRange(item.Split(','));
                }

                Searcher.PropertiesToLoad.AddRange(PropertiesToLoad.ToArray());
            }

            return(Searcher);
        }
Esempio n. 7
0
        public static IEnumerable <string> ConvertTo_SID(Args_ConvertTo_SID args = null)
        {
            if (args == null)
            {
                args = new Args_ConvertTo_SID();
            }

            var DomainSearcherArguments = new Args_Get_DomainObject
            {
                Domain     = args.Domain,
                Server     = args.Server,
                Credential = args.Credential
            };

            var SIDs = new List <string>();

            foreach (var item in args.ObjectName)
            {
                var name = item.Replace(@"/", @"\");

                if (args.Credential != null)
                {
                    var DN = ConvertADName.Convert_ADName(new Args_Convert_ADName
                    {
                        Identity   = new[] { name },
                        OutputType = ADSNameType.DN,
                        Domain     = DomainSearcherArguments.Domain,
                        Server     = DomainSearcherArguments.Server,
                        Credential = DomainSearcherArguments.Credential
                    });


                    if (DN != null)
                    {
                        var UserDomain = DN.First().Substring(DN.First().IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                        var UserName   = DN.First().Split(',')[0].Split('=')[1];

                        DomainSearcherArguments.Identity   = new[] { UserName };
                        DomainSearcherArguments.Domain     = UserDomain;
                        DomainSearcherArguments.Properties = new[] { @"objectsid" };
                        var obj = GetDomainObject.Get_DomainObject(DomainSearcherArguments);
                        foreach (LDAPProperty ldapProperty in obj)
                        {
                            SIDs.AddRange(ldapProperty.objectsid);
                        }
                    }
                }
                else
                {
                    try
                    {
                        if (name.Contains(@"\"))
                        {
                            args.Domain = name.Split('\\')[0];
                            name        = name.Split('\\')[1];
                        }
                        else if (args.Domain.IsNullOrEmpty())
                        {
                            args.Domain = GetDomain.Get_Domain().Name;
                        }

                        var obj = new System.Security.Principal.NTAccount(args.Domain, name);
                        SIDs.Add(obj.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value);
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[ConvertTo-SID] Error converting {args.Domain}\{name} : {e}");
                    }
                }
            }
            return(SIDs);
        }
Esempio n. 8
0
 public static System.DirectoryServices.ActiveDirectory.Domain Get_NetDomain(Args_Get_Domain args = null)
 {
     return(GetDomain.Get_Domain(args));
 }