Esempio n. 1
0
        private static string GetScalarContext(Novell.Directory.Ldap.LdapConnection conn, string attributeName)
        {
            string[] attributesToFetch = new string[] { attributeName };

            // Read the entries subschemaSubentry attribute.
            // Throws an exception if no entries are returned.
            Novell.Directory.Ldap.LdapEntry ent = conn.Read("", attributesToFetch);

            Novell.Directory.Ldap.LdapAttribute attr = ent.getAttribute(attributesToFetch[0]);
            string[] values = attr.StringValueArray;
            if (values == null || values.Length < 1)
            {
                throw new Novell.Directory.Ldap.LdapLocalException(
                          Novell.Directory.Ldap.Utilclass.ExceptionMessages.NO_SCHEMA
                          , new System.Object[] { "" }
                          , Novell.Directory.Ldap.LdapException.NO_RESULTS_RETURNED
                          );
            }

            if (values.Length > 1)
            {
                throw new Novell.Directory.Ldap.LdapLocalException(
                          Novell.Directory.Ldap.Utilclass.ExceptionMessages.MULTIPLE_SCHEMA
                          , new System.Object[] { "" }
                          , Novell.Directory.Ldap.LdapException.CONSTRAINT_VIOLATION
                          );
            }

            return(values[0]);
        } // End Function GetScalarContext
Esempio n. 2
0
        static void TestLogin()
        {
            string ldapHost = MySamples.TestSettings.ldapHost;
            int    ldapPort = MySamples.TestSettings.ldapPort; //System.Convert.ToInt32(args[1]);
            string loginDN  = MySamples.TestSettings.loginDN;  // args[2];
            string password = MySamples.TestSettings.password; // args[3];


            System.Collections.Generic.List <ARSoft.Tools.Net.Dns.SrvRecord> lsLdap = GetLdap();
            ARSoft.Tools.Net.Dns.SrvRecord ldap = lsLdap[0];

            Novell.Directory.Ldap.LdapConnection lc = null;
            int ldapVersion = Novell.Directory.Ldap.LdapConnection.Ldap_V3;

            try
            {
                lc = new Novell.Directory.Ldap.LdapConnection();
                // connect to the server
                lc.Connect(ldap.Target.ToString(), ldap.Port);

                // bind to the server
                lc.Bind(ldapVersion, loginDN, password);
                //lc.Bind(ldapVersion, @"", "");
                // lc.Bind(ldapVersion, (string)null, (string)null);

                System.Console.WriteLine(lc.Bound); // True when login successfull



                Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
                cons.ReferralFollowing = true;
                lc.Constraints         = cons;


                //string dn = "CN=xxx";
                //var entry = lc.Read(dn);
                //libldapsync.Data.LdapGroup grp = libldapsync.Data.LdapGroup.FromEntry(entry);
                //System.Console.WriteLine(grp);

                // string dn = "CN=xxx";
                // var entry = lc.Read(dn);
                // libldapsync.Data.LdapUser user = libldapsync.Data.LdapUser.FromEntry(entry);
                // string json = Newtonsoft.Json.JsonConvert.SerializeObject(user, Newtonsoft.Json.Formatting.Indented);
                // System.Console.WriteLine(json);
            }
            catch (System.Exception ex)
            { }
            finally
            {
                lc.Disconnect();
            }



            System.Console.WriteLine(System.Environment.NewLine);
            Console.WriteLine(" --- Press any key to continue --- ");
            System.Console.ReadKey();
        }
