Пример #1
0
        public void LdapModify_AddAttribute_Failure()
        {
            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            Assert.IsNotNull(ldapConnection);

            ldapConnection.LdapSimpleBindS(myDN, password);

            string basedn = "cn=lModAdd,cn=Users,dc=vsphere,dc=local";

            LdapMod[] lMods = new LdapMod[1];

            lMods[0] = new LdapMod((int)LdapMod.mod_ops.LDAP_MOD_ADD, "cn", new string[] { "Allen", null });


            try
            {
                ldapConnection.ModifyObject(basedn, lMods);
                Assert.Fail();
            }
            catch
            {
                //Expected Exception
            }
        }
Пример #2
0
        public static void LdapSearch_SASLBind_Failure()
        {
            ILdapMessage msg = null;

            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            Assert.IsNotNull(ldapConnection);

            try
            {
                ldapConnection.VmDirSafeLDAPBind(hostName, upn, password);
                msg = ldapConnection.LdapSearchExtS("", 2, filter_F, null, 1, IntPtr.Zero, 0);
            }
            catch
            {
                Assert.Fail();
            }

            List <ILdapEntry> entries = msg.GetEntries();

            if (entries.Count != 0)
            {
                Assert.Fail();
            }

            try
            {
                ldapConnection.LdapUnbindS();
            }
            catch
            {
                Assert.Fail();
            }
        }
Пример #3
0
        object getUserGroupsByYserNameGroup(string userName, ILdapConnection ldapConn)
        {
            ///var ldapConn = GetConnection();
            var users = new HashSet <string>();
            //My domain have 4 DC's
            var searchResults = ldapConn.Search(
                string.Empty,            //You can use String.Empty for all domain search. This is example about users
                LdapConnection.ScopeSub, //Use SUB
                string.Empty,            // Example of filtering with *. You can use String.Empty to query without filtering
                null,                    // no specified attributes
                false                    // return attr and value
                );

            while (searchResults.HasMore())
            {
                var nextEntry = searchResults.Next();
                nextEntry.GetAttributeSet();
                var attr = nextEntry.GetAttribute("mail");

                if (attr == null)
                {
                    users.Add(nextEntry.GetAttribute("distinguishedName").StringValue);
                }
                else
                {
                    users.Add(nextEntry.GetAttribute("mail").StringValue);
                }
            }

            return(users);
        }
Пример #4
0
        public static void ConnectI(this ILdapConnection connection, string unixSocketPath = "",
                                    LdapVersion version = LdapVersion.LDAP_VERSION3)
        {
            var encoded = HttpUtility.UrlEncode(unixSocketPath, Encoding.UTF8);

            connection.Connect($"{LdapSchema.LDAPI.ToString()}://{encoded}/", version);
        }
Пример #5
0
        public static void Ldap_Delete_Failure()
        {
            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            Assert.IsNotNull(ldapConnection);

            try
            {
                ldapConnection.LdapSimpleBindS(myDN, password_F);
                Assert.Fail();
            }
            catch
            {
                // Expected Exception.Invalid Password
            }

            try
            {
                ldapConnection.DeleteObject(basedn_F);
                Assert.Fail();
            }
            catch
            {
                // Expected Exception Due to Invalid Bind
            }
        }
Пример #6
0
 public void Delete <T>(T entity) where T : ILdapEntity
 {
     using (ILdapConnection connection = Connect())
     {
         connection.Delete(entity.DistinguishedName);
     }
 }
Пример #7
0
 public void Update <T>(T entity, IEnumerable <LdapModification> modifications) where T : ILdapEntity
 {
     using (ILdapConnection connection = Connect())
     {
         connection.Modify(entity.DistinguishedName, modifications.ToArray());
     }
 }
        public static List <T> SearchUsingVlv <T>(
            [NotNull] this ILdapConnection ldapConnection,
            [NotNull] LdapSortControl sortControl,
            [NotNull] Func <LdapEntry, T> converter,
            [NotNull] SearchOptions options,
            int pageSize)
        {
            if (ldapConnection == null)
            {
                throw new ArgumentNullException(nameof(ldapConnection));
            }

            if (sortControl == null)
            {
                throw new ArgumentNullException(nameof(sortControl));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (pageSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pageSize));
            }

            return(new VirtualListViewControlHandler(ldapConnection)
                   .SearchUsingVlv(sortControl, converter, options, pageSize));
        }
