internal override int BindSasl(SafeHandle ld, Native.LdapAuthType authType, LdapCredential ldapCredential)
        {
            LdapConnect(ld);
            var cred = ToNative(ldapCredential);

            return(NativeMethodsWindows.ldap_bind_s(ld, null, cred, Native.LdapAuthMechanism.ToBindMethod(authType)));
        }
Exemple #2
0
        public async Task <List <ADComputer> > SearchADComputersAsync(LdapCredential ldapCredential, string query)
        {
            List <ADComputer> result = new List <ADComputer>();

            if (ldapCredential is null)
            {
                throw new Exception("Failed to get LDAP Credentials");
            }

            using (LdapConnection ldapConnection = await CreateBindAsync(ldapCredential.UserName, ldapCredential.Password))
            {
                var    filter               = "(&(objectCategory=computer)(name=" + query + "*))";
                var    PropertiesToLoad     = new string[] { "cn" };
                string defaultNamingContext = _ldapOptions.Value.SearchBase;

                try
                {
                    var ldapSearchResults = await ldapConnection.SearchAsync(defaultNamingContext, filter, PropertiesToLoad, Native.LdapSearchScope.LDAP_SCOPE_SUB);

                    foreach (var ldapSearchResult in ldapSearchResults)
                    {
                        result.Add(new ADComputer(ldapSearchResult.DirectoryAttributes["cn"].GetValues <string>().First()));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
            return(result);
        }
Exemple #3
0
        internal override int BindSasl(SafeHandle ld, Native.LdapAuthType authType, LdapCredential ldapCredential)
        {
            var mech = Native.LdapAuthMechanism.FromAuthType(authType);
            var cred = ToNative(ld, mech, ldapCredential);

            var rc = NativeMethodsOsx.ldap_sasl_interactive_bind_s(ld, null, mech, IntPtr.Zero, IntPtr.Zero,
                (uint) Native.LdapInteractionFlags.LDAP_SASL_QUIET, UnixSaslMethods.SaslInteractionProcedure, cred);
            Marshal.FreeHGlobal(cred);
            return rc;
        }
Exemple #4
0
        public async Task <bool> TestCredentialsAsync(LdapCredential ldapCredential)
        {
            using var connection = await CreateBindAsync(ldapCredential.UserName, ldapCredential.Password);

            if (connection != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #5
0
        internal override async Task <IntPtr> BindSaslAsync(SafeHandle ld, Native.LdapAuthType authType,
                                                            LdapCredential ldapCredential, LDAP_TIMEVAL timeout)
        {
            var task = Task.Factory.StartNew(() =>
            {
                int rc;
                var msgid        = 0;
                var result       = IntPtr.Zero;
                var rmech        = IntPtr.Zero;
                var mech         = Native.LdapAuthMechanism.FromAuthType(authType);
                var cred         = ToNative(ld, mech, ldapCredential);
                var saslDefaults = Marshal.PtrToStructure <Native.LdapSaslDefaults>(cred);
                do
                {
                    rc = NativeMethodsLinux.ldap_sasl_interactive_bind(ld, null, mech, IntPtr.Zero, IntPtr.Zero,
                                                                       (uint)Native.LdapInteractionFlags.LDAP_SASL_QUIET,
                                                                       UnixSaslMethods.SaslInteractionProcedure, cred, result, ref rmech,
                                                                       ref msgid);
                    if (rc != (int)Native.ResultCode.SaslBindInProgress)
                    {
                        break;
                    }

                    ldap_msgfree(result);

                    if (ldap_result(ld, msgid, 0, timeout, ref result) == Native.LdapResultType.LDAP_ERROR)
                    {
                        ThrowIfError(rc, nameof(NativeMethodsLinux.ldap_sasl_interactive_bind));
                    }

                    if (result == IntPtr.Zero)
                    {
                        throw new LdapException(new LdapExceptionData("Result is not initialized",
                                                                      nameof(NativeMethodsLinux.ldap_sasl_interactive_bind), 1));
                    }
                } while (rc == (int)Native.ResultCode.SaslBindInProgress);

                Marshal.FreeHGlobal(cred);

                ThrowIfError(ld, rc, nameof(NativeMethodsLinux.ldap_sasl_interactive_bind),
                             new Dictionary <string, string>
                {
                    [nameof(saslDefaults)] = saslDefaults.ToString()
                });
                return(result);
            });

            return(await task.ConfigureAwait(false));
        }
        internal override async Task <IntPtr> BindSaslAsync(SafeHandle ld, Native.LdapAuthType authType,
                                                            LdapCredential ldapCredential, LDAP_TIMEVAL timeout)
        {
            var cred = ToNative(ldapCredential);

            var task = Task.Factory.StartNew(() =>
            {
                ThrowIfError(
                    NativeMethodsWindows.ldap_bind_s(ld, null, cred, Native.LdapAuthMechanism.ToBindMethod(authType)),
                    nameof(NativeMethodsWindows.ldap_bind_s));

                return(IntPtr.Zero);
            });

            return(await task.ConfigureAwait(false));
        }
        private static SEC_WINNT_AUTH_IDENTITY_EX ToNative(LdapCredential ldapCredential)
        {
            var cred = new SEC_WINNT_AUTH_IDENTITY_EX
            {
                version = NativeMethodsWindows.SEC_WINNT_AUTH_IDENTITY_VERSION,
                length  = Marshal.SizeOf(typeof(SEC_WINNT_AUTH_IDENTITY_EX)),
                flags   = NativeMethodsWindows.SEC_WINNT_AUTH_IDENTITY_UNICODE
            };

            if (ldapCredential != null)
            {
                cred.user           = string.IsNullOrEmpty(ldapCredential.UserName) ? null : ldapCredential.UserName;
                cred.userLength     = ldapCredential.UserName?.Length ?? 0;
                cred.password       = string.IsNullOrEmpty(ldapCredential.Password) ? null : ldapCredential.Password;
                cred.passwordLength = ldapCredential.Password?.Length ?? 0;
                cred.domain         = string.IsNullOrEmpty(ldapCredential.Realm) ? null : ldapCredential.Realm;
                cred.domainLength   = ldapCredential.Realm?.Length ?? 0;
            }

            return(cred);
        }
        internal static IntPtr GetSaslCredentials(LdapCredential ldapCredential, Native.LdapSaslDefaults saslDefaults)
        {
            if (!string.IsNullOrWhiteSpace(ldapCredential?.UserName))
            {
                saslDefaults.authcid = ldapCredential.UserName;
            }

            if (!string.IsNullOrWhiteSpace(ldapCredential?.Password))
            {
                saslDefaults.passwd = ldapCredential.Password;
            }

            if (!string.IsNullOrWhiteSpace(ldapCredential?.AuthorizationId))
            {
                saslDefaults.authzid = ldapCredential?.AuthorizationId;
            }

            var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(saslDefaults));

            Marshal.StructureToPtr(saslDefaults, ptr, false);
            return(ptr);
        }
Exemple #9
0
        public async Task <ADComputer> GetADComputerAsync(LdapCredential ldapCredential, string name)
        {
            ADComputer ADComputer = null;

            if (ldapCredential is null)
            {
                throw new Exception("Failed to get LDAP Credentials");
            }

            using (LdapConnection ldapConnection = await CreateBindAsync(ldapCredential.UserName, ldapCredential.Password))
            {
                string defaultNamingContext = _ldapOptions.Value.SearchBase;

                var ldapSearchResult = (await ldapConnection.SearchByCnAsync(defaultNamingContext, name, Native.LdapSearchScope.LDAP_SCOPE_SUB)).FirstOrDefault();

                if (ldapSearchResult != null)
                {
                    ADComputer = new ADComputer(ldapSearchResult.DirectoryAttributes["cn"].GetValues <string>().First());

                    if (ldapSearchResult.DirectoryAttributes.Any(x => x.Name == "ms-Mcs-AdmPwd"))
                    {
                        ADComputer.LAPSPassword           = ldapSearchResult.DirectoryAttributes["ms-Mcs-AdmPwd"].GetValues <string>().First().ToString();
                        ADComputer.LAPSPasswordExpireDate = DateTime.FromFileTime(Convert.ToInt64(ldapSearchResult.DirectoryAttributes["ms-Mcs-AdmPwdExpirationTime"].GetValues <string>().First().ToString()));
                    }
                    else
                    {
                        throw new Exception("No permission to retrieve LAPS Password");
                    }
                }
                else
                {
                    throw new Exception($"AD Computer {name} could not be found");
                }
            }

            return(ADComputer);
        }
 private static SEC_WINNT_AUTH_IDENTITY_EX GetCredentials(Native.LdapAuthType authType,
                                                          LdapCredential ldapCredential) =>
 authType == Native.LdapAuthType.External ? null : ToNative(ldapCredential);
Exemple #11
0
 internal abstract Task <IntPtr> BindSaslAsync(SafeHandle ld, LdapAuthType authType,
                                               LdapCredential ldapCredential, LDAP_TIMEVAL timeout);
Exemple #12
0
 internal abstract int BindSasl(SafeHandle ld, LdapAuthType authType, LdapCredential ldapCredential);
Exemple #13
0
        private IntPtr ToNative(SafeHandle ld, string mech, LdapCredential ldapCredential)
        {
            var saslDefaults = GetSaslDefaults(ld, mech);

            return(UnixSaslMethods.GetSaslCredentials(ldapCredential, saslDefaults));
        }
Exemple #14
0
 internal abstract Task <IntPtr> BindSaslAsync(SafeHandle ld, LdapAuthType authType,
                                               LdapCredential ldapCredential);
Exemple #15
0
        public static string GetAccountInfo(string ip)
        {
            string ldapInfo = string.Empty;

            using (LdapConnection ldapConnection = new LdapConnection())
            {
                try
                {
                    ldapConnection.Connect(ip);
                    LdapCredential anonymousCredential = new LdapCredential();
                    ldapConnection.Bind(Native.LdapAuthType.Simple, anonymousCredential);
                }
                catch
                {
                    return("- No anonymous authentication allowed" + Environment.NewLine);
                }
                var rootDse = ldapConnection.GetRootDse();
                IList <LdapEntry> searchEntries;
                try
                {
                    if (!rootDse.Attributes.ContainsKey("defaultNamingContext"))
                    {
                        return("- rootDse has no defaultNamingContext. Keys: " + rootDse.Attributes.Count);
                    }
                    searchEntries = ldapConnection.Search(rootDse.Attributes["defaultNamingContext"][0], "(objectclass=user)", scope: Native.LdapSearchScope.LDAP_SCOPE_SUB);
                }
                catch (LdapException)
                {
                    return("- No Anonymous Access Allowed");
                }
                catch (Exception)
                {
                    return(":<");
                }
                foreach (var result in searchEntries)
                {
                    string accountName = result.Attributes["sAMAccountName"].Count > 0 ? result.Attributes["sAMAccountName"][0].ToString() : string.Empty;
                    if (accountName.Trim() == "System.Byte[]")
                    {
                        Console.WriteLine("Woof - Contact Reelix - Something broke in the LDAP Migration!!!");
                        //accountName = Encoding.UTF8.GetString((byte[])result.Attributes["samaccountname"][0]);
                    }
                    ldapInfo += " - Account Name: " + accountName + Environment.NewLine;
                    string commonName = result.Attributes["cn"].Count > 0 ? (string)result.Attributes["cn"][0] : string.Empty;
                    ldapInfo += " -- Common Name: " + commonName + Environment.NewLine;
                    if (result.Attributes.ContainsKey("userPrincipalName"))
                    {
                        ldapInfo += " -- userPrincipalName: " + result.Attributes["userPrincipalName"][0] + Environment.NewLine;
                    }
                    if (result.Attributes["lastLogon"].Count == 1)
                    {
                        string lastLoggedIn = result.Attributes["lastLogon"][0];
                        if (lastLoggedIn != "0")
                        {
                            ldapInfo += " -- lastLogon: " + DateTime.FromFileTime(long.Parse(lastLoggedIn)) + Environment.NewLine;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Something broke with lastLogon :<");
                    }
                    if (result.Attributes.ContainsKey("description"))
                    {
                        string description = (string)result.Attributes["description"][0];
                        ldapInfo += " -- Description: " + result.Attributes["description"][0] + Environment.NewLine;
                    }
                }
            }
            return(ldapInfo.Trim(Environment.NewLine.ToCharArray()));
        }
Exemple #16
0
        public static string GetDefaultNamingContext(string ip, bool raw = false)
        {
            string ldapInfo = string.Empty;

            using (LdapConnection ldapConnection = new LdapConnection())
            {
                ldapConnection.Connect(ip, 389);
                LdapCredential anonymousCredential = new LdapCredential();
                try
                {
                    ldapConnection.Bind(Native.LdapAuthType.Simple, anonymousCredential);
                }
                catch (LdapException le)
                {
                    return("- Connection Error: " + le.Message + Environment.NewLine);
                }
                catch (Exception ex)
                {
                    return("- Unknown Error: " + ex.Message + Environment.NewLine);
                }
                // ldapConnection.AuthType = AuthType.Anonymous;

                var searchEntries = ldapConnection.Search(null, "(objectclass=*)", scope: Native.LdapSearchScope.LDAP_SCOPE_BASE);
                // SearchRequest request = new SearchRequest(null, "(objectclass=*)", System.DirectoryServices.Protocols.SearchScope.Base, "defaultNamingContext");

                // SearchResponse result = (SearchResponse)ldapConnection.SendRequest(request);

                if (searchEntries.Count == 1)
                {
                    if (searchEntries[0].Attributes.ContainsKey("defaultNamingContext"))
                    {
                        string defaultNamingContext = searchEntries[0].Attributes["defaultNamingContext"][0].ToString();
                        if (raw)
                        {
                            ldapInfo = defaultNamingContext;
                        }
                        else
                        {
                            ldapInfo = $"- defaultNamingContext: {defaultNamingContext}" + Environment.NewLine;
                        }
                    }
                    else if (searchEntries[0].Attributes.ContainsKey("objectClass"))
                    {
                        string objectClass = searchEntries[0].Attributes["objectClass"][0].ToString();
                        ldapInfo = "- No defaultNamingContext, but we have an objectClass: " + objectClass + Environment.NewLine;
                    }
                    else
                    {
                        ldapInfo = "- Error: No defaultNamingContext! Keys: " + searchEntries[0].Attributes.Count + Environment.NewLine;
                        foreach (var item in searchEntries[0].Attributes)
                        {
                            ldapInfo += "- Found Key: " + item.Key + " with value " + item.Value + Environment.NewLine;
                        }
                    }
                }
                else
                {
                    ldapInfo = "- Multiple items found! Bug Reelix!" + Environment.NewLine;
                }
            }
            return(ldapInfo);
        }