Esempio n. 3
0
        public static IDictionary <string, object> GetProperties(string host, int port, string dn, string username, string password, string[] properties)
        {
            var ret = new Dictionary <string, object> ();

            try {
                var cn = new Novell.Directory.Ldap.LdapConnection();
                cn.Connect(host, port);
                if (string.IsNullOrEmpty(dn))
                {
                    dn = "";
                }
                cn.Bind(username, password, Novell.Directory.Ldap.AuthenticationTypes.Secure | Novell.Directory.Ldap.AuthenticationTypes.ServerBind | Novell.Directory.Ldap.AuthenticationTypes.Signing | Novell.Directory.Ldap.AuthenticationTypes.FastBind);
                var results = cn.Search(dn, Novell.Directory.Ldap.LdapConnection.SCOPE_BASE, null, properties, false);
                var item    = results.next();
                var props   = item.getAttributeSet();
                foreach (Novell.Directory.Ldap.LdapAttribute att in props)
                {
                    object val = null;
                    if (att.Name.Equals("objectsid", StringComparison.OrdinalIgnoreCase))
                    {
                        val = Array.ConvertAll(att.ByteValue, (a) => (byte)a);
                    }
                    else if (att.Name.Equals("objectGUID", StringComparison.OrdinalIgnoreCase))
                    {
                        var guidBytes = Array.ConvertAll(att.ByteValue, (a) => (byte)a);
                        val = new Guid?(new Guid(guidBytes));
                    }
                    else if (att.Name.Equals("objectClass", StringComparison.OrdinalIgnoreCase))
                    {
                        val = att.StringValueArray[att.StringValueArray.GetUpperBound(0)];
                    }
                    else if (att.Name.Equals("msDS-LogonTimeSyncInterval", StringComparison.OrdinalIgnoreCase))
                    {
                        var guidBytes = Array.ConvertAll(att.ByteValue, (a) => (byte)a);
                        val = Convert.ToInt64(guidBytes[0]);
                    }
                    else
                    {
                        if (att.size() == 1)
                        {
                            val = att.StringValue;
                        }
                        else
                        {
                            val = att.StringValueArray;
                        }
                    }
                    ret.Add(att.Name, val);
                }
            } finally {
            }
            return(ret);
        }
Esempio n. 4
0
		public static IDictionary<string, object> GetProperties (string host, int port, string dn, string username, string password, string[] properties)
		{
			var ret = new Dictionary<string, object> ();
			try {
				var cn = new Novell.Directory.Ldap.LdapConnection ();
				cn.Connect (host, port);
				if (string.IsNullOrEmpty (dn)) dn = "";
				cn.Bind (username, password, Novell.Directory.Ldap.AuthenticationTypes.Secure | Novell.Directory.Ldap.AuthenticationTypes.ServerBind | Novell.Directory.Ldap.AuthenticationTypes.Signing | Novell.Directory.Ldap.AuthenticationTypes.FastBind);
				var results = cn.Search (dn, Novell.Directory.Ldap.LdapConnection.SCOPE_BASE, null, properties, false);
				var item = results.next ();
				var props = item.getAttributeSet ();
				foreach(Novell.Directory.Ldap.LdapAttribute att in props) {
					object val = null;
					if (att.Name.Equals ("objectsid", StringComparison.OrdinalIgnoreCase)) {
						val = Array.ConvertAll (att.ByteValue, (a) => (byte)a);
					}
					else if (att.Name.Equals ("objectGUID", StringComparison.OrdinalIgnoreCase)) {
						var guidBytes = Array.ConvertAll (att.ByteValue, (a) => (byte)a);
						val = new Guid?(new Guid(guidBytes));
					}
					else if (att.Name.Equals ("objectClass", StringComparison.OrdinalIgnoreCase)) {
						val = att.StringValueArray[att.StringValueArray.GetUpperBound (0)];
					}
					else if (att.Name.Equals ("msDS-LogonTimeSyncInterval", StringComparison.OrdinalIgnoreCase)) {
						var guidBytes = Array.ConvertAll (att.ByteValue, (a) => (byte)a);
						val = Convert.ToInt64 (guidBytes[0]);
					}
					else {
						if (att.size () == 1) {
							val = att.StringValue;
						} else {
							val = att.StringValueArray;
						}
					}
					ret.Add (att.Name, val);
				}
			} finally {

			}
			return ret;
		}
        private async Task <bool> ExecLdapAuthAsync(string username, string password)
        {
            var  host         = "jb.com"; // Host
            var  bindDN       = "cn=admin,dc=example,dc=org";
            var  bindPassword = "******";
            var  baseDC       = "dc=example,dc=org";
            bool isAuthorized = false;

            try
            {
                isAuthorized = await Task.Run(() =>
                {
                    using (var connection = new Novell.Directory.Ldap.LdapConnection())
                    {
                        connection.Connect(host, Novell.Directory.Ldap.LdapConnection.DEFAULT_PORT);
                        connection.Bind(bindDN, bindPassword);

                        var searchFilter = $"(&(objectClass=person)(uid={username}))";
                        var entities     = connection.Search(
                            baseDC,
                            Novell.Directory.Ldap.LdapConnection.SCOPE_SUB,
                            searchFilter,
                            new string[] { "uid", "cn", "mail" },
                            false);

                        string userDn = null;

                        while (entities.hasMore())
                        {
                            var entity  = entities.next();
                            var account = entity.getAttribute("uid");
                            if (account != null && account.StringValue == username)
                            {
                                userDn = entity.DN;
                                break;
                            }
                        }

                        if (string.IsNullOrWhiteSpace(userDn))
                        {
                            return(false);
                        }

                        try
                        {
                            connection.Bind(userDn, password);
                            return(connection.Bound);
                        }
                        catch (System.Exception)
                        {
                            return(false);
                        }
                    }
                });

                return(isAuthorized);
            }
            catch (Novell.Directory.Ldap.LdapException e)
            {
                throw e;
            }
        }