Пример #9
0
 public void Delete(string distinguishedName)
 {
     using (ILdapConnection connection = Connect())
     {
         connection.Delete(distinguishedName);
     }
 }
        public static Task <List <T> > SearchUsingSimplePagingAsync <T>(
            [NotNull] this ILdapConnection ldapConnection,
            [NotNull] Func <LdapEntry, T> converter,
            [NotNull] SearchOptions options,
            int pageSize,
            CancellationToken cancellationToken = default)
        {
            if (ldapConnection == null)
            {
                throw new ArgumentNullException(nameof(ldapConnection));
            }

            if (converter == null)
            {
                throw new ArgumentNullException(nameof(converter));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(new SimplePagedResultsControlHandler(ldapConnection)
                   .SearchWithSimplePagingAsync(converter, options, pageSize, cancellationToken));
        }
Пример #11
0
        public void LdapSearch_SimpleBind_Failure()
        {
            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            Assert.IsNotNull(ldapConnection);

            ldapConnection.LdapSimpleBindS(myDN, password);

            ILdapMessage msg = ldapConnection.LdapSearchExtS("", 2, filter_F, null, 1, IntPtr.Zero, 0);

            Assert.IsNotNull(msg);

            List <ILdapEntry> entries = msg.GetEntries();

            if (entries.Count != 0)
            {
                Assert.Fail();
            }

            try
            {
                ldapConnection.LdapUnbindS();
            }
            catch
            {
                Assert.Fail();
            }
        }
Пример #12
0
        protected virtual async void UpdateUserFromLdapConnection(ILdapConnection ldapConnection, User user, string userNameOrEmailAddress, Tenant tenant)
        {
            var searchFilter = await CreateSearchFilter(userNameOrEmailAddress, tenant);

            var attrs = new string[] { "sAMAccountName", "mail", "sn" };

            var entities = ldapConnection.Search(await _settings.GetContainer(tenant?.Id), LdapConnection.SCOPE_SUB, searchFilter, attrs, false);

            while (entities.HasMore())
            {
                var entity  = entities.Next();
                var account = entity.getAttribute("sAMAccountName");
                if (account != null && account.StringValue == userNameOrEmailAddress)
                {
                    if (entity.getAttribute("sAMAccountName") != null && !entity.getAttribute("sAMAccountName").StringValue.IsNullOrEmpty())
                    {
                        user.UserName = entity.getAttribute("sAMAccountName").StringValue;
                        user.Name     = entity.getAttribute("sAMAccountName").StringValue;
                    }

                    user.Surname = entity.getAttribute("sn") != null?entity.getAttribute("sn").StringValue : user.Surname;

                    user.EmailAddress = entity.getAttribute("mail") != null?entity.getAttribute("mail").StringValue : user.EmailAddress;

                    break;
                }
            }
        }
        public static Task <List <LdapEntry> > SearchUsingVlvAsync(
            [NotNull] this ILdapConnection ldapConnection,
            [NotNull] LdapSortControl sortControl,
            [NotNull] SearchOptions options,
            int pageSize,
            CancellationToken cancellationToken = default)
        {
            if (ldapConnection == null)
            {
                throw new ArgumentNullException(nameof(ldapConnection));
            }

            if (sortControl == null)
            {
                throw new ArgumentNullException(nameof(sortControl));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (pageSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pageSize));
            }

            return(new VirtualListViewControlHandler(ldapConnection)
                   .SearchUsingVlvAsync(sortControl, options, pageSize, cancellationToken));
        }