Esempio n. 6
0
        // TODO: Check if this is correct...
        internal static bool LdapAuth(string userName, string password, string m_Auth_LDAP_Server, string m_Auth_LDAP_DN)
        {
            // https://www.novell.com/support/kb/doc.php?id=3449660
            if (string.IsNullOrEmpty(password))
            {
                return(false);
            }

            try
            {
                string dn = m_Auth_LDAP_DN.Replace("%user", userName);

                int num = 389; // LDAP: 389, LDAPS: 636

                if (m_Auth_LDAP_Server.StartsWith("LDAPS://", System.StringComparison.InvariantCultureIgnoreCase))
                {
                    num = 636;
                    m_Auth_LDAP_Server = m_Auth_LDAP_Server.Substring(8);
                }
                else if (m_Auth_LDAP_Server.StartsWith("LDAP://", System.StringComparison.InvariantCultureIgnoreCase))
                {
                    num = 389;
                    m_Auth_LDAP_Server = m_Auth_LDAP_Server.Substring(7);
                }

                int pos = m_Auth_LDAP_Server.IndexOf(':');
                if (pos != -1 && (m_Auth_LDAP_Server.Length > pos))
                {
                    string strNum = m_Auth_LDAP_Server.Substring(pos + 1);
                    int    temp   = 0;

                    if (int.TryParse(strNum, out temp))
                    {
                        num = temp;
                    }

                    m_Auth_LDAP_Server = m_Auth_LDAP_Server.Substring(0, pos);
                }


                using (Novell.Directory.Ldap.LdapConnection conn =
                           new Novell.Directory.Ldap.LdapConnection())
                {
                    // System.Console.WriteLine("Connecting to:" + ldapHost);
                    conn.Connect(m_Auth_LDAP_Server, num);
                    conn.Bind(3, dn, password);

                    // System.Console.WriteLine(" Bind Successfull");
                    conn.Disconnect();
                }

                return(true);
            }
            catch (Novell.Directory.Ldap.LdapException e)
            {
                // System.Console.WriteLine("Error:" + e.LdapErrorMessage);
            }
            catch (System.Exception e)
            {
                // System.Console.WriteLine("Error:" + e.Message);
            }

            return(false);



            /*
             * // using System.DirectoryServices.Protocols;
             * bool validated = false;
             *
             * try
             * {
             *  string dn = m_Auth_LDAP_DN.Replace("%user", userName);
             *
             *  using (LdapConnection ldap = new LdapConnection(new LdapDirectoryIdentifier(m_Auth_LDAP_Server), new System.Net.NetworkCredential(dn, password), System.DirectoryServices.Protocols.AuthType.Basic))
             *  {
             *      ldap.SessionOptions.ProtocolVersion = 3;
             *      ldap.Bind();
             *  }
             *
             *
             *
             *  validated = true;
             * }
             * catch
             * {
             * }
             *
             * return validated;
             */
        }
Esempio n. 7
0
		public void TestLDAPConnectionRefused()
		{
			Novell.Directory.Ldap.LdapConnection connection = new Novell.Directory.Ldap.LdapConnection();
			connection.Connect("localhost", 0);
		}
Esempio n. 8
0
        } // End Function GetLdap

        public static void GetExchange()
        {
            System.Collections.Generic.List <ARSoft.Tools.Net.Dns.SrvRecord> lsLdap = GetLdap();
            ARSoft.Tools.Net.Dns.SrvRecord ldap = lsLdap[0];

            string[] attrs = new string[] { "cn", "distinguishedName", "sAMAccountName", "userPrincipalName"
                                            , "displayName", "givenName", "sn", "mail", "mailNickname"
                                            , "memberOf", "homeDirectory", "msExchUserCulture" };

            // CN = Common Name
            // OU = Organizational Unit
            // DC = Domain Component

            // cn                 Patrick Zihlmann
            // distinguishedName  CN=Patrick Zihlmann,OU=Benutzer,OU=MY_DOMAIN,DC=my_domain,DC=local
            // sAMAccountName	  Patrick.Zihlmann
            // userPrincipalName  [email protected]
            // displayName	      Patrick Zihlmann
            // givenName          Patrick
            // sn                 Zihlmann
            // mail               [email protected]
            // mailNickname       Patrick.Zihlmann
            // memberOf           CN=CS_ALL,OU=Groups,OU=Sample,DC=my_domain,DC=local
            // homeDirectory      \\dom-data01\user$\firstname.lastname

            // objectClass	top
            // objectClass	person
            // objectClass	organizationalPerson
            // objectClass	user

            // msExchUserCulture	de-CH

            // string searchFilter = "(&(objectClass=msExchExchangeServer))";
            // string searchFilter = "(&(objectClass=msExchExchangeServer)(msExchServerSite =$((GetADSite-Name $ADSite)))";
            string searchFilter = "(&(objectClass=msExchExchangeServer)(msExchServerSite=CN=COR-ERLEN,CN=Sites,CN=Configuration,DC=cor,DC=local))";


            string ldapHost = MySamples.TestSettings.ldapHost;
            int    ldapPort = MySamples.TestSettings.ldapPort; //System.Convert.ToInt32(args[1]);
            string loginDN  = MySamples.TestSettings.loginDN;  // args[2];
            string password = MySamples.TestSettings.password; // args[3];


            Novell.Directory.Ldap.LdapConnection lc = new Novell.Directory.Ldap.LdapConnection();
            int ldapVersion = Novell.Directory.Ldap.LdapConnection.Ldap_V3;

            try
            {
                // connect to the server
                lc.Connect(ldap.Target.ToString(), ldap.Port);

                // bind to the server
                lc.Bind(ldapVersion, loginDN, password);

                Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
                cons.ReferralFollowing = true;
                lc.Constraints         = cons;

                string searchBase = "CN=Configuration,DC=MY_DOMAIN,DC=local";
                searchBase = GetConfigurationNamingContext(lc);

                // To enable referral following, use LDAPConstraints.
                // setReferralFollowing passing
                //  -- TRUE to enable referrals, or
                //  -- FALSE(default) to disable referrals.
                Novell.Directory.Ldap.LdapSearchResults lsc = lc.Search(searchBase,
                                                                        Novell.Directory.Ldap.LdapConnection.SCOPE_SUB,
                                                                        searchFilter,
                                                                        attrs,
                                                                        false,
                                                                        (Novell.Directory.Ldap.LdapSearchConstraints)null);

                while (lsc.HasMore())
                {
                    Novell.Directory.Ldap.LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.Next();
                    } // End Try
                    catch (Novell.Directory.Ldap.LdapReferralException eR)
                    {
                        // https://stackoverflow.com/questions/46052873/ldap-referal-error
                        // The response you received means that the directory you are requesting does not contain the data you look for,
                        // but they are in another directory, and in the response there is the information about the "referral" directory
                        // on which you need to rebind to "redo" the search.This principle in LDAP are the referral.
                        // https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bp31k5d.html
                        // To enable referral following, use LDAPConstraints.setReferralFollowing passing TRUE to enable referrals, or FALSE (default) to disable referrals.

                        // are you sure your bind user meaning
                        // auth.impl.ldap.userid=CN=DotCMSUser,OU=Service Accounts,DC=mycompany,DC=intranet
                        // auth.impl.ldap.password = mypassword123
                        // has permissions to the user that is logging in and its groups?
                        System.Diagnostics.Debug.WriteLine(eR.LdapErrorMessage);
                    } // End Catch
                    catch (Novell.Directory.Ldap.LdapException e)
                    {
                        // WARNING: Here catches only LDAP-Exception, no other types...
                        System.Console.WriteLine("Error: " + e.LdapErrorMessage);
                        // Exception is thrown, go for next entry
                        continue;
                    } // End Catch


                    // https://ingogegenwarth.wordpress.com/2015/01/14/get-exchange-server-via-ldap/
                    // https://serverfault.com/questions/77954/finding-dns-name-of-exchange-server-for-user-using-ldap

                    Novell.Directory.Ldap.LdapAttribute atDN = nextEntry.getAttribute("distinguishedName");
                    Novell.Directory.Ldap.LdapAttribute atCN = nextEntry.getAttribute("cn");



                    if (atCN != null)
                    {
                        System.Console.WriteLine(atCN.StringValue);
                    }


                    if (atDN != null)
                    {
                        System.Console.WriteLine(atDN.StringValue);
                        Novell.Directory.Ldap.LdapEntry     entry = lc.Read(atDN.StringValue);
                        Novell.Directory.Ldap.LdapAttribute atNA  = entry.getAttribute("networkAddress");

                        if (atNA != null)
                        {
                            foreach (var s in atNA.StringValueArray)
                            {
                                if (!s.StartsWith("ncacn_ip_tcp:", System.StringComparison.InvariantCultureIgnoreCase))
                                {
                                    continue;
                                }

                                string dnsName = s.Substring("ncacn_ip_tcp:".Length);
                                System.Console.WriteLine(dnsName);
                                break;
                            }
                        }
                    }


                    System.Console.WriteLine("\r\n" + nextEntry.DN);
                    Novell.Directory.Ldap.LdapAttributeSet attributeSet = nextEntry.getAttributeSet();

                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        Novell.Directory.Ldap.LdapAttribute attribute = (Novell.Directory.Ldap.LdapAttribute)ienum.Current;
                        string attributeName = attribute.Name;
                        string attributeVal  = attribute.StringValue;
                        System.Console.WriteLine(attributeName + "value:" + attributeVal);
                    } // End while (ienum.MoveNext())
                }     // End while (lsc.HasMore())
            }         // End Try
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            } // End Catch
            finally
            {
                // disconnect with the server
                lc?.Disconnect();
            } // End Finally
        }     // End Function GetExchange