Пример #14
0
        public static async Task <IList <LdapEntry> > SearchBySidAsync(this ILdapConnection connection, string @base,
                                                                       string sid, LdapSearchScope scope = LdapSearchScope.LDAP_SCOPE_SUBTREE)
        {
            var hex = HexEscaper.Escape(LdapSidConverter.ConvertToHex(sid));

            return(await connection.SearchAsync(@base, $"(objectSID={hex})", scope : scope));
        }
Пример #15
0
        public static void Ldap_Delete_SASL_Failure()
        {
            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            Assert.IsNotNull(ldapConnection);

            try
            {
                ldapConnection.VmDirSafeLDAPBind(hostName, upn, password_F);
                Assert.Fail();
            }
            catch
            {
                // Expected Exception.Invalid Password
            }

            try
            {
                ldapConnection.DeleteObject(basedn_F);
                Assert.Fail();
            }
            catch
            {
                // Expected Exception Due To Invalid SASL Bind.
            }
        }
Пример #16
0
        public static void RunTests(Credentials cred)
        {
            System.Console.WriteLine("Running modify tests ...");

            myDN       = cred.myDN;
            hostName   = cred.hostName;
            upn        = cred.upn;
            password   = cred.password;
            portNumber = cred.portNumber;

            //False credentials
            myDN_F       = cred.myDN_F;
            hostName_F   = cred.hostName_F;
            upn_F        = cred.upn_F;
            password_F   = cred.password_F;
            portNumber_F = cred.portNumber_F;

            ldapConnection = LdapConnection.LdapInit(hostName, portNumber);
            Assert.IsNotNull(ldapConnection);

            ldapConnection.LdapSimpleBindS(myDN, password);
            LdapUser user = LdapUser.CreateRandomUser(ldapConnection);

            LdapModify_AddAttribute_Success(ldapConnection, user);
            LdapModify_AddAttribute_Failure(ldapConnection, user);
            LdapModify_ReplaceAttribute_Success(ldapConnection, user);
            LdapModify_DeleteAttribute_Success(ldapConnection, user);
        }
Пример #17
0
        public static void RunTests(Credentials cred)
        {
            System.Console.WriteLine("Running add tests ...");

            myDN       = cred.myDN;
            hostName   = cred.hostName;
            upn        = cred.upn;
            password   = cred.password;
            portNumber = cred.portNumber;

            //False credentials
            myDN_F       = cred.myDN_F;
            hostName_F   = cred.hostName_F;
            upn_F        = cred.upn_F;
            password_F   = cred.password_F;
            portNumber_F = cred.portNumber_F;

            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            ldapConnection.LdapSimpleBindS(myDN, password);

            LdapUser user = LdapUser.CreateRandomUser(ldapConnection);

            ILdapConnection ldapConnectionSASL = LdapConnection.LdapInit(hostName, portNumber);

            ldapConnectionSASL.VmDirSafeLDAPBind(hostName, upn, password);

            string UserName     = Guid.NewGuid().ToString("N");
            string UserNameSASL = Guid.NewGuid().ToString("N");

            Ldap_Add_Object_Success(ldapConnection, UserName);
            Ldap_Add_Object_SASL_Success(ldapConnectionSASL, UserNameSASL);
            Ldap_Add_Object_Failure(ldapConnection, UserName);
            Ldap_Add_Object_SASL_Failure(ldapConnectionSASL, UserNameSASL);
        }
Пример #18
0
        private void GetUserDetails(ILdapConnection ldapConnection, AppUser appUser, string username)
        {
            var searchFilter =
                string.Format("(&(objectClass=user)(objectClass=person)(sAMAccountName={0}))", username);

            var result = ldapConnection.Search(
                _config.Dn,
                LdapConnection.SCOPE_SUB,
                searchFilter,
                new[]
            {
                MemberOfAttribute, DisplayNameAttribute, SamAccountNameAttribute, EmailAddressAttribute
            },
                false
                );

            var user = result.next();

            if (user != null)
            {
                appUser.DisplayName  = user.getAttribute(DisplayNameAttribute).StringValue;
                appUser.Username     = user.getAttribute(SamAccountNameAttribute).StringValue;
                appUser.Roles        = user.getAttribute(MemberOfAttribute).StringValueArray;
                appUser.EmailAddress = user.getAttribute(EmailAddressAttribute).StringValue;
            }
        }