Esempio n. 9
0
        } // End Function GetDefaultNamingContext

        private static string GetDnsHostName(Novell.Directory.Ldap.LdapConnection conn)
        {
            return(GetScalarContext(conn, "dnsHostName	"));
        } // End Function GetDnsHostName
Esempio n. 10
0
        } // End Function GetConfigurationNamingContext

        private static string GetDefaultNamingContext(Novell.Directory.Ldap.LdapConnection conn)
        {
            return(GetScalarContext(conn, "defaultNamingContext"));
        } // End Function GetDefaultNamingContext
Esempio n. 11
0
        }     // End Function GetUsers

        public static void GetGroups()
        {
            System.Collections.Generic.List <ARSoft.Tools.Net.Dns.SrvRecord> lsLdap = GetLdap();
            ARSoft.Tools.Net.Dns.SrvRecord ldap = lsLdap[0];

            string[] attrs = new string[] { "cn", "sAMAccountName", "distinguishedName", "member" };

            // cn                 Exchange Servers
            // sAMAccountName     Exchange Servers
            // distinguishedName  CN=Exchange Servers,OU=Microsoft Exchange Security Groups,DC=my_domain,DC=local
            // member             CN=MYDOMAIN-EXCHANGE,CN=Computers,DC=my_domain,DC=local
            // name               Exchange Servers


            string searchFilter = "(objectCategory=group)";

            string ldapHost = MySamples.TestSettings.ldapHost;
            int    ldapPort = MySamples.TestSettings.ldapPort; //System.Convert.ToInt32(args[1]);
            string loginDN  = MySamples.TestSettings.loginDN;  // args[2];
            string password = MySamples.TestSettings.password; // args[3];

            int ldapVersion = Novell.Directory.Ldap.LdapConnection.Ldap_V3;

            Novell.Directory.Ldap.LdapConnection lc = null;

            try
            {
                lc = new Novell.Directory.Ldap.LdapConnection();

                // connect to the server
                lc.Connect(ldap.Target.ToString(), ldap.Port);
                // bind to the server
                lc.Bind(ldapVersion, loginDN, password);


                Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
                cons.ReferralFollowing = true;
                lc.Constraints         = cons;

                string searchBase = "DC=MY_DOMAIN,DC=local";
                searchBase = GetDefaultNamingContext(lc);

                Novell.Directory.Ldap.LdapSearchResults lsc = lc.Search(searchBase,
                                                                        Novell.Directory.Ldap.LdapConnection.SCOPE_SUB,
                                                                        searchFilter,
                                                                        attrs,
                                                                        false,
                                                                        (Novell.Directory.Ldap.LdapSearchConstraints)null);

                while (lsc.HasMore())
                {
                    Novell.Directory.Ldap.LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.Next();
                    }
                    catch (Novell.Directory.Ldap.LdapException e)
                    {
                        System.Console.WriteLine("Error: " + e.LdapErrorMessage);
                        // Exception is thrown, go for next entry
                        continue;
                    } // End Catch

                    Novell.Directory.Ldap.LdapAttribute attMember = nextEntry.getAttribute("member");
                    if (attMember != null)
                    {
                        foreach (string usr_cn in attMember.StringValueArray)
                        {
                            System.Console.WriteLine(" -- " + usr_cn);
                            // CN refers to:
                            // Novell.Directory.Ldap.LdapEntry cn = lc.Read(usr_cn);
                            // System.Console.WriteLine(cn);
                        } // Next usr_cn
                    }     // End if (attMember != null)

                    System.Console.WriteLine("\r\n" + nextEntry.DN);
                    Novell.Directory.Ldap.LdapAttributeSet attributeSet = nextEntry.getAttributeSet();

                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        Novell.Directory.Ldap.LdapAttribute attribute = (Novell.Directory.Ldap.LdapAttribute)ienum.Current;
                        string attributeName = attribute.Name;
                        string attributeVal  = attribute.StringValue;
                        System.Console.WriteLine(attributeName + "value:" + attributeVal);
                    } // End while (ienum.MoveNext())
                }     // End while (lsc.HasMore())
            }         // End Try
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            } // End Catch
            finally
            {
                // disconnect with the server
                lc?.Disconnect();
            } // End Finally
        }     // End Function GetGroups
Esempio n. 12
0
 public void TestLDAPConnectionRefused()
 {
     Novell.Directory.Ldap.LdapConnection connection = new Novell.Directory.Ldap.LdapConnection();
     connection.Connect("localhost", 0);
 }