Пример #19
0
        public static LdapEntry GetRootDse(this ILdapConnection connection)
        {
            var result = connection.Search(null, "(objectclass=*)",
                                           new[]
            {
                "namingContexts", "subschemaSubentry", "supportedLDAPVersion", "supportedSASLMechanisms",
                "supportedExtension", "supportedControl", "supportedFeatures", "vendorName", "vendorVersion"
            }, LdapSearchScope.LDAP_SCOPE_BASE)
                         .FirstOrDefault();

            if (result == null)
            {
                return(null);
            }

            var rootDse = connection.Search(null, "(objectclass=*)", scope: LdapSearchScope.LDAP_SCOPE_BASE).First();

            foreach (var attribute in rootDse.DirectoryAttributes)
            {
                var index = result.DirectoryAttributes.IndexOf(attribute);
                if (index != -1)
                {
                    result.DirectoryAttributes.RemoveAt(index);
                }
                result.DirectoryAttributes.Add(attribute);
            }

            return(result);
        }
Пример #20
0
        public void Ldap_Add_Object_SASL_Success()
        {
            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            Assert.IsNotNull(ldapConnection);

            ldapConnection.VmDirSafeLDAPBind(hostName, upn, password);

            string basedn = "cn=ExampleAddSasl,cn=Users,dc=vsphere,dc=local";

            LdapMod[] lMods = new LdapMod[3];

            lMods[0] = new LdapMod((int)LdapMod.mod_ops.LDAP_MOD_ADD, "cn", new string[] { "ExampleAddSasl", null });

            lMods[1] = new LdapMod(0, "objectClass", new string[] { "person", null });

            lMods[2] = new LdapMod(0, "sn", new string[] { "Allen", null });

            try
            {
                ldapConnection.AddObject(basedn, lMods);
            }
            catch
            {
                Assert.Fail();
            }
        }
Пример #21
0
        public static async Task <string> WhoAmI(this ILdapConnection connection, CancellationToken ct = default)
        {
            var response =
                (ExtendedResponse)await connection.SendRequestAsync(new ExtendedRequest("1.3.6.1.4.1.4203.1.11.3"),
                                                                    ct);

            return(Utils.Encoder.Instance.GetString(response.ResponseValue));
        }
Пример #22
0
 protected virtual async Task AuthenticateLdapConnectionAsync(ILdapConnection connection, string username, string password)
 {
     await connection.BindAsync(Native.LdapAuthType.Simple, new LdapCredential()
     {
         UserName = username,
         Password = password
     });
 }
Пример #23
0
 public void Add <T>(T entity) where T : ILdapEntity
 {
     using (ILdapConnection connection = Connect())
     {
         var entry = entity.ToNovellEntry(_mapper);
         connection.Add(entry);
     }
 }
Пример #24
0
        private static void ChangePasswordReplace(string newPassword, ILdapConnection ldap, string userDN)
        {
            // If you don't have the rights to Add and/or Delete the Attribute, you might have the right to change the password-attribute.
            // In this case uncomment the next 2 lines and comment the region 'Change Password by Delete/Add'
            var attribute   = new LdapAttribute("userPassword", newPassword);
            var ldapReplace = new LdapModification(LdapModification.REPLACE, attribute);

            ldap.Modify(userDN, new[] { ldapReplace }); // Change with Replace
        }
Пример #25
0
        public async Task LoadChildren(ILdapConnection connection, CancellationToken cancellationToken)
        {
            this.Events = await connection.Read <OrgUnit>($"cn=events,{this.Dn}", cancellationToken);

            this.Groups = await connection.Read <OrgUnit>($"cn=groups,{this.Dn}", cancellationToken);

            this.Tribes = await connection.Read <OrgUnit>($"cn=tribes,{this.Dn}", cancellationToken);

            this.VotedGroups = await connection.Read <OrgUnit>($"cn=voted_groups,{this.Dn}", cancellationToken);
        }
Пример #26
0
        public async Task LoadChildren(ILdapConnection connection, CancellationToken cancellationToken = default)
        {
            this.Sl = await connection.Read <TribeSl>($"cn={this.Id}_sl,{this.Dn}", cancellationToken);

            this.Gs = await connection.Read <TribeGs>($"cn={this.Id}_gs,{this.Dn}", cancellationToken);

            this.Lr = await connection.Read <TribeLr>($"cn={this.Id}_lr,{this.Dn}", cancellationToken);

            this.Lv = await connection.Read <TribeLv>($"cn={this.Id}_lv,{this.Dn}", cancellationToken);
        }
        /// <summary>
        /// Get some common Attributes from the Root DSE.
        /// This is really just a specialized <see cref="LdapSearchRequest"/>
        /// to handle getting some commonly requested information.
        /// </summary>
        public static RootDseInfo GetRootDseInfo(this ILdapConnection conn)
        {
            var searchResults = conn.Search("", LdapConnection.ScopeBase, "(objectClass=*)", new string[] { "*", "supportedExtension" }, false);

            if (searchResults.HasMore())
            {
                var sr = searchResults.Next();
                return(new RootDseInfo(sr));
            }
            return(null);
        }
Пример #28
0
 public static void LdapConnect_Init_Failure()
 {
     try
     {
         ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName_F, portNumber_F);
         ldapConnection.LdapSimpleBindS(myDN, password);
         Assert.Fail();
     }
     catch (Exception)
     {
     }
 }
Пример #29
0
        public static void LdapSearch_SASLBind_Success()
        {
            ILdapMessage msg = null;

            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            Assert.IsNotNull(ldapConnection);

            try
            {
                ldapConnection.VmDirSafeLDAPBind(hostName, upn, password);
                msg = ldapConnection.LdapSearchExtS("", 2, filter, null, 1, IntPtr.Zero, 0);
            }
            catch
            {
                Assert.Fail();
            }

            List <ILdapEntry> entries = msg.GetEntries();

            foreach (LdapEntry entry in entries)
            {
                string dn = entry.getDN();
                Assert.IsNotNull(dn);

                List <string> attributeNames = entry.getAttributeNames();
                Assert.IsNotNull(attributeNames);

                foreach (string attributeName in attributeNames)
                {
                    List <LdapValue> attributeValues = entry.getAttributeValues(attributeName);
                    Assert.IsNotNull(attributeValues);

                    foreach (LdapValue attributeValue in attributeValues)
                    {
                        if (attributeName == attribute)
                        {
                            Assert.IsTrue(attributeValue.StringValue == value);
                        }
                    }
                }
            }

            try
            {
                ldapConnection.LdapUnbindS();
            }
            catch
            {
                Assert.Fail();
            }
        }
Пример #30
0
        public static void LdapConnect_Simple_Bind_Failure()
        {
            ILdapConnection ldapConnection = LdapConnection.LdapInit(hostName, portNumber);

            try
            {
                ldapConnection.LdapSimpleBindS(myDN_F, password_F);
                Assert.Fail();
            }
            catch (Exception)
            {
            }
        }
        //returns 1 if success and 0 if failure
        public  int CreateConnection ()
        {
            try {
                ldConn = new LdapConnection ();
                if (ldConn == null)
                    throw new Exception ("Ldap Connection is null");

                bool isServerReachable = CheckServerReachability (this.server, LDAPOption.LDAP_PORT, VMDirConstants.SERVERTIMEOUT_IN_MILLI);
                if (isServerReachable == true) {
                    ldConn.VmDirSafeLDAPBind (this.server, this.bindDN, this.password);
                    _schemaManager = new SchemaManager (this);
                    _schemaManager.RefreshSchema ();
                    return 1;
                }
                return 0;

            } catch (Exception e) {
                return 0; 
            }
        }